//! The board as four columns, redrawn when the tree underneath it moves. //! //! Modelled on frig's TUI: event poll on a short timeout so timed work still runs when //! nobody is typing, state refreshed on a tick, and the terminal restored whatever //! happens. //! //! **Read only.** Moving a card by keypress is a follow-up. Everything here observes. use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime}; use anyhow::{Context, Result}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use ratatui::Frame; use ratatui::layout::{Constraint, Direction, Layout, Margin, Rect, Size}; use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span, Text}; use ratatui::widgets::{Block, Borders, Clear, Paragraph, Tabs, Wrap}; use crate::campaign::{CAMPAIGNS_DIR, CampaignIndex, Standing}; use crate::handlers::read_comments; use crate::util::*; /// How long the event poll waits before letting the tick run. pub const POLL: Duration = Duration::from_millis(250); /// The tab that throws every monitored board into one set of columns. /// /// Lowercase like the column headings, since it sits in the same row of chrome and is /// a label rather than a sentence. const ALL: &str = "all"; /// The rows of chrome above the columns, which is what the geometry depends on. /// /// A struct rather than two bools threaded through `frame_rows`, `board_area`, /// `card_width` and `column_text_height`: adjacent same-typed parameters are what the /// Rust Style rule in AGENTS.md warns about, and a caller that swapped them would measure /// a board nobody is looking at. Copied from `Board::chrome`, so the draw and the /// keypress measure one answer. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Chrome { /// Whether the tab row is drawn, which is whether more than one board is monitored. pub tabbed: bool, /// Whether the campaign frame is drawn, which is whether a campaign is selected. pub campaign: bool, } impl Chrome { /// The rows the campaign frame takes: a border either side of one row of prose. /// /// Three rather than four, because the frame says the rest of what it has to say on /// its borders: the identity on the top one and the standing on the bottom, the trade /// the detail overlay already makes with its title and its page indicator. Every row /// spent here is a row of cards. const CAMPAIGN_ROWS: u16 = 3; fn campaign_rows(self) -> u16 { match self.campaign { true => Self::CAMPAIGN_ROWS, false => 0, } } } /// One monitored board: where it lives, and what to call it. #[derive(Debug)] pub struct Project { /// The directory holding the `.worklane`, which is what its tab is named after. pub name: String, /// The `.worklane` directory itself. pub dir: PathBuf, } /// The boards to monitor, resolved from the paths given on the command line. /// /// Each path is resolved the way every other command resolves the working directory: /// the first `.worklane` at or above it. No paths at all is the working directory, /// which is what a bare `worklane` has always done. pub fn projects(paths: &[PathBuf], start: &Path) -> Result> { let named = !paths.is_empty(); let wanted: Vec = match named { true => paths.to_vec(), false => vec![start.to_path_buf()], }; let mut projects: Vec = Vec::new(); for path in &wanted { // The path is named in the failure, because with several arguments "No // .worklane directory found" does not say which one of them was wrong. Only // when one was given: a bare `worklane` has no path to name, and prefixing // the working directory would only bury the message every other command gives. let dir = match named { true => find_worklane_dir(path) .with_context(|| format!("no board at or above {}", path.display()))?, false => find_worklane_dir(path)?, }; // Two paths inside one project reach the same board. Monitoring it twice would // draw the same tickets under two tabs and count every change twice. if projects.iter().any(|project| project.dir == dir) { continue; } projects.push(Project { name: project_name(&dir), dir }); } Ok(projects) } /// What a tab is called: the directory holding the `.worklane`. /// /// The board directory is always named `.worklane`, so it is the parent that names the /// project. A `.worklane` with no parent means the filesystem root, and falls back to /// the path so a tab is never blank. fn project_name(dir: &Path) -> String { dir.parent() .and_then(|parent| parent.file_name()) .map(|name| name.to_string_lossy().to_string()) .unwrap_or_else(|| dir.to_string_lossy().to_string()) } /// A ticket as the board holds it, and the project it came from when the view mixes /// several. /// /// The label is `None` on a project's own tab, where the tab name already says it, and /// on a single board, where there is nothing to confuse it with. Set at reload rather /// than asked for at draw time, so nothing has to thread "which tab is this" down into /// the card renderer. pub struct Card { pub ticket: TicketItem, pub project: Option, /// Whether a ticket this one is `blocked by` is on the board and not done. /// /// Decided at reload like `project`, and for a stronger reason: the answer lives on /// two tickets at once, so no card can reach it alone and asking per draw would mean /// reading the tree per frame. Computed on the board the ticket came from and /// carried into the merge unchanged — `relate` resolves its target against one /// `.worklane`, so there is no such thing as a blocker in another project. pub blocked: bool, /// The campaign this ticket is in, as the label the card draws, or `None` for a ticket /// in none. /// /// `TicketItem::campaign` already carries the uuid, off the pass that builds the card. /// What is missing is a name for it, which lives in another directory, so this is /// resolved at reload from the one read of the campaigns index — never per draw, the /// rule `criteria` and `tags` already follow. /// /// A uuid no campaign carries resolves to `None` and the card says nothing, the answer /// `mark_blocked` gives a dangling blocker: a uuid nothing holds is a bookkeeping /// fault rather than a fact about this ticket. Resolved on the board the ticket came /// from and carried into the merge unchanged, for the reason `blocked` is: a campaign /// is addressed inside one `.worklane`, so one project's uuid must never be answered /// by another project's campaign. pub campaign: Option, } /// One status and the cards in it. pub struct Column { pub status: &'static str, pub cards: Vec, } /// A campaign as the board holds it: what the picker lists and what the frame draws. /// /// Read at reload from the one pass over the campaigns directory, the same pass that names /// 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. #[derive(Clone, Debug)] pub struct CampaignRow { pub uuid: String, pub title: String, pub codename: Option, /// The opening line of the description, or empty for a campaign with none. pub summary: String, /// 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. pub project: Option, } impl CampaignRow { /// The campaign as a label, the way a card carrying it is drawn. pub fn label(&self) -> Cell { campaign_label(&self.uuid, self.codename.as_deref()) } } /// One tab: a monitored board, or the merge across all of them. /// /// The selection and the column offsets live here rather than on the board, so /// switching tabs returns to where that tab was left instead of pointing the shared /// indices at whatever ticket happens to sit at the same place in another project. pub struct Tab { pub name: String, pub columns: Vec, pub column: usize, pub card: usize, /// First visible line of each column, counted in card lines. Parallel to /// `columns`, so a tick that reshapes the board resizes it in step. pub offsets: Vec, /// The campaigns this tab can be filtered to: the ones on its own board, or every /// board's on the merge. Rebuilt at reload beside the columns. pub campaigns: Vec, /// The uuid of the campaign the columns are filtered to, or `None` for the whole board. /// /// Per tab rather than on the `Board`, the way the selection is. A campaign belongs to /// one `.worklane`, so a filter carried across to another project's tab would empty it /// and say nothing about why. pub campaign: Option, } impl Tab { fn new(name: String) -> Self { Tab { name, columns: Vec::new(), column: 0, card: 0, offsets: Vec::new(), campaigns: Vec::new(), campaign: None, } } /// The selected campaign, or nothing when the tab is showing the whole board. /// /// Looked up by uuid rather than held as an index, so a reload that adds or drops a /// campaign cannot leave the frame pointing at a different one. A selection whose /// campaign has since left the board resolves to nothing, which `reload` then clears. fn selected_campaign(&self) -> Option<&CampaignRow> { let uuid = self.campaign.as_deref()?; 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 /// as indices into either. Taken from where done actually is instead of assuming the /// last slot, with a test pinning done as last so the two cannot drift apart. fn visible(&self, show_done: bool) -> &[Column] { &self.columns[..self.visible_count(show_done)] } fn visible_count(&self, show_done: bool) -> usize { if show_done { return self.columns.len(); } match self.columns.iter().position(|column| column.status == DONE) { Some(index) => index, None => self.columns.len(), } } /// Keep the selection on a card that exists, after the board changes under it. fn clamp(&mut self, show_done: bool) { let visible = self.visible_count(show_done); if visible == 0 { self.column = 0; self.card = 0; return; } self.column = self.column.min(visible - 1); let count = self.columns[self.column].cards.len(); self.card = match count { 0 => 0, count => self.card.min(count - 1), }; } fn selected(&self) -> Option<&Card> { self.columns .get(self.column) .and_then(|column| column.cards.get(self.card)) } } /// What the detail view holds while it is open: the ticket it belongs to, then its /// body and comments as one plain text. /// /// The title travels beside the text rather than inside it, because it does not /// scroll: it names the overlay from the border, where no amount of reading can /// carry it off the screen. #[derive(Debug)] pub struct Detail { pub title: String, pub id: String, /// The project the ticket belongs to, on the All tab only. The overlay covers the /// card that said so, and the id alone is not an address across several boards: /// acting on the ticket means knowing which project to run the command in. pub project: Option, /// The body as the overlay draws it: lines of styled spans, not a string. /// /// Styled here rather than painted into the text, because ratatui draws an escape /// sequence in a paragraph as literal bytes, which is 6d327df. It is also the one /// value the clamp and the draw both measure, so neither can wrap it differently /// from the other. pub body: Text<'static>, } impl Detail { /// The body as plain text, one line per drawn line. /// /// Only the suite asks: it is what an assertion about the body reads, and what shows /// that no escape sequence reached it. Nothing in the draw path needs it, so it is /// not carried alongside the spans where the two could disagree. #[cfg(test)] pub fn plain(&self) -> String { self.body .lines .iter() .map(|line| { line.spans .iter() .map(|span| span.content.as_ref()) .collect::() }) .collect::>() .join("\n") } } /// The open search prompt: what has been typed, and whether the last enter missed. /// /// One field on `Board` rather than a buffer beside a bool saying whether it is open, /// the shape `detail` uses: "the prompt is open" and "what is in it" then cannot /// disagree, and there is no state to reset when it closes. #[derive(Debug, Default)] pub struct Search { pub query: String, /// Set when enter found nothing, cleared by the next edit. The message is about the /// query that missed, so it goes the moment the query changes. pub missed: bool, } /// A line the footer carries in place of the key list until the next keypress. /// /// The board otherwise says everything by drawing it, and a copy leaves nothing on the /// screen to look at: the id was already there and the clipboard is somewhere else. So /// this is the one thing the board has to say in words. /// /// `failed` is "nothing reached the clipboard", not "an error occurred": an empty column /// and a terminal that refused the write are the same answer to the reader, who pressed /// a key and has nothing to paste. Both are drawn in red for the reason `no match` is. #[derive(Debug)] pub struct Notice { pub text: String, pub failed: bool, } impl Notice { fn done(text: impl Into) -> Self { Notice { text: text.into(), failed: false, } } fn failed(text: impl Into) -> Self { Notice { text: text.into(), failed: true, } } } /// The open campaign picker: which row the highlight is on, and where the list is /// scrolled to. /// /// `picker: Option` is the whole mode, the shape `search` and `detail` already /// use: "the picker is open" and "what is highlighted in it" cannot disagree, and closing /// it leaves nothing to reset. The rows are not held here — they are `Tab::campaigns`, /// rebuilt on every tick, so a campaign filed elsewhere appears in an open picker rather /// than in a copy of the list that has gone stale. #[derive(Debug, Default)] pub struct Picker { pub row: usize, /// First visible row, counted in rows, since a picker row is one line. pub offset: u16, } /// What is on screen. pub struct Board { /// The monitored boards as tabs, the merge first when there is more than one. /// Never empty, so `tab` is always a valid index. pub tabs: Vec, pub tab: usize, /// The open detail view, when one is open. pub detail: Option, /// First visible line of the detail view, counted in wrapped lines. pub offset: u16, /// The search prompt while it is open. `None` is the board reading keys as actions. pub search: Option, /// The campaign picker while it is open, on the same terms as `search`. pub picker: Option, /// What the last action said, until the next keypress takes it away. pub notice: Option, /// Whether the done column is drawn. Off at startup, and not remembered between /// runs: worklane has no config file, and one flag is not a reason to start one. /// Board-wide rather than per tab: it is a preference about the flow, not about a /// project. pub show_done: bool, pub should_quit: bool, projects: Vec, digest: u64, } impl Board { pub fn new(projects: Vec) -> Result { if projects.is_empty() { return Err(anyhow::anyhow!("no board to monitor")); } // The tabs are fixed for the run: a project cannot be added or dropped without // restarting, so only their contents are rebuilt on a tick. The merge goes // first because it is the reason to monitor several boards at once, and it is // therefore where the view opens. let mut tabs: Vec = Vec::new(); if projects.len() > 1 { tabs.push(Tab::new(ALL.to_string())); } tabs.extend(projects.iter().map(|project| Tab::new(project.name.clone()))); let mut board = Board { tabs, tab: 0, detail: None, offset: 0, search: None, picker: None, notice: None, show_done: false, should_quit: false, projects, digest: 0, }; board.reload()?; Ok(board) } /// Whether the tab row is drawn, which is whether there is more than one board. /// /// A single board keeps the view it has always had: no tabs, and the columns /// starting on the first row. pub fn tabbed(&self) -> bool { self.tabs.len() > 1 } /// The chrome above the columns, which is what every measurement of the board takes. /// /// One answer, read by the draw and by `follow_selection` alike: the frame appearing /// takes three rows off the columns, and a keypress that scrolled against the old /// height would put the selection where the next frame does not draw it. pub fn chrome(&self) -> Chrome { Chrome { tabbed: self.tabbed(), campaign: self.current().campaign.is_some(), } } pub fn current(&self) -> &Tab { &self.tabs[self.tab] } fn current_mut(&mut self) -> &mut Tab { &mut self.tabs[self.tab] } /// Re-read the trees only when the digest says one of them moved. /// /// The scan is the expensive part, not the draw, so this is what the tick guards. /// ratatui diffs its buffer, so drawing every iteration costs nothing. pub fn tick(&mut self) -> Result { let now = digest_of(&self.projects); if now == self.digest { return Ok(false); } self.reload()?; Ok(true) } fn reload(&mut self) -> Result<()> { // Each tree is read once, cards and campaigns together, since the campaign a card // names is resolved on that read. The merge is built from those cards rather than // by scanning every project a second time. // Two lists rather than a list of pairs, because `merge` takes every project's // columns at once and nothing would be served by cloning them into it. let merged = self.projects.len() > 1; let mut per_columns: Vec> = Vec::new(); let mut per_campaigns: Vec> = Vec::new(); for project in &self.projects { let (columns, campaigns) = columns_of(&project.dir); // The project is named on a row only where it has to be. On a single board // there is nothing to tell a campaign apart from, the bargain a card's project // label already takes. let label = match merged { true => Some(project.name.as_str()), false => None, }; per_columns.push(columns); per_campaigns.push(campaign_rows(&campaigns, label)); } let mut built: Vec<(Vec, Vec)> = Vec::new(); if merged { // Every board's campaigns under the merge, each carrying the project it was // filed in: on that tab an id says which campaign but not which board holds it. let campaigns = per_campaigns.iter().flatten().cloned().collect(); built.push((merge(&per_columns, &self.projects), campaigns)); } built.extend(per_columns.into_iter().zip(per_campaigns)); for (tab, (columns, campaigns)) in self.tabs.iter_mut().zip(built) { tab.campaigns = campaigns; // A selection whose campaign has left the board goes back to the whole board // rather than filtering it to nothing: the frame would have nothing to name and // every column would be empty, which reads as a board that has lost its // tickets. if tab.selected_campaign().is_none() { tab.campaign = None; } tab.columns = retain_campaign(columns, tab.campaign.as_deref()); // One scroll position per column, kept by index. A tick that adds or removes // columns is not a thing statuses do, but the resize keeps the two in step // regardless; `resize` both pads and truncates. tab.offsets.resize(tab.columns.len(), 0); tab.clamp(self.show_done); } self.digest = digest_of(&self.projects); // 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 // got shorter is caught by the clamp in the draw. if self.detail.is_some() { self.detail = self.selected().map(detail_of); } Ok(()) } /// The columns of the tab in view that are drawn. pub fn visible(&self) -> &[Column] { self.current().visible(self.show_done) } fn visible_count(&self) -> usize { self.current().visible_count(self.show_done) } /// Move to another tab, cycling at either end. /// /// Tabs cycle where the cards and columns clamp: a ring is what a row of tabs is /// everywhere else, and there is no bottom of a list to run out of. The tab keeps /// its own selection, so all this has to do is check that the selection is still on /// a card that exists — done may have been hidden while another tab was in view — /// and bring it into the window. pub fn select_tab(&mut self, delta: isize, screen: Size) { let count = self.tabs.len() as isize; if count < 2 { return; } self.tab = (self.tab as isize + delta).rem_euclid(count) as usize; let show_done = self.show_done; self.current_mut().clamp(show_done); self.follow_selection(screen); self.refresh_detail(); } /// Show or hide the done column. /// /// `ls` already holds this opinion: it counts done in its summary and leaves it out /// of the listing. Done only grows, so a quarter of the width goes to the column /// least often read while the three being worked get squeezed for it. /// /// Hiding is a change to what is drawn, never to what is read. The directory stays /// scanned and stays in the digest, so the count in the footer is right and revealing /// the column needs no rescan. pub fn toggle_done(&mut self, screen: Size) { self.show_done = !self.show_done; // Showing done again appends a column, so nothing below is reached and the // selection stays exactly where it was. Only the tab in view is corrected: the // others are clamped as they are switched to, since a selection nobody is // looking at cannot be pointing at anything on screen. if self.current().column < self.visible_count() { return; } // Hiding the column the selection is in moves it to the last one still drawn. // An open detail closes with it: it is showing a ticket that is no longer on the // board, and quietly swapping it for a different ticket is worse than closing. let show_done = self.show_done; self.current_mut().clamp(show_done); self.detail = None; self.offset = 0; self.follow_selection(screen); } pub fn selected(&self) -> Option<&Card> { self.current().selected() } /// Move between columns, keeping the card index where it can land. pub fn select_column(&mut self, delta: isize, screen: Size) { let visible = self.visible_count(); if visible == 0 { return; } // Bounded by what is drawn, so the selection cannot walk into a hidden column. let last = visible as isize - 1; let show_done = self.show_done; let tab = self.current_mut(); tab.column = (tab.column as isize + delta).clamp(0, last) as usize; tab.clamp(show_done); // Entering a column shows the card the selection landed on rather than // resetting to its top: the card index carries across columns, so a reset // would open the column with the highlight below the fold whenever it was. // The rest of the place the column was left in is kept. self.follow_selection(screen); self.refresh_detail(); } pub fn select_card(&mut self, delta: isize, screen: Size) { let tab = self.current_mut(); let count = match tab.columns.get(tab.column) { Some(column) => column.cards.len(), None => return, }; if count == 0 { return; } let column = tab.column; let card = (tab.card as isize + delta).clamp(0, count as isize - 1) as usize; self.select_at(column, card, screen); } /// Put the selection on one card, then bring it into view and follow it. /// /// The tail every move shares. `follow_selection` scrolls the column the card is in, /// and the offsets are per column and on the `Tab`, so a jump across columns moves /// the right one. `refresh_detail` keeps an open overlay on the ticket the selection /// names. A second version of either is how a jump comes to scroll differently from /// the arrow keys. fn select_at(&mut self, column: usize, card: usize, screen: Size) { let tab = self.current_mut(); tab.column = column; tab.card = card; self.follow_selection(screen); self.refresh_detail(); } /// Move the focused column's offset so the selected card sits inside the view. /// /// Measured on the same card lines the draw renders, so the two cannot disagree /// about how tall a card is. The screen comes in because the visible height /// belongs to the terminal, which only the caller measures between draws — the /// same reason `scroll_detail` takes it. The draw aligns the focused column again /// on its own geometry, so a resize between this and the next frame is corrected /// there; what is stored here is the place an unfocused column keeps. fn follow_selection(&mut self, screen: Size) { // The width and height the next draw will give this column, since a card's // height depends on how much of the title has to wrap and the tab row takes a // row off the columns. Measured before the borrows below. let column = self.current().column; let chrome = self.chrome(); let width = card_width(screen, chrome, self.visible_count(), column); let inner = column_text_height(screen, chrome); let tab = self.current_mut(); let Some(column) = tab.columns.get(tab.column) else { return; }; let Some(slot) = tab.offsets.get_mut(tab.column) else { return; }; let height = |card: &Card| card_height(card, width); let start: u16 = column .cards .get(..tab.card) .map(|before| before.iter().map(height).sum()) .unwrap_or(0); let end = start + column.cards.get(tab.card).map(height).unwrap_or(0); let total: u16 = column.cards.iter().map(height).sum(); *slot = aligned_offset(*slot, start, end, inner, total); } /// Open the detail view on the selected card, or close it if it is already open. pub fn toggle_detail(&mut self) { self.offset = 0; self.detail = match self.detail { Some(_) => None, None => self.selected().map(detail_of), }; } /// The campaign the tab in view is filtered to, or nothing for the whole board. pub fn campaign(&self) -> Option<&CampaignRow> { self.current().selected_campaign() } /// Open the picker on the campaign in view, or say there is nothing to pick from. /// /// A board with no campaigns gets a notice rather than an empty box: the box would /// have to be dismissed to learn that it was empty, and `Notice` is what the board /// already uses to say something in words. Failed, because the key was pressed and /// nothing came of it, which is the same answer a copy off an empty column gives. /// /// It opens on the campaign already selected, so `c` on a filtered board is a way to /// look at where you are as much as a way to move, and on the first row otherwise. pub fn open_picker(&mut self) { if self.current().campaigns.is_empty() { self.notice = Some(Notice::failed("no campaigns on this board")); return; } let row = self .current() .campaign .as_deref() .and_then(|uuid| self.current().campaigns.iter().position(|row| row.uuid == uuid)) .unwrap_or(0); self.picker = Some(Picker { row, offset: 0 }); } /// Feed a keypress to the open picker, and say whether it was taken. /// /// The same contract as `search_key`, and it runs beside it for the same reason: an /// open list has the keyboard, so `d` must not toggle the done column and `q` must not /// quit while the reader is choosing a campaign. `ctrl-c` is the one key it declines, /// 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. pub fn picker_key(&mut self, key: KeyEvent, screen: Size) -> bool { if self.picker.is_none() { return false; } let control = key.modifiers.contains(KeyModifiers::CONTROL); if control && key.code == KeyCode::Char('c') { return false; } match key.code { 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), _ => {} } true } /// 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 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); } /// Take the highlighted campaign and close the picker. fn take_picked(&mut self, screen: Size) { let Some(picker) = &self.picker else { return }; let Some(row) = self.current().campaigns.get(picker.row) else { return; }; let uuid = row.uuid.clone(); self.picker = None; self.select_campaign(Some(uuid), screen); } /// Filter the tab in view to one campaign, or back to the whole board. /// /// The filter is applied where the columns are built, so this reloads rather than /// filtering what is already on the tab: a filtered column is not something the /// unfiltered one can be recovered from, and the tree is what the board reads anyway. /// Cheap for the same reason a tick is. /// /// An open detail view closes, the answer hiding the done column already gives: the /// ticket it is showing may not be on the filtered board at all, and quietly swapping /// it for a different ticket is worse than closing. pub fn select_campaign(&mut self, campaign: Option, screen: Size) { if self.current().campaign == campaign { return; } self.current_mut().campaign = campaign; self.detail = None; self.offset = 0; // A selection kept from the unfiltered board would point at a card that is no // longer in that column, so it goes back to the top of the first one. let tab = self.current_mut(); tab.column = 0; tab.card = 0; tab.offsets.iter_mut().for_each(|offset| *offset = 0); // Swallowed for the reason the tick's is not: there is nobody above a keypress to // handle a failed read, and the board goes on being drawn either way. if let Err(err) = self.reload() { self.notice = Some(Notice::failed(format!("reload failed: {err}"))); } self.follow_selection(screen); } /// Put away what is open, and quit when there is nothing left to put away. /// /// What `esc` has always done, and now what `q` does too. `q` used to set /// `should_quit` outright, so a reader who pressed it to close a ticket lost the /// whole board instead, which is not what `q` means anywhere else that lays a /// document over a list. /// /// Here rather than in the match arm in `main.rs`: that dispatch is not reachable /// from a test, so a rule written into it is a rule nothing can check. The arm is /// left as the one line that names the keys. /// /// `ctrl-c` is therefore the only key that leaves the board while a ticket is open or /// a campaign is selected, and the footer says so rather than leaving the reader to /// find out. /// /// The order is the order things were put on: the overlay, then the campaign filter, /// then the board. One press takes off one layer, so nothing is skipped and nothing is /// taken away that the reader cannot see. pub fn dismiss(&mut self, screen: Size) { if self.detail.is_some() { self.toggle_detail(); return; } // A campaign filter is the next thing open, under the overlay and above the board // itself: it is a view the reader put on and has to be able to take off. Quitting // out from under it instead is exactly what `q` used to do to an open ticket, and // the footer says which of the two this key is about to do. if self.current().campaign.is_some() { self.select_campaign(None, screen); return; } self.should_quit = true; } /// Open the prompt on an empty query. /// /// Empty rather than the last query kept: that search is finished, and reopening on /// it would make `/` and enter repeat a jump nobody asked for. Repeating a search is /// `n`, which 3b16540 puts out of its own scope. pub fn open_search(&mut self) { self.search = Some(Search::default()); } /// Feed a keypress to the open prompt, and say whether it was taken. /// /// The prompt swallows every key it is given, the ones bound to actions included: /// typing `d` into a query must not toggle the done column and `q` must not quit. /// That is why this runs ahead of the action arms and reports what it took, rather /// than every arm below asking whether a search is open. With no prompt open it /// takes nothing, so the dispatch is unchanged for every other state. /// /// `ctrl-c` is the one key it declines. A terminal application always honours it, and /// a prompt that ate it would leave no way off the board without closing the prompt /// first. Any other control combination is swallowed and does nothing: it must not /// type its letter, and it must not fall through either, since the action arms match /// on the code alone and `ctrl-d` would reach the one bound to `d`. pub fn search_key(&mut self, key: KeyEvent, screen: Size) -> bool { if self.search.is_none() { return false; } let control = key.modifiers.contains(KeyModifiers::CONTROL); if control && key.code == KeyCode::Char('c') { return false; } match key.code { KeyCode::Esc => self.search = None, KeyCode::Enter => self.jump_to_match(screen), KeyCode::Backspace => self.edit_query(|query| { query.pop(); }), KeyCode::Char(typed) if !control => self.edit_query(|query| query.push(typed)), _ => {} } true } /// Change the query, and forget a miss that was about what it used to say. fn edit_query(&mut self, edit: impl FnOnce(&mut String)) { if let Some(search) = &mut self.search { edit(&mut search.query); search.missed = false; } } /// Take the query to the first match, or say there was none. /// /// A hit closes the prompt: it has done its job and the reader is back on the board. /// A miss keeps it open and marks it, so the query can be corrected in place instead /// of retyped from `/`, and the selection stays exactly where it was. fn jump_to_match(&mut self, screen: Size) { let Some(search) = &self.search else { return }; let query = search.query.clone(); let hit = first_match(self.visible(), &query); match hit { Some((column, card)) => { self.search = None; self.select_at(column, card, screen); } None => { if let Some(search) = &mut self.search { search.missed = true; } } } } /// The string the copy key puts on the clipboard: the selected card's short id. /// /// A method here rather than a line inside the arm that copies, so what gets copied /// is a question a test can ask without a clipboard or a terminal to answer it. /// /// The seven characters the card already prints and every command already takes, /// `ticket.id` rather than the full uuid: the point of the key is to stop those seven /// being retyped, and a `worklane show` resolves them. The project is left off on the /// merge tab even though the id alone is not an address there. This goes on a /// clipboard to be pasted into a command line, and a second word in it would have to /// be deleted every time. /// /// `None` on an empty column, so nothing is sent rather than an empty string put on /// the clipboard over whatever the reader had there. pub fn copy_text(&self) -> Option { self.selected().map(|card| card.ticket.id.clone()) } /// Copy the selected id through `copy`, and say what happened. /// /// The clipboard comes in as an argument rather than being reached for here, so the /// suite can drive both answers: `crate::clipboard::copy` in the dispatch, a closure /// in a test. Nothing else about the board changes, since a copy is not a move. /// /// A failure is said in the footer rather than returned. There is nobody above this /// to handle it: the board goes on being drawn, and an error swallowed here would /// look exactly like a copy that worked until the paste came out wrong. pub fn copy_selected_id(&mut self, copy: impl FnOnce(&str) -> Result<()>) { let Some(text) = self.copy_text() else { self.notice = Some(Notice::failed("nothing to copy")); return; }; self.notice = Some(match copy(&text) { Ok(()) => Notice::done(format!("copied {text}")), Err(err) => Notice::failed(format!("copy failed: {err}")), }); } /// Forget the notice, which is what every keypress does before it is dispatched. /// /// A keypress rather than a timer: it needs no clock on the board and no wakeup in /// the loop, and the moment the reader does anything else the message has been read /// or was never going to be. Doing nothing leaves it up, which is the one state where /// it is still worth reading. /// /// Here rather than in the loop for the reason `dismiss` is: the dispatch in /// `main.rs` is not reachable from a test, so a rule written into it is a rule /// nothing can check. pub fn clear_notice(&mut self) { self.notice = None; } /// Scroll the open detail view by whole screenfuls, one line kept for overlap. /// /// Up and down move the selection, so the scroll is on PageUp and PageDown. That is /// worth keeping either way: with the modal open, up and down step through the /// tickets and the modal follows, so a column can be read without closing it. /// /// Clamped against the wrapped text rather than the raw lines, so the last page ends /// with the ticket instead of running on into blank space, and against zero at the /// top. The screen is asked for because both ends belong to the overlay, which only /// the draw otherwise measures. pub fn scroll_detail(&mut self, pages: isize, screen: Size) { let Some(detail) = &self.detail else { return }; let text = detail_text_area(Rect::new(0, 0, screen.width, screen.height)); // A screenful less a line, so the eye has something to land on after the jump. let step = text.height.saturating_sub(1).max(1) as isize; let last = last_offset(&detail.body, text) as isize; self.offset = (self.offset as isize + pages.saturating_mul(step)).clamp(0, last) as u16; } fn refresh_detail(&mut self) { // A newly selected ticket starts at its top, not partway down where the last one // was left. self.offset = 0; if self.detail.is_some() { self.detail = self.selected().map(detail_of); } } } /// The ticket as the detail view holds it: its name and short id, then the body as /// `show` renders it and the comments. /// /// Plain rather than coloured, since ratatui draws styled spans and an escape sequence /// in a paragraph would be printed as literal bytes. fn detail_of(card: &Card) -> Detail { let ticket = &card.ticket; let content = std::fs::read_to_string(&ticket.path).unwrap_or_default(); let uuid = parse_ticket_field(&content, "ID"); let worklane_dir = ticket.path.parent().and_then(|status| status.parent()); // All of these read the tree beside the ticket, and all fall back to nothing: one // unreadable file must not take the board down with it. The relations cost a scan of // the board, paid only while a ticket is open and only on a tick that changed // something, which is what already reloads every card. The campaign title costs a // read of one small directory beside it, for the same reason `show` pays it: the // field stores a uuid, and a card that displayed one raw would say nothing. let resolved = worklane_dir .and_then(|dir| crate::campaign::resolved_for(&content, dir, false).ok()) .unwrap_or_default(); let comments = match worklane_dir { Some(worklane_dir) => { read_comments(&worklane_dir.join("comments").join(&uuid)).unwrap_or_default() } None => Vec::new(), }; // Colour off for the text, which is what keeps escapes out of the paragraph, and the // relations arrive as rows so the board can style them itself. let mut parts = content_parts(&content, false, &resolved); parts.push(BodyPart::Text(format!("\n{}", format_comments_with(&comments, false)))); Detail { title: ticket.title.clone(), id: ticket.id.clone(), project: card.project.clone(), body: detail_body(&parts), } } /// The rendered body as lines of spans: the text split where it says, and each relation /// row styled from the cells the CLI paints. /// /// A part that does not end on a newline runs on into the next one rather than closing a /// line, so the seam between text and relations is wherever the body actually put it and /// not wherever a part happened to end. fn detail_body(parts: &[BodyPart]) -> Text<'static> { let mut lines: Vec> = Vec::new(); let mut open: Vec> = Vec::new(); for part in parts { match part { BodyPart::Text(text) => { let mut rest = text.as_str(); while let Some((line, tail)) = rest.split_once('\n') { if !line.is_empty() { open.push(Span::raw(line.to_string())); } lines.push(Line::from(std::mem::take(&mut open))); rest = tail; } if !rest.is_empty() { open.push(Span::raw(rest.to_string())); } } // One line each, from the same cells `render_relations` paints, so the block // cannot read differently here than it does in `show`. BodyPart::Relations(rows) => { for row in relation_cells(rows) { open.extend(row.into_iter().map(span_of)); lines.push(Line::from(std::mem::take(&mut open))); } } } } if !open.is_empty() { lines.push(Line::from(open)); } Text::from(lines) } /// A cell as the board draws it: the same text in the same colour, as a span. /// /// The other half of `paint_cells`, which is the CLI's. `From` is what makes the /// two agree about what the colour is. fn span_of(cell: Cell) -> Span<'static> { match cell.color { Some(color) => Span::styled(cell.text, Style::default().fg(color.into())), None => Span::raw(cell.text), } } /// The four columns of one board, with each card's campaign already named. /// /// The index is read once here and handed to every card, rather than looked up per card /// or, worse, per draw: the uuid is on the ticket and the name is in another directory, /// so the cheapest honest place for the join is the pass that is already building the /// cards. An unreadable campaigns directory is an empty index, which leaves every card in /// no campaign and the board drawable. fn columns_of(worklane_dir: &Path) -> (Vec, CampaignIndex) { let campaigns = CampaignIndex::load(worklane_dir).unwrap_or_default(); let mut columns: Vec = status_dirs() .into_iter() .map(|status| { // An absent or unreadable directory is an empty column, not a missing one: // the four statuses are the shape of the board. let cards = collect_ticket_items(worklane_dir.join(status)) .unwrap_or_default() .into_iter() .map(|ticket| Card { campaign: campaign_of(&ticket, &campaigns), ticket, project: None, blocked: false, }) .collect(); Column { status, cards } }) .collect(); mark_blocked(&mut columns); (columns, campaigns) } /// The campaigns of one board as the picker and the frame hold them. /// /// Built off the index the cards were named from, so the list a reader picks out of and /// 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 { campaigns .iter() .map(|campaign| CampaignRow { uuid: campaign.uuid.clone(), title: campaign.title.clone(), codename: campaign.codename.clone(), summary: section_opening(&campaign.content, &DESCRIPTION).unwrap_or_default(), project: project.map(|name| name.to_string()), }) .collect() } /// The columns filtered to one campaign's members, or left as they are when none is /// selected. /// /// Every column is kept, empty ones included, for the reason `campaign show` prints every /// status: a campaign groups across the flow rather than within one status, so the shape of /// the answer is the four columns and the question is how many are in each. Filtered here, /// where the columns are built, so nothing downstream has to ask whether a campaign is /// selected — the board simply holds fewer cards. fn retain_campaign(mut columns: Vec, campaign: Option<&str>) -> Vec { let Some(uuid) = campaign else { return columns; }; for column in columns.iter_mut() { column .cards .retain(|card| card.ticket.campaign.as_deref() == Some(uuid)); } columns } /// The label for the campaign a ticket names, or nothing when it names none. /// /// Nothing, too, for a uuid the index does not hold. `campaign_cell` renders that case as /// `_missing_` because a metadata table is a place to report a dangling reference; a card /// is not, and the answer here is the one `mark_blocked` gives a blocker nobody holds. fn campaign_of(ticket: &TicketItem, campaigns: &CampaignIndex) -> Option { let uuid = ticket.campaign.as_deref()?; let campaign = campaigns.get(uuid)?; Some(campaign_label(&campaign.uuid, campaign.codename.as_deref())) } /// Set `blocked` on every card whose ticket waits on one that is not done. /// /// Two walks of what `columns_of` has just read, not a lookup per relation: the status /// of a blocker is on another card, so the pass builds the uuid to status map once and /// then answers every card from it. Nothing is read from disk here, which is the point /// — the blockers came off the same read that built the cards. /// /// A blocker the board does not hold marks nothing, the answer `mv` already gives it: a /// uuid nothing carries is a bookkeeping fault rather than a dependency. A ticket with /// no ID field is left out of the map entirely, or every ticket missing one would block /// every other ticket missing one, which is the guard `RelationIndex::inbound` makes. fn mark_blocked(columns: &mut [Column]) { let status_of: HashMap = columns .iter() .flat_map(|column| { column .cards .iter() .map(|card| (card.ticket.uuid.clone(), column.status)) }) .filter(|(uuid, _)| !uuid.trim().is_empty() && !is_unknown_value(uuid)) .collect(); for column in columns.iter_mut() { for card in column.cards.iter_mut() { card.blocked = card.ticket.blockers.iter().any(|blocker| { matches!(status_of.get(blocker.as_str()), Some(status) if *status != DONE) }); } } } /// Every board's columns as one set of four, each card labelled with the project it /// came from. /// /// Sorted through `by_priority_then_title`, the order the listing uses, rather than /// left as one project's column after another's: an overview whose order depended on /// the argument order would bury a p1 under another project's p5. fn merge(per_project: &[Vec], projects: &[Project]) -> Vec { status_dirs() .into_iter() .enumerate() .map(|(index, status)| { let mut cards: Vec = Vec::new(); for (columns, project) in per_project.iter().zip(projects) { let Some(column) = columns.get(index) else { continue; }; cards.extend(column.cards.iter().map(|card| Card { ticket: card.ticket.clone(), project: Some(project.name.clone()), // Already answered on the board the card came from. Recomputing it // over the merged columns would let one project's uuid resolve // against another's ticket, which is a relation nothing can record. blocked: card.blocked, // The same, and for the same reason: a campaign is resolved inside one // `.worklane`, so a merged lookup could answer one project's uuid with // another project's campaign. campaign: card.campaign.clone(), })); } cards.sort_by(|a, b| by_priority_then_title(&a.ticket, &b.ticket)); Column { status, cards } }) .collect() } /// The first card whose id or title holds `query`, as its column and its place in it. /// /// Reading order: column by column left to right, then top to bottom inside a column, /// which is how the board is laid out and how it is read. /// /// Over every card in the columns it is given, not the rows on screen. A query that /// answered differently on a tall terminal and a short one is not a search, and the jump /// scrolls the match into view anyway. The caller passes the *visible* columns, so a /// hidden done column is never searched: selecting a ticket that is not on the board /// would leave the highlight nowhere. /// /// Id and title only, per 3b16540, and both lowercased. The title has to be case /// insensitive to be worth typing; giving the id the same treatment costs nothing and /// lets a pasted id match whatever case it was copied in. /// /// An empty query matches nothing rather than everything. Enter on a prompt nobody typed /// into should leave the selection where it is, not jump to the first card on the board. fn first_match(columns: &[Column], query: &str) -> Option<(usize, usize)> { let needle = query.trim().to_lowercase(); if needle.is_empty() { return None; } columns.iter().enumerate().find_map(|(index, column)| { column .cards .iter() .position(|card| { card.ticket.id.to_lowercase().contains(&needle) || card.ticket.title.to_lowercase().contains(&needle) }) .map(|card| (index, card)) }) } /// The fingerprint of every monitored board, so a change in any of them redraws. fn digest_of(projects: &[Project]) -> u64 { let mut hasher = DefaultHasher::new(); for project in projects { digest(&project.dir).hash(&mut hasher); } hasher.finish() } /// A fingerprint of every ticket, campaign and comment file: name, length and modified /// time. /// /// Names alone would miss a ticket edited in place, and a directory's own mtime only /// moves on create and rename, so watching the directories would miss it too. Comment /// files are included because a comment added elsewhere has to reach the detail view, and /// campaign files because a campaign filed elsewhere has to reach the picker and a codename /// edited by hand has to reach every card that names it. /// /// Cheap enough on a tree of tens of small files that it needs no new dependency. If it /// ever stops being cheap, `notify` is the next step, and the reason belongs on the /// ticket. pub fn digest(worklane_dir: &Path) -> u64 { let mut entries: Vec<(String, u64, Duration)> = Vec::new(); let mut visit = |dir: PathBuf| { let Ok(read) = std::fs::read_dir(&dir) else { return; }; for entry in read.filter_map(|e| e.ok()) { let path = entry.path(); if path.extension().is_none_or(|e| e != "md") { continue; } let Ok(meta) = entry.metadata() else { continue }; let modified = meta .modified() .ok() .and_then(|at| at.duration_since(SystemTime::UNIX_EPOCH).ok()) .unwrap_or_default(); entries.push((path.to_string_lossy().to_string(), meta.len(), modified)); } }; for status in status_dirs() { visit(worklane_dir.join(status)); } // The campaigns, because the board draws them: a campaign filed elsewhere has to reach // the picker, and a codename edited by hand has to reach every card that names it. visit(worklane_dir.join(CAMPAIGNS_DIR)); // Comments live one level deeper, a directory per ticket. let comments = worklane_dir.join("comments"); if let Ok(read) = std::fs::read_dir(&comments) { for entry in read.filter_map(|e| e.ok()) { visit(entry.path()); } } // Sorted, so a directory handing entries back in a different order is not a change. entries.sort(); let mut hasher = DefaultHasher::new(); entries.hash(&mut hasher); hasher.finish() } pub fn draw(frame: &mut Frame, board: &Board) { let area = frame.area(); let chrome = board.chrome(); let rows = frame_rows(area, chrome); if chrome.tabbed { draw_tabs(frame, board, rows[TAB_ROW]); } if let Some(campaign) = board.campaign() { draw_campaign(frame, campaign, &board.current().standing(), rows[CAMPAIGN_ROW]); } draw_columns(frame, board, rows[BOARD_ROW]); draw_footer(frame, board, rows[FOOTER_ROW]); if let Some(detail) = &board.detail { draw_detail(frame, detail, board.offset, area); } // Over the overlay as well as the board. Both are things the reader put on, and the // picker is the one they are acting in: an overlay drawn on top of it would cover the // list they are choosing from. if let Some(picker) = &board.picker { draw_picker(frame, board.current(), picker, area); } } /// The rows of the frame, in the order `frame_rows` lays them out. /// /// Named rather than counted at each call site: the campaign frame arrived between the tab /// row and the columns, and an index written out by hand is an index that goes on meaning /// what it used to. const TAB_ROW: usize = 0; const CAMPAIGN_ROW: usize = 1; const BOARD_ROW: usize = 2; const FOOTER_ROW: usize = 3; /// The rows of the frame: the tab row, the campaign frame, the columns, the footer. /// /// One place, shared with the measurement in `card_width` and `column_text_height`, for /// the same reason `column_areas` is shared: geometry reproduced by hand is geometry /// that comes to disagree with the draw. With one board the tab row is zero rows high and /// with no campaign selected the frame is too, so the indices hold in every state and /// rendering into a zero-height row draws nothing. fn frame_rows(area: Rect, chrome: Chrome) -> std::rc::Rc<[Rect]> { Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(u16::from(chrome.tabbed)), Constraint::Length(chrome.campaign_rows()), Constraint::Min(3), Constraint::Length(1), ]) .split(area) } /// One tab per monitored board, plus the merge, named after the directory each lives in. /// /// Cyan for the one in view, the colour the focused column's border already uses, and /// grey for the rest. fn draw_tabs(frame: &mut Frame, board: &Board, area: Rect) { let names: Vec = board.tabs.iter().map(|tab| tab.name.clone()).collect(); frame.render_widget( Tabs::new(names) .select(board.tab) .style(Style::default().fg(Color::Grey.into())) .highlight_style( Style::default() .fg(Color::Cyan.into()) .add_modifier(Modifier::BOLD), ), area, ); } /// The selected campaign above the columns: what it is called, what it is for, and how far /// it has got. /// /// The columns below are its members, so this is the row that says whose members they are. /// Three rows for it, of which one is prose: the identity goes on the top border and the /// standing on the bottom one, the trade the detail overlay already makes with its title /// and its page indicator, and every row taken here is a row of cards. /// /// The title carries the id in red, the codename in its own colour and bold, and the name /// 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) { let mut block = Block::default() .borders(Borders::ALL) .border_style(Style::default().fg(Color::Grey.into())) .title(Line::from(campaign_title(campaign, area.width))); // Right-aligned on the bottom border, where the overlay already puts the one number it // has to show. The count is plain and the derived state is orange, which is the two // colours `campaign ls` prints the same pair in. let mut standing_spans = vec![Span::raw(format!(" {}", standing.label()))]; if let Some(state) = standing.state() { standing_spans.push(Span::styled( format!(" [{state}]"), Style::default().fg(Color::Orange.into()), )); } standing_spans.push(Span::raw(" ")); // The way out, on the border of the thing it undoes rather than in the footer. The // footer row is already at its width naming eight keys, and this belongs beside the // frame anyway: it is what takes the frame away. Grey because it is chrome, the colour // the footer's own key names and the overlay's page indicator take. // // Dropped whole when the two would meet, the rule the page indicator follows: half of // either reads as something else, and the footer still answers how to leave the board. let hint = " q board "; let room = area.width.saturating_sub(2) as usize; if hint.chars().count() + spans_width(&standing_spans) <= room { block = block .title_bottom(Line::from(Span::styled(hint, Style::default().fg(Color::Grey.into())))); } block = block.title_bottom(Line::from(standing_spans).right_aligned()); // The description's opening line, or the placeholder in grey for a campaign that has // none: the row is spent either way, and a blank one reads as a frame that failed to // draw. Wrapped off, so a long line is cut at the border rather than pushing the frame // taller than the geometry says it is. let summary = match campaign.summary.is_empty() { true => Span::styled(DESCRIPTION.placeholder, Style::default().fg(Color::Grey.into())), false => Span::raw(campaign.summary.clone()), }; frame.render_widget(Paragraph::new(Line::from(summary)).block(block), area); } /// The campaign frame's title: `(id) ~codename · Name`, cut to the border it sits on. /// /// The same shape and the same cut as `detail_title`, since both name one thing on a /// border: the id first because that is how every view addresses a campaign, the codename /// next because it is the id in a word, and the name last because it is what the two are /// shorthand for. A campaign with no codename spends nothing on one. fn campaign_title(campaign: &CampaignRow, frame_width: u16) -> Vec> { let label = campaign.label(); let codename = match campaign.codename.is_some() { true => format!("{} ", label.text), false => String::new(), }; let prefix = format!(" ({}) {codename}· ", short_id(&campaign.uuid)); let room = frame_width.saturating_sub(2) as usize; // The trailing space is part of what has to fit, so it is measured rather than added // on afterwards: a title that filled the border exactly would otherwise be drawn one // cell past it and cut by ratatui, taking the space and the last letter with it. let whole = format!("{} ", campaign.title); let name = match prefix.chars().count() + whole.chars().count() <= room { true => whole, // What is left after the prefix and the space that follows the cut name. false => match room.saturating_sub(prefix.chars().count() + 1) { 0 => String::new(), keep => format!("{} ", with_ellipsis(&campaign.title, keep)), }, }; vec![ Span::raw(" ("), Span::styled( short_id(&campaign.uuid).to_string(), Style::default().fg(Color::Red.into()), ), Span::raw(") "), Span::styled( codename, Style::default() .fg(label.color.unwrap_or(Color::Grey).into()) .add_modifier(Modifier::BOLD), ), Span::raw("· "), Span::styled(name, Style::default().fg(Color::Green.into())), ] } fn draw_columns(frame: &mut Frame, board: &Board, area: Rect) { // Only the drawn columns are measured, so hiding done gives its width back to the // three that are left rather than leaving a gap where it was. let columns = board.visible(); let areas = column_areas(area, columns.len()); for (index, column) in columns.iter().enumerate() { let focused = index == board.current().column; let title = format!(" {} ({}) ", column.status, column.cards.len()); let block = Block::default() .borders(Borders::ALL) .title(Span::styled( title, Style::default() .fg(Color::Orange.into()) .add_modifier(if focused { Modifier::BOLD } else { Modifier::empty() }), )) .border_style(Style::default().fg(if focused { Color::Cyan.into() } else { Color::Grey.into() })); // The cards go into one paragraph, and where each card starts is recorded as // it is added: the scroll has to measure what is really drawn, not assume a // card size the renderer has to agree with. let text = areas[index].inner(Margin::new(1, 1)); let mut lines: Vec = Vec::new(); let mut starts: Vec = Vec::new(); for (at, card) in column.cards.iter().enumerate() { let selected = focused && at == board.current().card; starts.push(lines.len() as u16); lines.extend(card_lines(card, selected, text.width)); } let total = lines.len() as u16; let stored = board.current().offsets.get(index).copied().unwrap_or(0); // The focused column follows its selection here as well as on the keypress: // the terminal can be resized between the two, and a tick can shorten the // column under a reader who is already at the end. An unfocused column keeps // the place it was left in, capped so it cannot show blank space past its // last card. let offset = if focused { let card = board.current().card; let start = starts.get(card).copied().unwrap_or(total); let end = starts.get(card + 1).copied().unwrap_or(total); aligned_offset(stored, start, end, text.height, total) } else { stored.min(total.saturating_sub(text.height)) }; // An empty status is an empty column, not a column that is not there. frame.render_widget(Paragraph::new(lines).block(block).scroll((offset, 0)), areas[index]); } } /// The lines one card occupies, measured the way `draw_columns` renders it. /// /// Width-dependent, because the title wraps: the same ticket is four rows in a wide /// column and five in a narrow one. fn card_height(card: &Card, width: u16) -> u16 { card_lines(card, false, width).len() as u16 } /// The rectangles the columns are drawn in, from one place. /// /// Shared with the measurement in `follow_selection`, so the width a card lays itself /// out in is the width it is drawn in. `Ratio` leaves a remainder column to whichever /// slot ratatui gives it, and guessing that arithmetic by hand is how the two come to /// disagree about where a card starts. fn column_areas(area: Rect, count: usize) -> std::rc::Rc<[Rect]> { let widths: Vec = (0..count) .map(|_| Constraint::Ratio(1, count.max(1) as u32)) .collect(); Layout::default() .direction(Direction::Horizontal) .constraints(widths) .split(area) } /// The width a card has inside one column, as the next draw will lay it out. fn card_width(screen: Size, chrome: Chrome, count: usize, column: usize) -> u16 { column_areas(board_area(screen, chrome), count) .get(column) .map(|area| area.inner(Margin::new(1, 1)).width) .unwrap_or(0) } /// The rows a column's cards share: inside the border of the area the columns get. /// /// A border row on either side of the text. The draw measures the real inner rectangle /// instead, so a terminal too short for this arithmetic is corrected there. fn column_text_height(screen: Size, chrome: Chrome) -> u16 { board_area(screen, chrome).height.saturating_sub(2) } /// The area the columns are drawn in, which is what `draw` hands to `draw_columns`. fn board_area(screen: Size, chrome: Chrome) -> Rect { frame_rows(Rect::new(0, 0, screen.width, screen.height), chrome)[BOARD_ROW] } /// The offset that keeps the lines `start..end` in view, inside content `0..total`. /// /// A range below the view lands its last line on the bottom row; one above the view /// puts its first line on the top row; inside, the offset stays where it was. Capped /// against `total - inner` last, so neither path runs past the end of the content into /// blank space — the same both-ends clamp `scroll_detail` applies to the overlay. fn aligned_offset(offset: u16, start: u16, end: u16, inner: u16, total: u16) -> u16 { let offset = if end > offset.saturating_add(inner) { end.saturating_sub(inner) } else if start < offset { start } else { offset }; offset.min(total.saturating_sub(inner)) } /// One card as four corners with the title between them: /// /// ```text /// ●◐ (1b78a24) 2026-12-31 /// The tui detail view cannot /// scroll, and the footer says… /// ~beaver #cli #tui /// Ansho Rei [3/9] /// ``` /// /// The due date and the criteria count are on the right because a corner is where the /// eye goes for a number, and both were invisible at the end of a line of prose. The /// title gets two rows because worklane's own titles are routinely longer than a /// quarter of a terminal, and one row cut them off mid-word with nothing to say so. /// /// On the All tab the project follows the id in that top left corner, since across /// several boards the id alone is not an address: two projects can hold the same title, /// and seven characters do not say where they live. /// /// The campaign and the tags sit between the title and the bottom corners, on a row a /// ticket without either does not spend. See [`labels_line`]. /// /// A held-up ticket carries [`BLOCKED_MARK`] after its id, ahead of the project and the /// due date, both of which give way to it: those are context for a ticket somebody can /// start, and this is the one thing on a card that says not to. fn card_lines(card: &Card, selected: bool, width: u16) -> Vec> { let ticket = &card.ticket; let (glyph, colour) = priority_mark(ticket.priority); let emphasis = if selected { Modifier::REVERSED } else { Modifier::empty() }; let mut left = vec![ Span::styled( glyph.to_string(), Style::default().fg(colour.into()).add_modifier(emphasis), ), Span::raw(" "), Span::styled( format!("({})", ticket.id), Style::default().fg(Color::Red.into()).add_modifier(emphasis), ), ]; // After the id, not before it: inserted ahead of the id the mark would push it out // of line, and a column of ids that do not start at the same cell is harder to read // than one card's worth of state is worth. Dropped whole when the row cannot hold // the identity and the mark together, the rule a corner follows, rather than // wrapping or cutting it. if card.blocked && spans_width(&left) + 1 + BLOCKED_MARK.chars().count() <= width as usize { left.push(Span::raw(" ")); left.push(Span::styled( BLOCKED_MARK.to_string(), Style::default() .fg(Color::BrightRed.into()) .add_modifier(emphasis), )); } let label = card .project .as_deref() .and_then(|name| project_label(name, width, spans_width(&left))); if let Some(label) = label { left.push(Span::raw(" ")); // Grey like the owner and the criteria count: the shape carries which project // this is, and colour here accentuates rather than encodes. left.push(Span::styled( label, Style::default().fg(Color::Grey.into()).add_modifier(emphasis), )); } let mut lines = vec![corner_line(left, due_span(&ticket.due), width)]; lines.extend( title_lines(&ticket.title, width) .into_iter() .map(|line| Line::from(Span::styled(line, Style::default().add_modifier(emphasis)))), ); if let Some(row) = labels_line(card.campaign.as_ref(), &ticket.tags, width) { lines.push(row); } lines.push(corner_line( vec![Span::styled( ticket.owner.clone(), Style::default().fg(Color::Grey.into()), )], ticket.criteria.map(|progress| { Span::styled( format!("[{}/{}]", progress.met, progress.total), Style::default().fg(Color::Grey.into()), ) }), width, )); lines.push(Line::from("")); lines } /// The ticket's campaign and tags under the title, or nothing when it has neither. /// /// Each tag is prefixed with `#` and the row is dimmed like the owner and the criteria /// count: what a card is for is telling tickets apart at a glance, and colour here /// accentuates rather than encodes. Without the marker the row reads as a third line of /// the title, since a tag is an ordinary word and the title sits directly above it. /// /// The campaign is the same kind of thing said the same way, with [`CAMPAIGN_MARK`] for /// its marker and in bold. It comes **first and takes its space first**: two cards in one /// campaign are what a reader is looking for when they are looking for a campaign at all, /// and the tags are the context around that. So a row too narrow to hold both drops the /// tags whole and keeps the campaign, the order `corner_line` and `project_label` already /// use — the stronger fact takes the row and the weaker one gives way. Bold is what stops /// it reading as another tag when a card carries five. /// /// A row the column will not hold is dropped whole, the rule `corner_line` applies to a /// corner: a cut list reads as a shorter one, and `bug` and `bugfix` truncated to the /// same width say the same thing. A ticket with neither a campaign nor a tag spends no row /// at all, the way a short title spends no second one, so a ticket in no campaign renders /// exactly as it did before campaigns reached the card. /// /// Each tag carries its own colour, from `tag_color`, so the same tag is the same /// colour on every card in every column, and the campaign carries its own from /// `campaign_label` for the same reason. The row is spans rather than one string for /// that reason alone; it is still measured as one string. fn labels_line(campaign: Option<&Cell>, tags: &[String], width: u16) -> Option> { let width = width as usize; // Measured on the raw text, before anything is styled. What fits must not depend on // the colour decision, or a card would hold its labels in one render and drop them in // the other. let campaign = campaign.filter(|cell| cell.text.chars().count() <= width); let used = campaign.map_or(0, |cell| cell.text.chars().count()); // The space between the campaign and the first tag, which the row has to hold too. let room = width.saturating_sub(used + usize::from(campaign.is_some())); let row = tags .iter() .map(|tag| format!("#{tag}")) .collect::>() .join(" "); let tags: &[String] = match !row.is_empty() && row.chars().count() <= room { true => tags, false => &[], }; if campaign.is_none() && tags.is_empty() { return None; } let mut spans = Vec::with_capacity(tags.len() * 2 + 2); if let Some(cell) = campaign { spans .push(span_of(cell.clone()).patch_style(Style::default().add_modifier(Modifier::BOLD))); } for tag in tags { if !spans.is_empty() { spans.push(Span::raw(" ")); } spans.push(Span::styled(format!("#{tag}"), Style::default().fg(tag_color(tag).into()))); } Some(Line::from(spans)) } /// The project name as it fits beside whatever the row already carries. /// /// The mark, the id and the blocked mark are the ticket's identity and its state, and /// neither gives way, so the label takes what the row has left and ends in an ellipsis /// where it was cut. It is measured before the due date, which is what gives the project /// the narrow column: on the All tab the project matters more than the date, and /// `corner_line` drops the date when what is left will not hold it. /// /// `used` is measured off the spans already built rather than added up from the widths /// they are supposed to have. The hand-written version left out the space after the /// priority mark, so the label was handed one cell more than the row had and a narrow /// column drew a card one character wider than its column. /// /// Under three characters there is nothing left to say, and a single letter and a dot /// would only crowd the corner, so the label goes instead. fn project_label(name: &str, width: u16, used: usize) -> Option { // The space between the label and what precedes it. let room = (width as usize).checked_sub(used + 1)?; if room < 3 { return None; } match name.chars().count() <= room { true => Some(name.to_string()), false => Some(with_ellipsis(name, room)), } } /// A set due in the timestamp colour, an unset one dimmed, per the colour guideline. /// /// The date part only: the field is not validated, so it can hold a time as well, and a /// corner has no room to spare on one. fn due_span(due: &str) -> Option> { let colour = match is_unknown_value(due) { true => Color::Grey, false => Color::Cyan, }; Some(Span::styled(due_date(due).to_string(), Style::default().fg(colour.into()))) } /// `left` at the left, `right` at the right, with the gap between them. /// /// The right-hand corner is dropped whole when it will not fit rather than truncated or /// wrapped: half a date reads as a different date, and a card that reflows in a narrow /// column changes height, which the scroll would then have to chase. The left corner is /// the ticket's identity and always stays. fn corner_line( left: Vec>, right: Option>, width: u16, ) -> Line<'static> { let mut spans = left; let used = spans_width(&spans); let Some(right) = right else { return Line::from(spans); }; let wanted = right.content.chars().count(); // One space minimum, so the two corners never touch. No room at all and the right // corner goes rather than the line growing past the column. if let Some(gap) = (width as usize).checked_sub(used + wanted + 1) { spans.push(Span::raw(" ".repeat(gap + 1))); spans.push(right); } Line::from(spans) } /// The cells a run of spans takes, counted in characters rather than bytes. fn spans_width(spans: &[Span<'static>]) -> usize { spans.iter().map(|span| span.content.chars().count()).sum() } /// The title over one row or two, wrapped on spaces, cut with an ellipsis if even two /// are not enough. /// /// One row when one is enough: a second, blank row on every short ticket would spend /// the column's height on nothing. A word longer than the column is broken rather than /// left to overflow, since a uuid or a path has no space to break at. fn title_lines(title: &str, width: u16) -> Vec { let width = width.max(1) as usize; let mut rows: Vec = Vec::new(); let mut row = String::new(); for word in title.split_whitespace() { let room = width - row.chars().count().min(width); let space = usize::from(!row.is_empty()); if word.chars().count() + space <= room { if space == 1 { row.push(' '); } row.push_str(word); continue; } if !row.is_empty() { rows.push(std::mem::take(&mut row)); } // A word too long for a row of its own is broken across rows. for chunk in chars_in_chunks(word, width) { if row.chars().count() + chunk.chars().count() > width { rows.push(std::mem::take(&mut row)); } row.push_str(&chunk); } } if !row.is_empty() { rows.push(row); } if rows.len() > 2 { rows.truncate(2); rows[1] = with_ellipsis(&rows[1], width); } if rows.is_empty() { rows.push(String::new()); } rows } fn chars_in_chunks(word: &str, width: usize) -> Vec { let chars: Vec = word.chars().collect(); chars.chunks(width).map(|chunk| chunk.iter().collect()).collect() } /// The row with an ellipsis on the end, making room for it if the row is full. fn with_ellipsis(row: &str, width: usize) -> String { let keep = match row.chars().count() < width { true => row.chars().count(), false => width.saturating_sub(1), }; let mut cut: String = row.chars().take(keep).collect(); // Trailing space before an ellipsis reads as a gap rather than a cut. while cut.ends_with(' ') { cut.pop(); } cut.push('…'); cut } fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { // The prompt takes the whole row while it is open. The footer is one line and // already says what the state allows, and with every key going into the buffer the // key list it replaces describes nothing that currently works. if let Some(search) = &board.search { draw_search(frame, search, area); return; } // 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, ); return; } // And a notice takes it for the one keypress it lives, for a weaker reason than the // prompt's: every key still works while it is up. It is that a message squeezed in // beside the list would move every key in it, and the row is the only place on the // board that is not a ticket. Ordered after the prompt, which is an input and cannot // be covered, and a keypress clears the notice before it can open one anyway. if let Some(notice) = &board.notice { draw_notice(frame, notice, area); return; } // While done is hidden its count goes here, which is the board's version of the // summary line `ls` prints above a listing that leaves done out. let done = match board.show_done { true => "d hide done".to_string(), false => format!("d show done ({})", done_count(board)), }; // Only when there is a tab to move to, since the footer names keys that work. let tabs = match board.tabbed() { true => "tab project ", false => "", }; // The last slot answers the same question in every state: how to get out of here. `q` // takes off whatever is on top, so with a ticket open or a campaign selected the honest // answer is `ctrl-c`, the only key left that quits in one press. Naming `q quit` over // either would be the fault 1b78a24 was, a footer describing a key by what it used to // do — and with a campaign selected it names what that press actually does instead. let quit = match board.detail.is_some() || board.campaign().is_some() { true => "ctrl-c quit", false => "q quit", }; // `c` is named where a reader has to find it: on the board, with nothing selected. Over // an open ticket and on a board already filtered to a campaign it is left out, because // the frame's own border then says how to put the campaign away and the row is at its // width naming eight keys. Incomplete rather than wrong, which is the trade this row is // allowed to make: what it must never do is name a key by what it used to do. let campaign = match board.campaign().is_some() { true => "", false => "c campaign ", }; let keys = match board.detail { Some(_) => format!( " {tabs}←→↑↓ select pgup/pgdn scroll / search y copy id enter/q close {done} {quit} " ), None => format!( " {tabs}←→ column ↑↓ card / search {campaign}y copy id enter detail {done} {quit} " ), }; frame.render_widget( Paragraph::new(Span::styled(keys, Style::default().fg(Color::Grey.into()))), area, ); } /// What the last keypress did, where the keys would otherwise be. /// /// Red when nothing reached the clipboard, so a copy that did not happen does not read /// like one that did, and the default foreground when it did: the same division the /// prompt draws its query and its miss with. fn draw_notice(frame: &mut Frame, notice: &Notice, area: Rect) { let style = match notice.failed { true => Style::default().fg(Color::BrightRed.into()), false => Style::default(), }; frame.render_widget(Paragraph::new(Span::styled(format!(" {}", notice.text), style)), area); } /// The prompt, in place of the key list it would otherwise describe wrongly. /// /// The real terminal cursor goes after the query rather than a glyph standing in for /// one: ratatui shows the cursor only for a frame that asked for it, and that is also /// what tells the reader they are in an input while the query is still empty. /// /// What was typed is drawn in the default foreground and the keys in grey, because one /// of them is content and the other is chrome. A miss is said beside the query it is /// about, in brightred, since grey chrome is exactly what a reader skips. Colour /// accentuates here as it does on a card; the words carry the meaning either way. fn draw_search(frame: &mut Frame, search: &Search, area: Rect) { let prompt = format!(" /{}", search.query); let mut spans = vec![Span::raw(prompt.clone())]; if search.missed { spans.push(Span::styled(" no match", Style::default().fg(Color::BrightRed.into()))); } spans.push(Span::styled( " enter jump esc cancel ", Style::default().fg(Color::Grey.into()), )); frame.render_widget(Paragraph::new(Line::from(spans)), area); // Held on the row, so a query longer than the terminal leaves the cursor 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 .current() .columns .iter() .find(|column| column.status == DONE) .map_or(0, |column| column.cards.len()) } /// Where the campaign picker sits in the frame. /// /// 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. fn picker_overlay(area: Rect, rows: usize) -> Rect { let width = area .width .saturating_mul(3) .div_euclid(5) .max(20) .min(area.width); // A border row either side of the list. let wanted = u16::try_from(rows).unwrap_or(u16::MAX).saturating_add(2); let height = wanted.min(picker_height(area)); Rect { x: area.x + (area.width.saturating_sub(width)) / 2, y: area.y + (area.height.saturating_sub(height)) / 2, width, height, } } /// The tallest the picker's box can be, whatever its list holds. fn picker_height(area: Rect) -> u16 { area.height .saturating_sub(area.height / 4) .max(4) .min(area.height) } /// The rows the picker draws its list in, the border taken off either side. /// /// Measured against the tallest box it can be rather than the box it currently is, because /// the caller that scrolls is a keypress and has only the screen: a height that depended on /// the number of rows would make the scroll step depend on the list it is scrolling. A list /// short enough to fit anyway has nothing to scroll, so the two agree where it matters. fn picker_text_area(area: Rect) -> Rect { Rect { height: picker_height(area).saturating_sub(2), ..picker_overlay(area, 0) } } /// The campaign picker: one row per campaign, the highlighted one reversed. /// /// Each row is the short id, the campaign as a label, and the opening line of its /// description cut to what is left, which is the same three things in the same order the /// frame's title carries. The description is the field that gives way, because it is the /// only one of the three that is prose. /// /// The rows come off the tab rather than off the picker, so a campaign filed while the /// 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 text = overlay.inner(Margin::new(1, 1)); let lines: Vec = tab .campaigns .iter() .enumerate() .map(|(at, campaign)| picker_line(campaign, 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()), Style::default().fg(Color::Orange.into()), )); // Capped against blank space past the last row, the way an unfocused column is. let last = (lines.len() as u16).saturating_sub(text.height); frame.render_widget(Clear, overlay); frame.render_widget( Paragraph::new(lines) .block(block) .scroll((picker.offset.min(last), 0)), overlay, ); } /// 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 /// whatever colours are already on it. The summary is grey because it is context around the /// two things being chosen between, and it is cut with an ellipsis rather than dropped: half /// a sentence still says what a campaign is about, which is not true of half an id. fn picker_line(campaign: &CampaignRow, selected: bool, width: u16) -> Line<'static> { let emphasis = match selected { true => Modifier::REVERSED, false => Modifier::empty(), }; let mut spans = vec![Span::styled( format!("({})", short_id(&campaign.uuid)), Style::default().fg(Color::Red.into()).add_modifier(emphasis), )]; // Only a real codename, unlike a card, which falls back to the short id because it has // no other way to name the campaign. Here the id is the first thing on the row, so the // fallback would print it twice and say nothing the second time. if campaign.codename.is_some() { let label = campaign.label(); spans.push(Span::raw(" ")); spans.push(Span::styled( label.text.clone(), Style::default() .fg(label.color.unwrap_or(Color::Grey).into()) .add_modifier(emphasis | Modifier::BOLD), )); } // The project on the merge tab, where a campaign id does not say which board holds it. if let Some(project) = &campaign.project { spans.push(Span::raw(" ")); spans.push(Span::styled( project.clone(), Style::default().fg(Color::Grey.into()).add_modifier(emphasis), )); } // What the campaign is *called* takes the row first, and the prose takes what is left. // Under three characters there is nothing left to say, the bargain `project_label` makes. let used = spans_width(&spans); let summary = match campaign.summary.is_empty() { true => campaign.title.as_str(), false => campaign.summary.as_str(), }; if let Some(room) = (width as usize).checked_sub(used + 2).filter(|room| *room >= 3) { let cut = match summary.chars().count() <= room { true => summary.to_string(), false => with_ellipsis(summary, room), }; spans.push(Span::raw(" ")); spans.push(Span::styled( cut, Style::default().fg(Color::Grey.into()).add_modifier(emphasis), )); } Line::from(spans) } /// Where the detail overlay sits in the frame. /// /// Inset, so the board stays visible around the edges and the overlay reads as one. fn detail_overlay(area: Rect) -> Rect { let width = area.width.saturating_sub(area.width / 5).max(20); let height = area.height.saturating_sub(area.height / 6).max(6); Rect { x: area.x + (area.width.saturating_sub(width)) / 2, y: area.y + (area.height.saturating_sub(height)) / 2, width: width.min(area.width), height: height.min(area.height), } } /// The part of the overlay that holds text: the border takes a row and a column on /// either side, and the title sits on the top border rather than below it. fn detail_text_area(area: Rect) -> Rect { detail_overlay(area).inner(Margin::new(1, 1)) } /// How tall the detail body is once wrapped to `width`. /// /// Measured by the widget rather than counted by hand, since it wraps on words. A count /// of the raw lines would stop short of the end on a wrapped ticket, and one that /// ignored the wrapping the other way would run past it into blank space. /// /// The one place the number comes from. The scroll clamp and the page indicator are both /// derived from it, and two measurements are two numbers free to disagree: an indicator /// saying there is more to read where the scroll refuses to move is worse than no /// indicator at all. fn wrapped_height(detail: &Text<'static>, width: u16) -> u16 { let wrapped = Paragraph::new(detail.clone()) .wrap(Wrap { trim: false }) .line_count(width); u16::try_from(wrapped).unwrap_or(u16::MAX) } /// The furthest the detail view can scroll: the last screenful, and no further. fn last_offset(detail: &Text<'static>, text: Rect) -> u16 { wrapped_height(detail, text.width).saturating_sub(text.height) } /// The step `scroll_detail` takes, a screenful less the line kept for overlap. /// /// The page numbers are counted in it rather than in whole screenfuls, so the pages the /// indicator names are the ones the keys can actually land on. Counting by screenfuls /// would put a 30 line ticket in a 10 line viewport at `pg 3/3` two rows short of its /// end, since three presses are what it takes to get there. fn scroll_step(height: u16) -> u16 { height.saturating_sub(1).max(1) } /// Where the reader is, as `pg 2/5`, or `None` when there is nothing to say or no room /// to say it in. /// /// `offset` has to be clamped already and `last` is what it was clamped against, so this /// is arithmetic on the one wrapped measurement rather than a second look at the text. /// /// **The furthest offset is the last page by definition, not by division.** The clamp /// stops at `last`, which is the wrapped height less the viewport and not a page /// boundary, so the final screenful is partial: dividing there reads `pg 2/3` at the /// bottom of the ticket and claims there is more to read. fn page_indicator(offset: u16, last: u16, height: u16, overlay_width: u16) -> Option { // Nothing scrolls, so there are no pages to be on. A ticket that fits spends no // indicator, the way an untagged card spends no row on tags. if last == 0 { return None; } let step = scroll_step(height); let total = last.div_ceil(step).saturating_add(1); let page = match offset >= last { true => total, false => offset / step + 1, }; let indicator = format!(" pg {page}/{total} "); // Dropped whole rather than cut, the rule a card's corner follows: half a page number // reads as a different one. Measured against the inner width, since the two border // columns are not the indicator's to write on. The title cannot be crowded by this // however narrow the overlay gets, because the two sit on opposite borders. match indicator.chars().count() <= overlay_width.saturating_sub(2) as usize { true => Some(indicator), false => None, } } fn draw_detail(frame: &mut Frame, detail: &Detail, offset: u16, area: Rect) { let overlay = detail_overlay(area); let text = detail_text_area(area); // One measurement, two derivations. Clamped here as well as on the keypress: the // terminal may have been resized since, and a ticket read to its end can grow // shorter under a tick. Which is also what repages the indicator, since the wrapped // count and the viewport both move with the width. let last = wrapped_height(&detail.body, text.width).saturating_sub(text.height); let offset = offset.min(last); let mut block = Block::default() .borders(Borders::ALL) .border_style(Style::default().fg(Color::Cyan.into())) .title(Span::styled( detail_title(detail, overlay.width), Style::default().fg(Color::Orange.into()), )); // On the bottom border, so it costs no text row, which is the trade the title already // makes on the top one. Grey because it is chrome: it says where you are in the // ticket rather than anything about the ticket, so it takes the colour the footer // keys and a rendered checkbox take, and does not compete with the orange title. if let Some(indicator) = page_indicator(offset, last, text.height, overlay.width) { block = block.title_bottom( Line::from(Span::styled(indicator, Style::default().fg(Color::Grey.into()))) .right_aligned(), ); } frame.render_widget(Clear, overlay); frame.render_widget( Paragraph::new(detail.body.clone()) .block(block) .wrap(Wrap { trim: false }) .scroll((offset, 0)), overlay, ); } /// The overlay's title: the short id and the name of the ticket it has open. /// /// The id goes first because that is how every other view addresses a ticket, and the /// name after it because that is what the id is shorthand for. Both sit on the border /// rather than at the head of the paragraph, so reading to the end of a long ticket /// cannot carry them off the screen. /// /// The string is cut here rather than left to the renderer, which truncates an /// overlong title at whatever cell it reaches and would take the id with it. Cut /// against the inner width — a border column on either side is not the title's to /// write on — the id survives whole and the name ends in an ellipsis where it was /// trimmed. On an overlay too narrow for even the id, what fits is what shows. fn detail_title(detail: &Detail, overlay_width: u16) -> String { // The project rides in the prefix, beside the id, so what survives the cut is the // whole address rather than half of one. Absent on a single board and on a // project's own tab, where the overlay reads exactly as it always has. let project = match &detail.project { Some(name) => format!("{name} "), None => String::new(), }; let room = overlay_width.saturating_sub(2) as usize; let full = format!(" ({}) {}· {} ", detail.id, project, detail.title); if full.chars().count() <= room { return full; } let prefix = format!(" ({}) {}· ", detail.id, project); match room.checked_sub(prefix.chars().count() + 1) { Some(keep) if keep > 0 => { let name: String = detail.title.chars().take(keep).collect(); format!("{prefix}{name}…") } _ => full.chars().take(room).collect(), } } #[cfg(test)] mod tests { use super::*; use ratatui::Terminal; use ratatui::backend::TestBackend; /// A board on disk, since everything here is about reading a real tree. /// /// The directory stands in for a `.worklane`, so its parent is the temp directory /// and `project_name` reads the generated name off it. fn board_dir() -> PathBuf { let dir = std::env::temp_dir().join(format!("worklane-tui-{}", uuid::Uuid::new_v4())); for status in status_dirs() { std::fs::create_dir_all(dir.join(status)).unwrap(); } dir } /// The single board case, which is what most of these tests are about. fn one_board(dir: &Path) -> Board { Board::new(vec![project_at(dir)]).unwrap() } fn project_at(dir: &Path) -> Project { Project { name: project_name(dir), dir: dir.to_path_buf(), } } /// Several boards, named so a test can tell their cards apart. fn boards(dirs: &[(&str, &Path)]) -> Board { Board::new( dirs.iter() .map(|(name, dir)| Project { name: name.to_string(), dir: dir.to_path_buf(), }) .collect(), ) .unwrap() } fn selected_title(board: &Board) -> Option { board.selected().map(|card| card.ticket.title.clone()) } fn write_ticket(dir: &Path, status: &str, uuid: &str, title: &str, extra: &str) -> PathBuf { let path = dir.join(status).join(format!("{}_{}.md", uuid, slug(title))); std::fs::write( &path, format!( "# {title}\n\n## Description\nA description.\n\n## Acceptance Criteria\n\ - [ ] Crit one\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ - **Tags**: _None_\n- **Due**: 2026-12-31\n- **Owner**: alice\n\ - **Created At**: 2026-08-21 02:00:00\n- **Status**: {status}\n{extra}" ), ) .unwrap(); path } /// A section of numbered lines, so a test can say which of them is on screen. /// /// Long enough not to fit any overlay the tests draw, which is true of every real /// ticket in the repo as well. fn long_section(lines: usize) -> String { let body: String = (1..=lines).map(|n| format!("Line {n:03}\n")).collect(); format!("\n## Notes\n{body}") } /// The screen the scrolling tests draw on, so the keypress and the draw measure the /// same overlay. const SCREEN: Size = Size { width: 120, height: 20 }; /// One board, no campaign selected: the chrome most of these tests measure against. const PLAIN: Chrome = Chrome { tabbed: false, campaign: false }; /// The rendered buffer as lines of text, escapes and styling dropped. fn render(board: &Board, width: u16, height: u16) -> Vec { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); (0..buffer.area.height) .map(|y| { (0..buffer.area.width) .map(|x| buffer[(x, y)].symbol()) .collect::() }) .collect() } /// The column headings, which sit on the top border row. /// /// That row alone, because the footer names done as well: a whole-screen search for /// `done (0)` passes on the footer whether the column is drawn or not, which is how /// three of these tests came to be vacuous the moment done was hidden. Located /// through the layout rather than assumed to be row zero, since a tab row sits above /// it when more than one board is monitored. fn headings(board: &Board, width: u16, height: u16) -> String { let top = board_area(Size { width, height }, board.chrome()).y as usize; render(board, width, height).remove(top) } /// The tab row, which is the top row whenever it is drawn at all. fn tab_row(board: &Board, width: u16, height: u16) -> String { render(board, width, height).remove(0) } fn footer(board: &Board, width: u16, height: u16) -> String { render(board, width, height).pop().expect("no rows rendered") } /// The overlay's top border row, where the block title sits. /// /// Counted in characters rather than bytes: the rows carry multi-byte glyphs. fn overlay_title_row(lines: &[String], width: u16, height: u16) -> String { let overlay = detail_overlay(Rect::new(0, 0, width, height)); lines[overlay.y as usize] .chars() .skip(overlay.x as usize) .take(overlay.width as usize) .collect() } /// The overlay's bottom border row, where the page indicator sits. fn overlay_bottom_row(lines: &[String], width: u16, height: u16) -> String { let overlay = detail_overlay(Rect::new(0, 0, width, height)); lines[(overlay.y + overlay.height - 1) as usize] .chars() .skip(overlay.x as usize) .take(overlay.width as usize) .collect() } /// A board with one ticket long enough to scroll, opened on it. fn scrolling_board(dir: &Path, lines: usize) -> Board { write_ticket( dir, "backlog", "11111111-0000-4000-8000-000000000000", "A long one", &long_section(lines), ); let mut board = one_board(dir); board.toggle_detail(); board } #[test] fn the_board_draws_the_four_statuses_as_columns_once_done_is_shown() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); write_ticket(&dir, "committed", "22222222-0000-4000-8000-000000000000", "Second one", ""); let mut board = one_board(&dir); board.toggle_done(SCREEN); let row = headings(&board, 120, 20); for heading in ["backlog (1)", "committed (1)", "reviewing (0)", "done (0)"] { assert!(row.contains(heading), "no {heading:?} in:\n{row}"); } } /// Done only grows, and it is the column least often read. `ls` already leaves it /// out of its listing while counting it in the summary; this is the same opinion. #[test] fn the_board_opens_with_the_done_column_hidden() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished one", ""); let board = one_board(&dir); assert!(!board.show_done, "done was drawn at startup"); let row = headings(&board, 120, 20); for heading in ["backlog (1)", "committed (0)", "reviewing (0)"] { assert!(row.contains(heading), "no {heading:?} in:\n{row}"); } assert!(!row.contains("done"), "done is still a column:\n{row}"); // Hidden, not unread: the count is right and revealing it needs no rescan. assert_eq!(board.current().columns.len(), 4); assert_eq!(board.visible().len(), 3); assert_eq!(done_count(&board), 1); assert!( !render(&board, 120, 20).join("\n").contains("Finished one"), "a hidden done ticket was drawn" ); } /// The three that are left take the width done was using, rather than leaving a gap. #[test] fn the_visible_columns_share_the_full_width() { let dir = board_dir(); let mut board = one_board(&dir); let hidden = headings(&board, 120, 20); assert_eq!(hidden.matches('┌').count(), 3, "{hidden}"); assert!(hidden.ends_with('┐'), "the columns stop short of the edge:\n{hidden}"); board.toggle_done(SCREEN); let shown = headings(&board, 120, 20); assert_eq!(shown.matches('┌').count(), 4, "{shown}"); assert!(shown.ends_with('┐'), "{shown}"); } /// Hiding is a prefix of the columns, which only holds while done is last. The /// board leans on that, so the assumption is pinned rather than assumed. #[test] fn the_done_column_is_last() { assert_eq!(status_dirs().last(), Some(&DONE)); } #[test] fn the_footer_names_the_key_and_carries_the_count_while_done_is_hidden() { let dir = board_dir(); for (n, title) in [("44444444", "One"), ("55555555", "Two")] { write_ticket(&dir, "done", &format!("{n}-0000-4000-8000-000000000000"), title, ""); } let mut board = one_board(&dir); let hidden = footer(&board, 120, 20); assert!(hidden.contains("d show done (2)"), "{hidden}"); board.toggle_done(SCREEN); let shown = footer(&board, 120, 20); assert!(shown.contains("d hide done"), "{shown}"); // With the column drawn, its own heading carries the count. assert!(!shown.contains("(2)"), "the count is printed twice:\n{shown}"); } /// The modal footer names it too, since the key works with a ticket open. #[test] fn the_detail_footer_also_names_the_done_key() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); let row = footer(&board, 120, 20); assert!(row.contains("d show done (0)"), "{row}"); assert!(row.contains("pgup/pgdn scroll"), "{row}"); } /// Hiding the column under the selection has to move it, or it points at nothing. #[test] fn hiding_done_under_the_selection_moves_it_to_the_last_visible_column() { let dir = board_dir(); write_ticket(&dir, "reviewing", "33333333-0000-4000-8000-000000000000", "Ready", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.toggle_done(SCREEN); board.select_column(3, SCREEN); assert_eq!(selected_title(&board), Some("Finished".to_string())); board.toggle_done(SCREEN); assert_eq!(board.current().column, 2, "the selection stayed on a column that is gone"); assert_eq!(selected_title(&board), Some("Ready".to_string())); } /// And an open detail of a done ticket goes with it: showing a ticket that is no /// longer on the board is worse than closing, and swapping it for a different /// ticket without saying so is worse than both. #[test] fn hiding_done_closes_a_detail_view_of_a_done_ticket() { let dir = board_dir(); write_ticket(&dir, "reviewing", "33333333-0000-4000-8000-000000000000", "Ready", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.toggle_done(SCREEN); board.select_column(3, SCREEN); board.toggle_detail(); assert!(board.detail.is_some()); board.toggle_done(SCREEN); assert!(board.detail.is_none(), "{:?}", board.detail); } /// A ticket being read in a column that is not going anywhere stays open. #[test] fn hiding_done_leaves_a_detail_view_of_another_ticket_open() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); board.toggle_done(SCREEN); board.toggle_done(SCREEN); assert!(board.detail.is_some(), "an unrelated detail view was closed"); } /// Done is appended rather than inserted, so showing it moves nothing. #[test] fn showing_done_again_leaves_the_selection_where_it_was() { let dir = board_dir(); write_ticket(&dir, "committed", "22222222-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Beta", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.select_column(1, SCREEN); board.select_card(1, SCREEN); let (column, card) = (board.current().column, board.current().card); board.toggle_done(SCREEN); assert_eq!((board.current().column, board.current().card), (column, card)); assert_eq!(selected_title(&board), Some("Beta".to_string())); } /// The selection cannot walk into a column that is not drawn. #[test] fn the_selection_stops_at_the_last_visible_column() { let dir = board_dir(); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.select_column(9, SCREEN); assert_eq!(board.current().column, 2); assert!(board.selected().is_none(), "the selection reached the done column"); board.toggle_done(SCREEN); board.select_column(9, SCREEN); assert_eq!(board.current().column, 3); assert_eq!(selected_title(&board), Some("Finished".to_string())); } /// The card has to carry enough to identify the ticket without opening it. #[test] fn a_card_shows_the_short_id_title_owner_and_due() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let board = one_board(&dir); let screen = render(&board, 120, 20).join("\n"); assert!(screen.contains("(1111111)"), "no short id in:\n{screen}"); assert!(screen.contains("First one"), "no title in:\n{screen}"); assert!(screen.contains("alice"), "no owner in:\n{screen}"); assert!(screen.contains("2026-12-31"), "no due date in:\n{screen}"); } /// One ticket in backlog, written by hand so a test can set the fields the shared /// fixture pins: the due value, and the criteria. fn write_card(dir: &Path, title: &str, due: &str, criteria: &str) { write_tagged_card(dir, title, due, criteria, "_None_"); } /// The same, with the Tags field a test can set. Untagged is `_None_`, which is /// what `add` writes for a ticket given no tags. fn write_tagged_card(dir: &Path, title: &str, due: &str, criteria: &str, tags: &str) { let uuid = "11111111-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{}_{}.md", uuid, slug(title))), format!( "# {title}\n\n## Description\nA description.\n\n## Acceptance Criteria\n\ {criteria}\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ - **Tags**: {tags}\n- **Due**: {due}\n- **Owner**: alice\n\ - **Created At**: 2026-08-21 02:00:00\n- **Status**: backlog\n" ), ) .unwrap(); } /// The same again, with the Campaign field a test can set. /// /// A separate fixture rather than a sixth parameter on `write_tagged_card`: the /// callers that care about tags do not care about campaigns, and five string /// arguments in a row is what the Rust Style rule in AGENTS.md warns about. fn write_member_card(dir: &Path, title: &str, tags: &str, campaign: &str) { let uuid = "11111111-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{}_{}.md", uuid, slug(title))), format!( "# {title}\n\n## Description\nA description.\n\n## Acceptance Criteria\n\ - [ ] One\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ - **Tags**: {tags}\n- **Due**: 2026-12-31\n- **Owner**: alice\n\ - **Created At**: 2026-08-21 02:00:00\n- **Campaign**: {campaign}\n\ - **Status**: backlog\n" ), ) .unwrap(); } /// A campaign on disk, since the board reads the directory rather than being told. /// /// The codename is written as `_Not set_` when a test does not give one, which is what /// `campaign add` writes for a campaign filed without one. fn write_campaign(dir: &Path, uuid: &str, title: &str, codename: &str, description: &str) { let campaigns = dir.join(CAMPAIGNS_DIR); std::fs::create_dir_all(&campaigns).unwrap(); let codename = match codename.is_empty() { true => NOT_SET, false => codename, }; std::fs::write( campaigns.join(format!("{}_{}.md", uuid, slug(title))), format!( "# {title}\n\n## Description\n{description}\n\n## Metadata\n\n\ - **ID**: {uuid}\n- **Codename**: {codename}\n- **Owner**: alice\n\ - **Created At**: 2026-08-21 02:00:00\n" ), ) .unwrap(); } /// The rows of the only card on the board, at the width the column gives it. fn only_card(dir: &Path, width: u16, height: u16) -> Vec { let board = one_board(dir); let inner = card_width(Size { width, height }, board.chrome(), board.visible().len(), 0); let ticket = board.selected().expect("no card"); card_lines(ticket, false, inner) .iter() .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect()) .collect() } /// The rows of the only card, laid out in a column of exactly `inner` characters. /// /// Takes the width directly rather than deriving it from a terminal size, so a test /// about a narrow column says which width it means instead of solving `card_width` /// backwards for a screen that produces one. fn only_card_at(dir: &Path, inner: u16) -> Vec { let board = one_board(dir); let ticket = board.selected().expect("no card"); card_lines(ticket, false, inner) .iter() .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect()) .collect() } /// The foreground of the span whose text is `needle`, which `render` cannot show: /// it drops styling on the way out of the buffer. fn card_colour(dir: &Path, width: u16, needle: &str) -> Option { let board = one_board(dir); let inner = card_width(Size { width, height: 20 }, board.chrome(), board.visible().len(), 0); let ticket = board.selected().expect("no card"); card_lines(ticket, false, inner) .iter() .flat_map(|line| line.spans.clone()) .find(|span| span.content == needle) .and_then(|span| span.style.fg) } /// worklane's own titles are routinely longer than a quarter of a terminal, and one /// row cut them mid-word with nothing to say so. #[test] fn a_long_title_takes_two_rows_and_is_cut_visibly() { let dir = board_dir(); // Three rows' worth at the width three columns give a 120 wide terminal, so the // second row has to end in a cut rather than the title simply fitting. write_card( &dir, "A title long enough to need a second row, and then a third one after that, \ which is where it has to give up", "2026-12-31", "- [ ] One", ); let rows = only_card(&dir, 120, 20); let inner = card_width(Size { width: 120, height: 20 }, PLAIN, 3, 0) as usize; assert_eq!(rows.len(), 5, "expected two title rows and a blank: {rows:?}"); assert!(rows[1].starts_with("A title long"), "{rows:?}"); // Wrapped on a space, not cut mid-word, where there was room to choose. assert!(!rows[1].ends_with('…'), "the first row was cut: {rows:?}"); assert!(rows[2].ends_with('…'), "the cut is invisible: {rows:?}"); for row in &rows { assert!(row.chars().count() <= inner, "row past the column: {row:?}"); } } /// A tagged ticket says so on the card: the Tags field was invisible on the board, /// so nothing told you a ticket was tagged bug without opening it. #[test] fn a_card_shows_its_tags_under_the_title() { let dir = board_dir(); write_tagged_card(&dir, "Short", "2026-12-31", "- [ ] One", "cli, tui"); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 5, "the tag row is missing: {rows:?}"); assert_eq!(rows[1], "Short"); assert_eq!(rows[2], "#cli #tui"); assert!(rows[3].starts_with("alice"), "the owner moved: {rows:?}"); } /// Each tag carries its own colour, so the row can be scanned for one tag rather /// than read word by word. The row used to be a single grey span, which is what /// made a card of three tags one undifferentiated run. #[test] fn each_tag_on_a_card_carries_its_own_colour() { let dir = board_dir(); write_tagged_card(&dir, "Short", "2026-12-31", "- [ ] One", "cli, docs"); let cli = card_colour(&dir, 120, "#cli"); let docs = card_colour(&dir, 120, "#docs"); // Through `tag_color`, not against a literal: the card has to use the mapping, // and the mapping is pinned by its own test in util.rs. assert_eq!(cli, Some(tag_color("cli").into())); assert_eq!(docs, Some(tag_color("docs").into())); assert_ne!(cli, docs, "two tags rendered in one colour"); assert_ne!(cli, Some(Color::Grey.into()), "the row is still flat grey"); } /// And an untagged one spends no row on them, the way a short title spends no /// second row. #[test] fn an_untagged_card_spends_no_row_on_tags() { let dir = board_dir(); write_tagged_card(&dir, "Short", "2026-12-31", "- [ ] One", "_None_"); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "{rows:?}"); assert!(!rows.iter().any(|row| row.contains('#')), "{rows:?}"); } /// A row too wide for the column goes whole, the rule a corner follows: a cut list /// reads as a shorter one, and bug and bugfix cut to the same width say the same /// thing. #[test] fn a_tag_row_too_wide_for_the_column_is_dropped_whole() { let dir = board_dir(); write_tagged_card(&dir, "Short", "2026-12-31", "- [ ] One", "frontend, operations"); // One character short of "#frontend #operations", and one over it. let narrow = only_card_at(&dir, 20); assert_eq!(narrow.len(), 4, "the row was kept: {narrow:?}"); assert!(!narrow.iter().any(|row| row.contains('#')), "{narrow:?}"); let fits = only_card_at(&dir, 21); assert_eq!(fits[2], "#frontend #operations", "{fits:?}"); } /// And a title that fits gets one row, or the second is wasted on every short /// ticket in the column. #[test] fn a_short_title_leaves_the_card_four_rows() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [ ] One"); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "{rows:?}"); assert_eq!(rows[1], "Short"); } /// The corners: id and due on top, owner and progress at the bottom. #[test] fn the_due_date_and_the_criteria_count_sit_on_the_right() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two\n- [ ] Three"); let rows = only_card(&dir, 120, 20); assert!(rows[0].starts_with("\u{25cf}\u{25d0} (1111111)"), "{rows:?}"); assert!(rows[0].ends_with("2026-12-31"), "the due is not on the right: {rows:?}"); assert!(rows[2].starts_with("alice"), "{rows:?}"); assert!(rows[2].ends_with("[1/3]"), "the count is not on the right: {rows:?}"); } /// The field is not validated, so it can hold a time. A corner has no room for one. #[test] fn a_due_with_a_time_shows_the_date_only() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31 09:30:00", "- [ ] One"); let rows = only_card(&dir, 120, 20); assert!(rows[0].ends_with("2026-12-31"), "{rows:?}"); assert!(!rows[0].contains("09:30"), "the time reached the card: {rows:?}"); } /// Greyed like everywhere else, rather than left as an empty corner. The set case is /// the timestamp colour, which is what makes the corner worth looking at. #[test] fn an_unset_due_is_dimmed_and_a_set_one_carries_the_timestamp_colour() { let dir = board_dir(); write_card(&dir, "Short", "_Not set_", "- [ ] One"); assert_eq!( card_colour(&dir, 120, "_Not set_"), Some(Color::Grey.into()), "an unset due is not dimmed" ); let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [ ] One"); assert_eq!(card_colour(&dir, 120, "2026-12-31"), Some(Color::Cyan.into())); } /// `[0/0]` says less than saying nothing. #[test] fn a_ticket_with_no_criteria_shows_no_count() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "_No acceptance criteria provided._"); let rows = only_card(&dir, 120, 20); assert_eq!(rows[2], "alice", "a count appeared from nowhere: {rows:?}"); } /// Counted through `criteria()`, so the card and the numbers `show` prints cannot /// disagree: a checkbox in a description is not a criterion in either. #[test] fn a_checkbox_outside_the_criteria_section_is_not_counted() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{uuid}_short.md")), format!( "# Short\n\n## Description\n- [x] not a criterion\n\n## Acceptance Criteria\n\ - [x] One\n- [ ] Two\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ - **Due**: 2026-12-31\n- **Owner**: alice\n- **Status**: backlog\n" ), ) .unwrap(); let rows = only_card(&dir, 120, 20); assert!(rows[2].ends_with("[1/2]"), "the description was counted: {rows:?}"); } /// A column too narrow for both corners keeps the identity and drops the rest, /// rather than overflowing the border or reflowing to a taller card. #[test] fn a_narrow_column_drops_the_right_corner() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [ ] One"); let rows = only_card(&dir, 52, 14); let inner = card_width(Size { width: 52, height: 14 }, PLAIN, 3, 0) as usize; assert!(rows[0].starts_with("\u{25cf}\u{25d0} (1111111)"), "{rows:?}"); assert!(!rows[0].contains("2026"), "the due overran the column: {rows:?}"); for row in &rows { assert!(row.chars().count() <= inner, "row past the column: {row:?}"); } } /// An empty status is a column with nothing in it, not a column that is missing. #[test] fn an_empty_status_renders_as_an_empty_column() { let dir = board_dir(); let mut board = one_board(&dir); assert_eq!(board.current().columns.len(), 4); board.toggle_done(SCREEN); let row = headings(&board, 120, 20); for status in status_dirs() { assert!(row.contains(&format!("{status} (0)")), "{row}"); } } /// Even with a status directory absent altogether, the board keeps its shape. #[test] fn a_missing_status_directory_is_still_a_column() { let dir = board_dir(); std::fs::remove_dir_all(dir.join(DONE)).unwrap(); let mut board = one_board(&dir); assert_eq!(board.current().columns.len(), 4); board.toggle_done(SCREEN); assert!(headings(&board, 120, 20).contains("done (0)")); } #[test] fn the_digest_is_stable_when_nothing_changes() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); assert_eq!(digest(&dir), digest(&dir)); } #[test] fn the_digest_moves_when_a_ticket_is_created_or_moved() { let dir = board_dir(); let before = digest(&dir); let path = write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let created = digest(&dir); assert_ne!(before, created, "a new ticket went unnoticed"); let moved = dir.join("committed").join(path.file_name().unwrap()); std::fs::rename(&path, &moved).unwrap(); assert_ne!(created, digest(&dir), "a moved ticket went unnoticed"); std::fs::remove_file(&moved).unwrap(); assert_eq!(before, digest(&dir), "a deleted ticket left a trace"); } /// The case a directory watch would miss: no create, no rename, only the body. #[test] fn the_digest_moves_when_a_ticket_is_edited_in_place() { let dir = board_dir(); let path = write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let before = digest(&dir); let content = std::fs::read_to_string(&path).unwrap(); std::fs::write(&path, content.replace("A description.", "A longer description.")).unwrap(); assert_ne!(before, digest(&dir), "an in-place edit went unnoticed"); } /// And the harder half of it: an edit that does not change the length either, so /// only the modified time gives it away. #[test] fn the_digest_moves_on_an_edit_of_the_same_length() { let dir = board_dir(); let path = write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let content = std::fs::read_to_string(&path).unwrap(); let same_length = content.replace("A description.", "A descriptionA"); assert_eq!(content.len(), same_length.len(), "the fixture changed length"); std::fs::write(&path, &same_length).unwrap(); let before = digest(&dir); // Stamped rather than slept on, so the test does not depend on how coarse the // filesystem's timestamps are. let file = std::fs::File::options().write(true).open(&path).unwrap(); file.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000)) .unwrap(); assert_ne!(before, digest(&dir), "a same-length edit went unnoticed"); } /// A comment added elsewhere has to reach the detail view, so it counts as a change. #[test] fn the_digest_moves_when_a_comment_is_added() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let before = digest(&dir); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA note from elsewhere.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); assert_ne!(before, digest(&dir), "a new comment went unnoticed"); } #[test] fn navigation_moves_between_columns_and_cards() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", ""); write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Gamma", ""); let mut board = one_board(&dir); assert_eq!(selected_title(&board), Some("Alpha".to_string())); board.select_card(1, SCREEN); assert_eq!(selected_title(&board), Some("Beta".to_string())); // Clamped at both ends rather than wrapping board.select_card(5, SCREEN); assert_eq!(selected_title(&board), Some("Beta".to_string())); board.select_card(-9, SCREEN); assert_eq!(selected_title(&board), Some("Alpha".to_string())); board.select_column(1, SCREEN); assert_eq!(selected_title(&board), Some("Gamma".to_string())); // reviewing is empty, so there is nothing selected there board.select_column(1, SCREEN); assert!(board.selected().is_none()); board.select_column(-9, SCREEN); assert_eq!(board.current().column, 0); } /// Moving from a column with three cards to one with one must not leave the /// selection pointing past the end. #[test] fn the_card_index_is_clamped_when_the_column_is_shorter() { let dir = board_dir(); for (n, title) in [ ("11111111", "Alpha"), ("22222222", "Beta"), ("33333333", "Gamma"), ] { write_ticket(&dir, "backlog", &format!("{n}-0000-4000-8000-000000000000"), title, ""); } write_ticket(&dir, "committed", "44444444-0000-4000-8000-000000000000", "Delta", ""); let mut board = one_board(&dir); board.select_card(2, SCREEN); board.select_column(1, SCREEN); assert_eq!(board.current().card, 0); assert_eq!(selected_title(&board), Some("Delta".to_string())); } /// A column long enough that one window cannot hold it: twelve cards at four lines /// each against seventeen visible rows on [`SCREEN`]. fn fill_column(dir: &Path, status: &str, count: usize) { for n in 1..=count { write_ticket( dir, status, &format!("{n:08}-0000-4000-8000-000000000000"), &format!("Ticket {n:02}"), "", ); } } /// The reported bug: walking the selection down past the fold left the highlight on /// a card the window could not see, so from the keyboard nothing appeared to move. #[test] fn selecting_down_past_the_fold_brings_the_selected_card_into_view() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); let top = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(top.contains("Ticket 01"), "{top}"); assert!(!top.contains("Ticket 12"), "the fixture fits without scrolling:\n{top}"); board.select_card(11, SCREEN); let scrolled = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( scrolled.contains("Ticket 12"), "the selection fell below the fold:\n{scrolled}" ); assert!(!scrolled.contains("Ticket 01"), "nothing scrolled:\n{scrolled}"); } /// And back up again: reaching the top returns the column to its head. #[test] fn selecting_up_scrolls_back_to_the_top() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); board.select_card(11, SCREEN); assert_eq!(board.current().offsets[0], 31); board.select_card(-99, SCREEN); assert_eq!(board.current().offsets[0], 0, "the column stayed where the bottom left it"); let top = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(top.contains("Ticket 01"), "{top}"); assert!(!top.contains("Ticket 12"), "{top}"); } /// Down stops at the last card rather than running into blank space past it, and /// the last card is what ends the view. #[test] fn the_column_scroll_stops_at_the_last_card() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); // More downs than the column has, since the clamp and the cap are what stop it. for _ in 0..30 { board.select_card(1, SCREEN); } assert_eq!(board.current().card, 11); // Twelve cards at four lines, seventeen visible rows. assert_eq!(board.current().offsets[0], 48 - 17); let end = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(end.contains("Ticket 12"), "the end is out of reach:\n{end}"); assert!(!end.contains("Ticket 01"), "nothing scrolled:\n{end}"); } /// A ticket moved elsewhere shortens the column under the reader; the draw has to /// take that without waiting for a keypress, and the stored offset heals on the /// next one rather than throwing the reader anywhere first. #[test] fn a_tick_that_shrinks_a_column_keeps_the_selection_in_view() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); board.select_card(11, SCREEN); for n in 6..=12 { let uuid = format!("{n:08}-0000-4000-8000-000000000000"); let name = format!("{uuid}_ticket-{n:02}.md"); std::fs::remove_file(dir.join("backlog").join(name)).unwrap(); } assert!(board.tick().unwrap(), "the tick saw no change"); assert_eq!(board.current().card, 4, "the selection was not clamped to the new end"); let shrunk = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(shrunk.contains("Ticket 05"), "the new end is out of reach:\n{shrunk}"); assert!(!shrunk.contains("Ticket 06"), "{shrunk}"); // The stored value is stale until the next navigation, which is fine: the draw // corrected what was shown, and this is what writes the correction back. board.select_card(0, SCREEN); assert_eq!(board.current().offsets[0], 3); } /// Each column keeps its own place: leaving one must not snap it back to the top, /// and entering one must show the card the selection landed on, not its head. #[test] fn each_column_keeps_its_place_and_entering_one_shows_the_selection() { let dir = board_dir(); fill_column(&dir, "backlog", 12); for n in 1..=3 { write_ticket( &dir, "committed", &format!("{:08}-0000-4000-8000-000000000000", n + 20), &format!("Other {n:02}"), "", ); } let mut board = one_board(&dir); board.select_card(11, SCREEN); board.select_column(1, SCREEN); // The card index carried over and clamps onto committed's last card. assert_eq!(board.current().card, 2); let away = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( away.contains("Ticket 12"), "leaving snapped the column back to its top:\n{away}" ); assert!(away.contains("Other 03"), "{away}"); board.select_column(-1, SCREEN); // Back in backlog the selection is card 2: the index is shared and it moved // while we were away, so the column follows where it is now rather than // holding a scroll position for a highlight it no longer has. assert_eq!(board.current().card, 2); let back = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(back.contains("Ticket 03"), "returning lost the selection:\n{back}"); assert!(!back.contains("Ticket 12"), "{back}"); } /// The terminal can shrink between the keypress and the draw; the draw measures the /// real geometry, so the selection cannot be left above or below the fold. #[test] fn a_resize_between_the_keypress_and_the_draw_is_taken_at_draw_time() { let dir = board_dir(); fill_column(&dir, "backlog", 12); // Tall enough that every card fits, so the keypress stores no scroll at all. let roomy = Size { width: 120, height: 60 }; let mut board = one_board(&dir); board.select_card(11, roomy); assert_eq!(board.current().offsets[0], 0); let shrunk = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( shrunk.contains("Ticket 12"), "the smaller window hid the selection:\n{shrunk}" ); assert!(!shrunk.contains("Ticket 01"), "{shrunk}"); } #[test] fn the_detail_view_shows_the_body_and_the_comments() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA note from elsewhere.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); let mut board = one_board(&dir); assert!(board.detail.is_none()); board.toggle_detail(); let detail = board.detail.as_ref().expect("no detail"); assert!(detail.plain().contains("A description."), "{}", detail.plain()); assert!(detail.plain().contains("Crit one"), "{}", detail.plain()); assert!(detail.plain().contains("A note from elsewhere."), "{}", detail.plain()); assert!(detail.plain().contains("bob"), "{}", detail.plain()); // Plain text, since ratatui would print an escape as literal bytes assert!( !detail.plain().contains('\x1b'), "escapes reached the detail view: {:?}", detail.plain() ); board.toggle_detail(); assert!(board.detail.is_none()); } /// The reported bug: the modal showed a description, criteria and a metadata /// table belonging to a ticket it never named. #[test] fn the_detail_view_names_the_ticket_it_has_open() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); let screen = render(&board, SCREEN.width, SCREEN.height); let row = overlay_title_row(&screen, SCREEN.width, SCREEN.height); assert!(row.contains("(1111111)"), "no short id on the border:\n{row}"); assert!(row.contains("First one"), "no title on the border:\n{row}"); // The heading stays out of the text: `show` prints it and here the border // carries it, so it is on screen once rather than twice. assert!( !board.detail.as_ref().unwrap().plain().contains("First one"), "{:?}", board.detail ); } /// Scrolled to the end of a long ticket, the name is still where it started. #[test] fn the_name_stays_on_screen_at_the_end_of_a_long_ticket() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", &long_section(60), ); let mut board = one_board(&dir); board.toggle_detail(); for _ in 0..20 { board.scroll_detail(1, SCREEN); } let screen = render(&board, SCREEN.width, SCREEN.height); assert!( screen.join("\n").contains("Line 060"), "nothing scrolled:\n{}", screen.join("\n") ); let row = overlay_title_row(&screen, SCREEN.width, SCREEN.height); assert!(row.contains("(1111111)"), "the id scrolled away:\n{row}"); assert!(row.contains("First one"), "the title scrolled away:\n{row}"); } /// A title longer than the overlay is cut to the border — corners intact, id /// whole, ellipsis where the name gave up — not overrun and not dropped whole. #[test] fn a_long_title_is_cut_to_the_border_it_sits_on() { let dir = board_dir(); // Long enough to pass the overlay's inner width many times over, short enough // that its slug still fits a filename. let title = format!("Head {} tailmarker", "filler ".repeat(20)); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", &title, ""); let mut board = one_board(&dir); board.toggle_detail(); let screen = render(&board, SCREEN.width, SCREEN.height); let row = overlay_title_row(&screen, SCREEN.width, SCREEN.height); assert!(row.starts_with('┌'), "the left corner gave way:\n{row}"); assert!(row.ends_with('┐'), "the right corner gave way:\n{row}"); assert!(row.contains("(1111111)"), "the id did not survive the cut:\n{row}"); assert!(row.contains("Head"), "the border was left blank:\n{row}"); assert!(row.contains('…'), "the cut read as a complete title:\n{row}"); assert!(!row.contains("tailmarker"), "the title overran the border:\n{row}"); } /// A comment added while the detail view is open shows up on the next tick. #[test] fn a_tick_picks_up_a_comment_added_under_an_open_detail_view() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); assert!(!board.detail.as_ref().unwrap().plain().contains("A late note.")); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA late note.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); assert!(board.tick().unwrap(), "the tick saw no change"); assert!( board.detail.as_ref().unwrap().plain().contains("A late note."), "{:?}", board.detail ); } #[test] fn a_tick_with_nothing_changed_does_not_reload() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); assert!(!board.tick().unwrap()); } /// The reported bug: a ticket longer than the overlay had no way to be read past its /// first screenful, comments included. #[test] fn paging_down_reaches_the_end_of_a_long_ticket() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", &long_section(60)); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nThe last word.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); let top = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(top.contains("A description."), "not at the top:\n{top}"); assert!(!top.contains("Line 060"), "the fixture is too short:\n{top}"); // More pages than the ticket has, since the clamp is what stops it. for _ in 0..20 { board.scroll_detail(1, SCREEN); } let end = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(end.contains("Line 060"), "the end is out of reach:\n{end}"); assert!(end.contains("The last word."), "the comments are out of reach:\n{end}"); assert!(!end.contains("A description."), "nothing scrolled:\n{end}"); } /// The end of the scroll is the end of the text, not blank space past it, and the top /// of it is the top of the ticket. #[test] fn the_scroll_offset_stops_at_both_ends() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", &long_section(60), ); let mut board = one_board(&dir); board.toggle_detail(); for _ in 0..20 { board.scroll_detail(1, SCREEN); } let settled = board.offset; assert!(settled > 0, "a long ticket did not scroll at all"); board.scroll_detail(1, SCREEN); assert_eq!(board.offset, settled, "the offset ran past the end"); // The last screenful is full: text on the bottom row of the overlay, not the // blank space a clamp on the raw lines would have left there. let lines = render(&board, SCREEN.width, SCREEN.height); let text = detail_text_area(Rect::new(0, 0, SCREEN.width, SCREEN.height)); let bottom: String = lines[(text.bottom() - 1) as usize] .chars() .skip(text.x as usize) .take(text.width as usize) .collect(); assert!( !bottom.trim().is_empty(), "the last page ran into blank space:\n{}", lines.join("\n") ); board.scroll_detail(-40, SCREEN); assert_eq!(board.offset, 0, "the offset went above the top"); } /// A ticket that fits has nothing to scroll, so the keys do nothing to it. #[test] fn a_ticket_shorter_than_the_overlay_does_not_scroll() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); // Tall enough that the whole ticket is on screen at once. let roomy = Size { width: 120, height: 60 }; let mut board = one_board(&dir); board.toggle_detail(); let before = render(&board, roomy.width, roomy.height); board.scroll_detail(1, roomy); assert_eq!(board.offset, 0); assert_eq!(render(&board, roomy.width, roomy.height), before); } /// Up and down still move the selection with the detail view open, and the modal /// follows, which is the reason the scroll went on pgup and pgdn in the first place. #[test] fn the_selection_still_moves_under_an_open_detail_view() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", ""); let mut board = one_board(&dir); board.toggle_detail(); // By id in the text: the heading is stripped from the body, and the title // travels beside it for the block title instead. assert!( board.detail.as_ref().unwrap().plain().contains("11111111"), "{:?}", board.detail ); board.select_card(1, SCREEN); assert_eq!(selected_title(&board), Some("Beta".to_string())); assert!( board.detail.as_ref().unwrap().plain().contains("22222222"), "{:?}", board.detail ); } /// A newly selected ticket starts at its own top, not where the last one was left. #[test] fn the_scroll_offset_resets_when_the_selection_moves() { let dir = board_dir(); let long = long_section(60); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", &long); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", &long); write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Gamma", &long); let mut board = one_board(&dir); board.toggle_detail(); board.scroll_detail(1, SCREEN); assert!(board.offset > 0); board.select_card(1, SCREEN); assert_eq!(board.offset, 0, "the next card opened partway down"); board.scroll_detail(1, SCREEN); assert!(board.offset > 0); board.select_column(1, SCREEN); assert_eq!(board.offset, 0, "the next column opened partway down"); } #[test] fn the_scroll_offset_resets_when_the_detail_view_is_reopened() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", &long_section(60), ); let mut board = one_board(&dir); board.toggle_detail(); board.scroll_detail(1, SCREEN); assert!(board.offset > 0); board.toggle_detail(); board.toggle_detail(); assert_eq!(board.offset, 0, "the ticket reopened where it was left"); } /// An edit elsewhere in the tree must not throw the reader back to the top. #[test] fn a_tick_leaves_the_scroll_where_the_reader_put_it() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", &long_section(60)); let mut board = one_board(&dir); board.toggle_detail(); board.scroll_detail(1, SCREEN); let offset = board.offset; let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA late note.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); assert!(board.tick().unwrap(), "the tick saw no change"); assert_eq!(board.offset, offset); } // ------------------------------------------------------------- close or quit -- /// A reader pressing `q` to put a ticket away lost the whole board instead. #[test] fn dismiss_closes_an_open_overlay_and_leaves_the_board_up() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); assert!(board.detail.is_some(), "nothing was open to dismiss"); board.dismiss(SCREEN); assert!(board.detail.is_none(), "the overlay stayed open"); assert!(!board.should_quit, "closing a ticket took the board with it"); // Still on the ticket it was opened from, so the next `enter` reopens it. assert_eq!(selected_title(&board).as_deref(), Some("First one")); } /// With nothing over the board there is nothing to put away, so the key means what /// it has always meant. #[test] fn dismiss_quits_when_there_is_nothing_left_to_dismiss() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.dismiss(SCREEN); assert!(board.should_quit, "the board stayed up with nothing to close"); } /// The rule is `Board::dismiss`, which the two tests above reach. What is left to /// guard is the dispatch that cannot be reached: that both keys arrive there from /// one arm, and that `ctrl-c` still quits outright, since after this it is the only /// key that leaves the board while a ticket is open. /// /// Scanned the way `nothing_the_body_renders_asks_the_terminal_for_the_colour_decision` /// scans, and over whitespace-collapsed source so rustfmt cannot fail it. #[test] fn the_dispatch_gives_q_and_esc_one_arm_and_leaves_ctrl_c_quitting() { let source = include_str!("main.rs") .split_whitespace() .collect::>() .join(" "); assert!( source.contains("KeyCode::Esc | KeyCode::Char('q') => board.dismiss(screen),"), "`q` and `esc` mean one thing and have to reach `Board::dismiss` from one \ arm. Two arms carrying one rule is how a later edit changes it for one key \ and not the other, which is what this ticket already was." ); let at = source .find("KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL)") .expect("no ctrl-c arm in the dispatch"); // What the arm does, not what is anywhere near it: the arms after this one call // the board and would answer a whole-file search. let arm = &source[at..(at + 120).min(source.len())]; assert!( arm.contains("=> { board.should_quit = true }"), "`ctrl-c` has to keep quitting outright: with `q` closing an open ticket it \ is the only key that leaves the board in one press, and the footer says so. \ Found instead: {arm}" ); } /// The footer is what sent the reporter looking for their own mistake, so it has to /// name the keys that exist and only those. #[test] fn the_footer_names_the_keys_that_work() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", &long_section(60), ); let mut board = one_board(&dir); let closed = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(closed.contains("↑↓ card"), "{closed}"); assert!(closed.contains("enter detail"), "{closed}"); assert!(!closed.contains("scroll"), "a scroll offered with nothing open:\n{closed}"); assert!(closed.contains("q quit"), "nothing says how to leave:\n{closed}"); board.toggle_detail(); let open = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(open.contains("pgup/pgdn scroll"), "{open}"); assert!(open.contains("select"), "{open}"); assert!(open.contains("enter/q close"), "{open}"); } /// The other half of giving `q` a second meaning. A footer that goes on saying /// `q quit` over an open ticket describes the key by what it used to do, which is /// the fault 1b78a24 was in the other direction. #[test] fn the_footer_names_q_as_the_close_key_while_a_ticket_is_open() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); let row = footer(&board, 120, 20); assert!(row.contains("enter/q close"), "q is not named as the close key:\n{row}"); assert!(!row.contains("q quit"), "q still offered as the quit key:\n{row}"); // And the last slot still answers how to get out, which from here is the one // key that does it in a single press. assert!(row.contains("ctrl-c quit"), "nothing says what quits from here:\n{row}"); } // ------------------------------------------------------------------- searching -- /// A keypress with nothing held, which is what typing into a prompt is. fn typed(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) } fn letter(c: char) -> KeyEvent { typed(KeyCode::Char(c)) } /// Type a whole query into an open prompt, one key at a time, the way it arrives. fn type_query(board: &mut Board, query: &str) { for c in query.chars() { assert!(board.search_key(letter(c), SCREEN), "'{c}' was not taken"); } } /// A board with something to find in three columns, done included. fn searchable() -> PathBuf { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha first", ""); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta second", ""); write_ticket( &dir, "committed", "33333333-0000-4000-8000-000000000000", "Gamma third", "", ); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Delta finished", ""); dir } /// The prompt takes the row, and the board is still drawn behind it. #[test] fn the_prompt_replaces_the_footer_and_leaves_the_board_up() { let dir = searchable(); let mut board = one_board(&dir); board.open_search(); let screen = render(&board, SCREEN.width, SCREEN.height); let row = screen.last().expect("no rows rendered"); assert!(row.contains("enter jump"), "{row}"); assert!(row.contains("esc cancel"), "{row}"); assert!(!row.contains("q quit"), "the key list survived the prompt:\n{row}"); assert!( screen.join("\n").contains("Alpha first"), "the board went away behind the prompt" ); type_query(&mut board, "gam"); let row = footer(&board, SCREEN.width, SCREEN.height); assert!(row.contains("/gam"), "the query is not drawn: {row}"); } /// The whole point of an input mode. Every one of these keys does something on the /// board, and none of it may happen while a query is being typed. #[test] fn the_prompt_swallows_the_keys_that_are_bound_to_actions() { let dir = searchable(); let mut board = one_board(&dir); let before = selected_title(&board); board.open_search(); for key in [ letter('d'), letter('q'), letter('j'), letter('h'), typed(KeyCode::Up), typed(KeyCode::Down), typed(KeyCode::Left), typed(KeyCode::Right), typed(KeyCode::Tab), typed(KeyCode::PageDown), ] { assert!(board.search_key(key, SCREEN), "{key:?} was not taken"); } assert!(!board.show_done, "typing 'd' toggled the done column"); assert!(!board.should_quit, "typing 'q' quit the board"); assert_eq!(selected_title(&board), before, "an arrow moved the selection"); // The letters landed in the query; the keys that are not characters did not. assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some("dqjh")); } /// `ctrl-c` is the exception, since a terminal application always honours it. Every /// other control combination is swallowed and does nothing: it must not type its /// letter, and it must not reach the action arm that matches on the code alone. #[test] fn the_prompt_declines_ctrl_c_and_eats_every_other_control_key() { let dir = searchable(); let mut board = one_board(&dir); board.open_search(); let ctrl = |c: char| KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL); assert!( !board.search_key(ctrl('c'), SCREEN), "the prompt ate ctrl-c and left no way off the board" ); assert!(board.search_key(ctrl('d'), SCREEN), "ctrl-d fell through to the 'd' arm"); assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some("")); } /// Esc is consumed by the search, so it never reaches the arm that closes an overlay /// or quits, and it leaves the selection alone. #[test] fn esc_leaves_the_search_without_touching_the_selection_or_the_overlay() { let dir = searchable(); let mut board = one_board(&dir); board.toggle_detail(); let before = selected_title(&board); board.open_search(); type_query(&mut board, "gamma"); assert!(board.search_key(typed(KeyCode::Esc), SCREEN), "esc was not taken"); assert!(board.search.is_none(), "the prompt stayed open"); assert!(board.detail.is_some(), "esc reached the overlay arm"); assert!(!board.should_quit, "esc reached the quit arm"); assert_eq!(selected_title(&board), before, "the selection moved on a cancel"); // And the next esc is the overlay's again. assert!(!board.search_key(typed(KeyCode::Esc), SCREEN)); } /// The jump itself: enter takes the selection to the match and puts the prompt away. #[test] fn enter_selects_the_first_match_and_closes_the_prompt() { let dir = searchable(); let mut board = one_board(&dir); board.open_search(); type_query(&mut board, "beta"); assert!(board.search_key(typed(KeyCode::Enter), SCREEN), "enter was not taken"); assert!(board.search.is_none(), "the prompt stayed open on a hit"); assert_eq!(selected_title(&board).as_deref(), Some("Beta second")); } /// Reading order, left to right then top to bottom, which is how the board is laid /// out and how it is read. Not the rows on screen: the second match here is in a /// column the selection is not in. #[test] fn a_match_in_another_column_moves_the_column_and_scrolls_it_into_view() { let dir = board_dir(); // Enough cards above the match that its column has to scroll to show it. for n in 0..12 { write_ticket( &dir, "committed", &format!("1111111{n:x}-0000-4000-8000-000000000000"), &format!("Filler {n:02}"), "", ); } write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Alpha first", ""); write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Zulu last", ""); let mut board = one_board(&dir); board.open_search(); type_query(&mut board, "zulu"); board.search_key(typed(KeyCode::Enter), SCREEN); assert_eq!(selected_title(&board).as_deref(), Some("Zulu last")); assert_eq!(board.current().column, 1, "the column did not move with the card"); assert!( board.current().offsets[1] > 0, "the match's column was not scrolled to show it: {:?}", board.current().offsets ); // Drawn, not merely selected, which is what follow_selection is for. let screen = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(screen.contains("Zulu last"), "the match is off screen:\n{screen}"); } /// A hidden column is not on the board, so a match in it would put the highlight /// nowhere. Revealing done brings it back into range. #[test] fn a_hidden_done_column_is_never_searched() { let dir = searchable(); let mut board = one_board(&dir); let before = selected_title(&board); board.open_search(); type_query(&mut board, "delta"); board.search_key(typed(KeyCode::Enter), SCREEN); assert_eq!(selected_title(&board), before, "a hidden ticket was selected"); assert!( board.search.as_ref().is_some_and(|search| search.missed), "a match in a hidden column was reported as a hit" ); board.search_key(typed(KeyCode::Esc), SCREEN); board.toggle_done(SCREEN); board.open_search(); type_query(&mut board, "delta"); board.search_key(typed(KeyCode::Enter), SCREEN); assert_eq!(selected_title(&board).as_deref(), Some("Delta finished")); } /// The id and the title, both case insensitive, and nothing else on the ticket. #[test] fn a_search_reads_the_id_and_the_title_and_neither_case_matters() { let dir = searchable(); let board = one_board(&dir); let columns = board.visible(); let title_of = |hit: Option<(usize, usize)>| { hit.map(|(column, card)| columns[column].cards[card].ticket.title.clone()) }; assert_eq!(title_of(first_match(columns, "GAMMA")).as_deref(), Some("Gamma third")); assert_eq!(title_of(first_match(columns, "gamma")).as_deref(), Some("Gamma third")); // The seven characters the card prints, in either case. assert_eq!(title_of(first_match(columns, "3333333")).as_deref(), Some("Gamma third")); // On the ticket, but not in the id or the title. assert_eq!(first_match(columns, "A description."), None); assert_eq!(first_match(columns, "alice"), None); } /// Reading order is column by column, then down inside a column, so a query matching /// several cards lands on the leftmost and highest of them. #[test] fn the_first_match_is_the_first_in_reading_order() { let dir = searchable(); let board = one_board(&dir); // Every ticket here ends in a letter, so this matches all four. assert_eq!(first_match(board.visible(), "a"), Some((0, 0))); // Only the second column's, so the column index moves and the card index does not. assert_eq!(first_match(board.visible(), "gamma"), Some((1, 0))); } /// Doing nothing visible is what makes a reader retype a query that was already /// right, so a miss is said, the prompt stays open to be corrected, and the selection /// does not move. #[test] fn a_query_matching_nothing_says_so_and_leaves_the_selection_alone() { let dir = searchable(); let mut board = one_board(&dir); let before = selected_title(&board); board.open_search(); type_query(&mut board, "nothing here"); board.search_key(typed(KeyCode::Enter), SCREEN); assert_eq!(selected_title(&board), before, "the selection moved on a miss"); assert!(board.search.is_some(), "the prompt closed on a miss"); let row = footer(&board, SCREEN.width, SCREEN.height); assert!(row.contains("no match"), "the miss was silent: {row}"); // The message is about the query that missed, so the next edit takes it away. board.search_key(typed(KeyCode::Backspace), SCREEN); let row = footer(&board, SCREEN.width, SCREEN.height); assert!(!row.contains("no match"), "the miss outlived its query: {row}"); } /// Backspace edits, and enter on an empty query is a no-op rather than a match on /// everything: nobody pressing enter on a prompt they have not typed into means /// "select the first card on the board". #[test] fn backspace_edits_the_query_and_an_empty_one_matches_nothing() { let dir = searchable(); let mut board = one_board(&dir); let before = selected_title(&board); board.open_search(); type_query(&mut board, "gamma"); for _ in 0..3 { board.search_key(typed(KeyCode::Backspace), SCREEN); } assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some("ga")); // Past the start is empty, not a panic. for _ in 0..5 { board.search_key(typed(KeyCode::Backspace), SCREEN); } assert_eq!(board.search.as_ref().map(|s| s.query.as_str()), Some("")); board.search_key(typed(KeyCode::Enter), SCREEN); assert_eq!(selected_title(&board), before, "an empty query matched a card"); assert_eq!(first_match(board.visible(), ""), None); assert_eq!(first_match(board.visible(), " "), None); } /// An overlay follows the jump the way it follows the arrow keys, which is what /// `select_at` sharing `refresh_detail` with `select_card` buys. #[test] fn an_open_overlay_follows_the_jump() { let dir = searchable(); let mut board = one_board(&dir); board.toggle_detail(); assert!( board.detail.as_ref().unwrap().plain().contains("11111111"), "{:?}", board.detail ); board.open_search(); type_query(&mut board, "gamma"); board.search_key(typed(KeyCode::Enter), SCREEN); let detail = board.detail.as_ref().expect("the overlay closed on a jump"); assert_eq!(detail.title, "Gamma third"); assert!(detail.plain().contains("33333333"), "{detail:?}"); } /// With no prompt open the keyboard belongs to the action arms, so `search_key` has /// to take nothing at all. Otherwise the pre-branch would swallow the whole board. #[test] fn nothing_is_taken_while_no_prompt_is_open() { let dir = searchable(); let mut board = one_board(&dir); for key in [letter('d'), letter('q'), letter('/'), typed(KeyCode::Esc)] { assert!(!board.search_key(key, SCREEN), "{key:?} was taken with no prompt open"); } assert!(board.search.is_none()); } /// Both footers name the key, since the jump works with a ticket open as well: it /// moves the selection, and the overlay follows. #[test] fn both_footers_name_the_search_key() { let dir = searchable(); let mut board = one_board(&dir); assert!(footer(&board, 120, 20).contains("/ search")); board.toggle_detail(); assert!(footer(&board, 120, 20).contains("/ search")); } /// The real terminal cursor sits after the query, rather than a glyph standing in for /// one. ratatui shows the cursor only for a frame that asked for it, so this is also /// what says "you are typing" while the query is still empty. #[test] fn the_cursor_sits_after_the_query_on_the_prompt_row() { let dir = searchable(); let mut board = one_board(&dir); board.open_search(); type_query(&mut board, "gam"); let mut terminal = Terminal::new(TestBackend::new(SCREEN.width, SCREEN.height)).unwrap(); terminal.draw(|frame| draw(frame, &board)).unwrap(); let at = terminal.get_cursor_position().unwrap(); // The leading space, the `/`, and the three characters typed. assert_eq!(at.x, 5, "the cursor is not after the query"); assert_eq!(at.y, SCREEN.height - 1, "the cursor left the prompt row"); } /// `/` is the way in, and only from the action arms: typed into an open prompt it is /// an ordinary character, which is what makes searching for a path possible. #[test] fn the_dispatch_opens_the_search_and_gives_the_prompt_the_keyboard_first() { let source = include_str!("main.rs") .split_whitespace() .collect::>() .join(" "); assert!( source.contains("if board.search_key(key, screen) { continue; }"), "the prompt has to be offered every key before the action arms, or typing \ 'd' into a query toggles the done column" ); assert!( source.contains("KeyCode::Char('/') => board.open_search(),"), "`/` has to open the prompt from the action arms" ); } // ------------------------------------------------------------------ the copy key -- /// A sink that records what it was handed, standing in for the clipboard. fn recorder(taken: &mut Option) -> impl FnOnce(&str) -> Result<()> + '_ { move |text: &str| { *taken = Some(text.to_string()); Ok(()) } } /// What the card prints and what every command takes: the seven characters, so the /// point of the key is that they are not retyped. #[test] fn the_copy_key_puts_the_selected_short_id_on_the_clipboard() { let dir = searchable(); let mut board = one_board(&dir); assert_eq!(board.copy_text().as_deref(), Some("1111111")); let mut taken = None; board.copy_selected_id(recorder(&mut taken)); assert_eq!(taken.as_deref(), Some("1111111")); // Said in words, because a copy leaves nothing on the screen to look at. let row = footer(&board, 120, 20); assert!(row.contains("copied 1111111"), "the copy was silent: {row}"); // The selection follows the copy: it is the card that was copied from. let mut taken = None; board.select_card(1, SCREEN); board.copy_selected_id(recorder(&mut taken)); assert_eq!(taken.as_deref(), Some("2222222")); } /// The reader who has a ticket open is exactly the one who has decided to act on it, /// so the key has to work there too, and the overlay stays where it was. #[test] fn the_copy_key_works_with_the_detail_overlay_open() { let dir = searchable(); let mut board = one_board(&dir); board.toggle_detail(); let mut taken = None; board.copy_selected_id(recorder(&mut taken)); assert_eq!(taken.as_deref(), Some("1111111")); assert!(board.detail.is_some(), "the copy closed the ticket it copied from"); } /// Nothing selected is nothing to copy, and above all not an empty string: that would /// take away whatever the reader had on the clipboard and give nothing back. #[test] fn an_empty_column_copies_nothing_at_all() { let dir = searchable(); let mut board = one_board(&dir); // reviewing, which `searchable` leaves empty. board.select_column(2, SCREEN); assert!(board.selected().is_none(), "the column was not empty"); assert_eq!(board.copy_text(), None); let mut taken = None; board.copy_selected_id(recorder(&mut taken)); assert_eq!(taken, None, "an empty column reached the clipboard"); // Said rather than ignored, and in red: the reader pressed a key and has nothing // to paste, which is the same answer a failed write gives. let notice = board.notice.as_ref().expect("nothing was said"); assert_eq!(notice.text, "nothing to copy"); assert!(notice.failed, "a copy that did not happen read as one that did"); let row = footer(&board, 120, 20); assert!(row.contains("nothing to copy"), "{row}"); } /// A copy that did not happen must not read like one that did, or the reader pastes /// whatever was on the clipboard before and acts on the wrong ticket. #[test] fn a_clipboard_that_refuses_the_write_says_so() { let dir = searchable(); let mut board = one_board(&dir); board.copy_selected_id(|_| Err(anyhow::anyhow!("could not write to the terminal"))); let notice = board.notice.as_ref().expect("the failure was swallowed"); assert!(notice.failed, "a failed copy was reported as a success"); let row = footer(&board, 120, 20); assert!(row.contains("copy failed"), "{row}"); // The reason travels with it: a bare "failed" leaves nothing to act on. assert!(row.contains("could not write to the terminal"), "{row}"); assert!(!row.contains("copied 1111111"), "both answers were drawn: {row}"); } /// The message belongs to the keypress that made it. It survives the tick, since the /// board redraws four times a second and a notice cleared there would never be read, /// and it goes the moment the reader does anything else. #[test] fn the_notice_outlives_the_tick_and_not_the_next_keypress() { let dir = searchable(); let mut board = one_board(&dir); let mut taken = None; board.copy_selected_id(recorder(&mut taken)); board.tick().unwrap(); assert!(board.notice.is_some(), "the tick took the message away"); assert!(footer(&board, 120, 20).contains("copied"), "the message was not drawn"); board.clear_notice(); assert!(board.notice.is_none(), "the message outlived its keypress"); // And the keys are back, rather than the row staying spent on a read message. let row = footer(&board, 120, 20); assert!(row.contains("q quit"), "the key list did not come back: {row}"); } /// Both footers name it, since the key works with a ticket open as well. #[test] fn both_footers_name_the_copy_key() { let dir = searchable(); let mut board = one_board(&dir); assert!(footer(&board, 120, 20).contains("y copy id")); board.toggle_detail(); assert!(footer(&board, 120, 20).contains("y copy id")); } /// The rules are `copy_selected_id` and `clear_notice`, which the tests above reach. /// What is left is the dispatch, which none of them can: that `y` is bound at all, /// that it is handed the real clipboard, and that the clearing runs ahead of every /// key rather than only ahead of the arms. /// /// Scanned over whitespace-collapsed source, the way the other two dispatch tests /// scan, so rustfmt cannot fail it. #[test] fn the_dispatch_binds_y_to_the_clipboard_and_clears_the_notice_on_every_key() { let source = include_str!("main.rs") .split_whitespace() .collect::>() .join(" "); assert!( source.contains("KeyCode::Char('y') => board.copy_selected_id(clipboard::copy),"), "`y` has to reach `Board::copy_selected_id` with the real clipboard: the \ argument is what the suite replaces, so the dispatch is the only place \ the OSC 52 write is named" ); let cleared = source .find("board.clear_notice();") .expect("a notice that nothing clears sits in the footer for the rest of the session"); let prompt = source.find("if board.search_key(key, screen)").unwrap(); assert!( cleared < prompt, "the notice has to be cleared ahead of the prompt as well as the arms: a \ key typed into a query is still a key" ); } // ------------------------------------------------------- several boards at once -- /// A project tree: a directory holding a `.worklane`, which is what a path argument /// is resolved to. fn project_tree(name: &str) -> PathBuf { let root = std::env::temp_dir() .join(format!("worklane-project-{}", uuid::Uuid::new_v4())) .join(name); for status in status_dirs() { std::fs::create_dir_all(root.join(".worklane").join(status)).unwrap(); } root } /// No path is the working directory, which is what a bare `worklane` has always /// done, and the tab is named after the project rather than after `.worklane`. #[test] fn no_path_resolves_the_working_directory() { let root = project_tree("alpha"); let found = projects(&[], &root).unwrap(); assert_eq!(found.len(), 1); assert_eq!(found[0].name, "alpha"); assert_eq!(found[0].dir.file_name().unwrap(), ".worklane"); } /// A path is resolved the way the working directory is: the first board at or above /// it, so pointing at a subdirectory finds the project it belongs to. #[test] fn a_path_resolves_the_first_board_at_or_above_it() { let root = project_tree("alpha"); let deep = root.join("src").join("nested"); std::fs::create_dir_all(&deep).unwrap(); let found = projects(&[deep], &std::env::temp_dir()).unwrap(); assert_eq!(found.len(), 1); assert_eq!(found[0].name, "alpha"); } #[test] fn several_paths_are_monitored_together() { let (alpha, beta) = (project_tree("alpha"), project_tree("beta")); let found = projects(&[alpha, beta], &std::env::temp_dir()).unwrap(); let names: Vec<&str> = found.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["alpha", "beta"]); } /// With several arguments, "No .worklane directory found" does not say which one was /// wrong, so the path is named. #[test] fn a_path_with_no_board_fails_naming_that_path() { let alpha = project_tree("alpha"); let bare = std::env::temp_dir().join(format!("worklane-bare-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&bare).unwrap(); let error = projects(&[alpha, bare.clone()], &std::env::temp_dir()).unwrap_err(); let printed = format!("{error:#}"); assert!( printed.contains(&bare.display().to_string()), "the failing path is not named: {printed}" ); // And the usual message is still there, underneath the path. assert!(printed.contains("No .worklane directory found"), "{printed}"); } /// Two paths inside one project reach one board, and drawing it twice would show the /// same tickets under two tabs. #[test] fn two_paths_reaching_one_board_are_monitored_once() { let root = project_tree("alpha"); let deep = root.join("src"); std::fs::create_dir_all(&deep).unwrap(); let found = projects(&[root, deep], &std::env::temp_dir()).unwrap(); assert_eq!(found.len(), 1, "the same board was monitored twice"); } /// One board is the view it has always been: no tabs, columns on the top row. #[test] fn a_single_board_has_no_tab_row() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); let board = one_board(&dir); assert!(!board.tabbed()); assert_eq!(board.tabs.len(), 1); let top = tab_row(&board, 120, 20); assert!(top.starts_with('┌'), "something took the top row:\n{top}"); assert!(top.contains("backlog (1)"), "{top}"); } /// A tab per project, plus the merge, and the merge is where the view opens: it is /// the reason to monitor several boards at once. #[test] fn several_boards_get_a_tab_each_beside_the_all_tab() { let (first, second) = (board_dir(), board_dir()); let board = boards(&[("alpha", &first), ("beta", &second)]); assert!(board.tabbed()); let names: Vec<&str> = board.tabs.iter().map(|tab| tab.name.as_str()).collect(); assert_eq!(names, [ALL, "alpha", "beta"]); assert_eq!(board.current().name, ALL); let row = tab_row(&board, 120, 20); for name in [ALL, "alpha", "beta"] { assert!(row.contains(name), "no {name:?} in the tab row:\n{row}"); } // The columns moved down a row rather than being drawn over. assert!(headings(&board, 120, 20).contains("backlog (0)")); } /// The merge holds every board's tickets, in the order the listing uses rather than /// one project's column after another's. #[test] fn the_all_tab_holds_every_board_in_one_set_of_columns() { let (first, second) = (board_dir(), board_dir()); // Written the wrong way round on purpose: the merge has to sort, not concatenate. write_ticket(&first, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", ""); write_ticket(&second, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&second, "committed", "33333333-0000-4000-8000-000000000000", "Gamma", ""); let board = boards(&[("alpha", &first), ("beta", &second)]); let titles: Vec<&str> = board.current().columns[0] .cards .iter() .map(|card| card.ticket.title.as_str()) .collect(); assert_eq!(titles, ["Alpha", "Beta"], "the merge kept the argument order"); let row = headings(&board, 120, 20); assert!(row.contains("backlog (2)"), "{row}"); assert!(row.contains("committed (1)"), "{row}"); // And each project's own tab still holds only its own tickets. let mut board = board; board.select_tab(1, SCREEN); assert_eq!(board.current().name, "alpha"); assert_eq!(board.current().columns[0].cards.len(), 1); } /// Two boards can hold the same title, and seven characters of uuid do not say where /// a ticket lives, so the card on the merge names its project. #[test] fn a_card_on_the_all_tab_names_its_project() { let (first, second) = (board_dir(), board_dir()); write_ticket(&first, "backlog", "11111111-0000-4000-8000-000000000000", "Same name", ""); write_ticket(&second, "backlog", "22222222-0000-4000-8000-000000000000", "Same name", ""); let mut board = boards(&[("alpha", &second), ("beta", &first)]); let merged = render(&board, 120, 20).join("\n"); assert!(merged.contains("alpha"), "no project on the card:\n{merged}"); assert!(merged.contains("beta"), "no project on the card:\n{merged}"); // Not on a project's own tab, where the tab name already says it. board.select_tab(1, SCREEN); let own = board.current().columns[0].cards[0].project.as_deref(); assert_eq!(own, None, "the label was drawn where the tab says it"); } /// The label takes what the row has left, never the mark or the id, and says it was /// cut. A column too narrow for even that keeps the identity alone. /// /// The mark, a space and the id in its brackets, which is what `card_lines` has /// built by the time it asks. #[test] fn the_project_label_gives_way_to_the_mark_and_the_id() { const IDENTITY: usize = 2 + 1 + SHORT_ID_WIDTH + 2; assert_eq!(project_label("alpha", 38, IDENTITY).as_deref(), Some("alpha")); // Room for three characters of a longer name, the last of them the ellipsis. assert_eq!(project_label("factry-core", 16, IDENTITY).as_deref(), Some("fa…")); assert_eq!(project_label("factry-core", 13, IDENTITY), None); assert_eq!(project_label("alpha", 4, IDENTITY), None); } /// The label plus everything before it has to fit the column it is drawn in. The /// arithmetic this replaced left out the space after the priority mark, so the row /// came out one cell wider than the column at every width the label was cut at. #[test] fn the_project_label_leaves_the_row_inside_the_column() { const IDENTITY: usize = 2 + 1 + SHORT_ID_WIDTH + 2; for width in 13u16..40 { let Some(label) = project_label("factry-core", width, IDENTITY) else { continue; }; let row = IDENTITY + 1 + label.chars().count(); assert!(row <= width as usize, "row {row} over column {width}"); } } // ------------------------------------------------------- the blocked mark -- const BLOCKER: &str = "aaaaaaaa-0000-4000-8000-000000000000"; const WAITER: &str = "bbbbbbbb-0000-4000-8000-000000000000"; const ELSEWHERE: &str = "cccccccc-0000-4000-8000-000000000000"; /// A Relations section as `relate` writes it, for the `extra` a fixture appends. /// /// It lands after the Metadata rather than in `SECTION_ORDER`'s place for it, which /// `section_body` reads all the same: these tests are about what the section says, /// not where the writer puts it. fn blocked_by(uuid: &str) -> String { format!("\n## Relations\n\n- blocked by {uuid}\n") } /// Whether the board decided the named ticket is held up. /// /// Over every column, done included: the flag is filled whether or not the column /// is drawn, the same way `reload` scans done while `d` hides it. fn marked_blocked(board: &Board, title: &str) -> bool { board .current() .columns .iter() .flat_map(|column| &column.cards) .find(|card| card.ticket.title == title) .unwrap_or_else(|| panic!("no card titled '{title}'")) .blocked } /// The rows of the named ticket's card, laid out in a column of `inner` characters. fn card_rows(board: &Board, title: &str, inner: u16) -> Vec { let card = board .current() .columns .iter() .flat_map(|column| &column.cards) .find(|card| card.ticket.title == title) .unwrap_or_else(|| panic!("no card titled '{title}'")); card_lines(card, false, inner) .iter() .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect()) .collect() } /// The one thing on a card that says do not start this. Without it a ticket whose /// blocker is still open reads exactly like one that is ready. #[test] fn a_card_waiting_on_an_open_ticket_carries_the_blocked_mark() { let dir = board_dir(); write_ticket(&dir, "committed", BLOCKER, "The blocker", ""); write_ticket(&dir, "backlog", WAITER, "The waiter", &blocked_by(BLOCKER)); let board = one_board(&dir); assert!(marked_blocked(&board, "The waiter")); // The far end of the relation is not held up by holding somebody else up. assert!(!marked_blocked(&board, "The blocker")); let screen = render(&board, 120, 20).join("\n"); assert!( screen.contains(&format!("({}) {}", short_id(WAITER), BLOCKED_MARK)), "no mark after the id:\n{screen}" ); } /// The mark is the state of the dependency, not a note that one was ever recorded. #[test] fn a_card_whose_blockers_are_all_done_carries_none() { let dir = board_dir(); write_ticket(&dir, "done", BLOCKER, "The blocker", ""); write_ticket(&dir, "backlog", WAITER, "The waiter", &blocked_by(BLOCKER)); let board = one_board(&dir); assert!(!marked_blocked(&board, "The waiter")); let screen = render(&board, 120, 20).join("\n"); assert!(!screen.contains(BLOCKED_MARK), "a cleared blocker still marked:\n{screen}"); } /// One open blocker out of two is still a reason not to start, the rule `mv` applies /// when it names every open blocker rather than the first. #[test] fn a_card_is_marked_while_any_one_of_its_blockers_is_open() { let dir = board_dir(); write_ticket(&dir, "done", BLOCKER, "The blocker", ""); write_ticket(&dir, "reviewing", ELSEWHERE, "The other blocker", ""); write_ticket( &dir, "backlog", WAITER, "The waiter", &format!("\n## Relations\n\n- blocked by {BLOCKER}\n- blocked by {ELSEWHERE}\n"), ); assert!(marked_blocked(&one_board(&dir), "The waiter")); } /// The answer `mv` gives a dangling uuid: a bookkeeping fault, not a dependency. #[test] fn a_blocker_the_board_does_not_hold_marks_nothing() { let dir = board_dir(); write_ticket(&dir, "backlog", WAITER, "The waiter", &blocked_by(ELSEWHERE)); assert!(!marked_blocked(&one_board(&dir), "The waiter")); } /// Nothing but `relate` writes the section, so a line that is not a relation means a /// hand-edited file. `show` and `mv` are where that is reported; the board draws the /// ticket unmarked, the exception `detail_of` already makes for the same reason. #[test] fn a_relations_section_that_cannot_be_parsed_leaves_the_board_drawable() { let dir = board_dir(); write_ticket( &dir, "backlog", WAITER, "The waiter", "\n## Relations\n\n- waits for the other one\n", ); let board = one_board(&dir); assert!(!marked_blocked(&board, "The waiter")); let screen = render(&board, 120, 20).join("\n"); assert!(screen.contains("The waiter"), "the board lost the ticket:\n{screen}"); } /// Dropped whole in a column that cannot hold the identity and the mark together, /// the rule a corner follows. The id keeps its place either way: a column of ids /// starting at different cells costs more than one card's state is worth. #[test] fn a_column_too_narrow_for_the_mark_drops_it() { let dir = board_dir(); write_ticket(&dir, "committed", BLOCKER, "The blocker", ""); write_ticket(&dir, "backlog", WAITER, "The waiter", &blocked_by(BLOCKER)); let board = one_board(&dir); // The mark, a space, the id in its brackets, and the space the mark needs. let identity = (2 + 1 + SHORT_ID_WIDTH + 2) as u16; let id = format!("({})", short_id(WAITER)); let wide = card_rows(&board, "The waiter", identity + 2); assert!(wide[0].contains(BLOCKED_MARK), "no mark with room for it: {:?}", wide[0]); let narrow = card_rows(&board, "The waiter", identity); assert!( !narrow[0].contains(BLOCKED_MARK), "mark kept over the column: {:?}", narrow[0] ); assert!(narrow[0].contains(&id), "the identity gave way instead: {:?}", narrow[0]); assert!(narrow[0].chars().count() <= identity as usize, "row over the column"); } /// The merge resolves nothing of its own. A relation names a uuid `relate` looked up /// in one `.worklane`, so a blocker in another project is not a thing that exists, /// and the flag each card arrives with is the one its own board worked out. #[test] fn the_blocked_mark_follows_a_card_onto_the_merge() { let (first, second) = (board_dir(), board_dir()); write_ticket(&first, "committed", BLOCKER, "The blocker", ""); write_ticket(&first, "backlog", WAITER, "The waiter", &blocked_by(BLOCKER)); write_ticket(&second, "backlog", ELSEWHERE, "Elsewhere", &blocked_by(BLOCKER)); // The merge tab is where the view opens. let board = boards(&[("alpha", &first), ("beta", &second)]); assert_eq!(board.current().name, ALL); assert!(marked_blocked(&board, "The waiter")); assert!( !marked_blocked(&board, "Elsewhere"), "a uuid on another board was read as a blocker" ); } /// A change in any monitored board has to redraw, not only one in the first. #[test] fn the_digest_covers_every_monitored_board() { let (first, second) = (board_dir(), board_dir()); let projects = vec![project_at(&first), project_at(&second)]; let before = digest_of(&projects); write_ticket(&second, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); assert_ne!(before, digest_of(&projects), "the second board went unwatched"); } #[test] fn a_tick_picks_up_a_ticket_added_to_the_second_board() { let (first, second) = (board_dir(), board_dir()); let mut board = boards(&[("alpha", &first), ("beta", &second)]); assert!(!render(&board, 120, 20).join("\n").contains("Late one")); write_ticket(&second, "backlog", "11111111-0000-4000-8000-000000000000", "Late one", ""); assert!(board.tick().unwrap(), "the tick saw no change"); let screen = render(&board, 120, 20).join("\n"); assert!(screen.contains("Late one"), "{screen}"); } /// Each tab keeps its own place. Sharing one column and card index across projects /// would land the selection on whatever unrelated ticket sits at the same spot. #[test] fn each_tab_keeps_its_own_selection() { let (first, second) = (board_dir(), board_dir()); write_ticket(&first, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&first, "committed", "22222222-0000-4000-8000-000000000000", "Beta", ""); write_ticket(&second, "backlog", "33333333-0000-4000-8000-000000000000", "Gamma", ""); let mut board = boards(&[("alpha", &first), ("beta", &second)]); // On alpha's tab, move to its committed column. board.select_tab(1, SCREEN); board.select_column(1, SCREEN); assert_eq!(selected_title(&board), Some("Beta".to_string())); // beta has nothing in committed, so its own tab opens where it was left. board.select_tab(1, SCREEN); assert_eq!(board.current().name, "beta"); assert_eq!(board.current().column, 0); assert_eq!(selected_title(&board), Some("Gamma".to_string())); // And alpha is where it was, not reset by having been left. board.select_tab(-1, SCREEN); assert_eq!(board.current().column, 1); assert_eq!(selected_title(&board), Some("Beta".to_string())); } /// Tabs cycle, which is what a row of tabs does everywhere else, and there is no /// end of a list to run off. #[test] fn the_tabs_cycle_at_both_ends() { let (first, second) = (board_dir(), board_dir()); let mut board = boards(&[("alpha", &first), ("beta", &second)]); board.select_tab(-1, SCREEN); assert_eq!(board.current().name, "beta", "back from the first tab went nowhere"); board.select_tab(1, SCREEN); assert_eq!(board.current().name, ALL); } /// A single board has no tab to move to, so the key does nothing and the footer does /// not offer it. #[test] fn the_tab_key_and_its_footer_entry_need_more_than_one_board() { let dir = board_dir(); let mut single = one_board(&dir); single.select_tab(1, SCREEN); assert_eq!(single.tab, 0); assert!(!footer(&single, 120, 20).contains("tab project")); let other = board_dir(); let board = boards(&[("alpha", &dir), ("beta", &other)]); let row = footer(&board, 120, 20); assert!(row.contains("tab project"), "{row}"); } /// Two boards can hold tickets with the same title, so the overlay has to open the /// one the card came from, and say which project that was. #[test] fn the_detail_view_from_the_all_tab_opens_the_right_ticket() { let (first, second) = (board_dir(), board_dir()); write_ticket(&first, "backlog", "11111111-0000-4000-8000-000000000000", "Same name", ""); write_ticket(&second, "backlog", "22222222-0000-4000-8000-000000000000", "Same name", ""); let mut board = boards(&[("alpha", &first), ("beta", &second)]); board.toggle_detail(); let detail = board.detail.as_ref().expect("no detail"); let project = detail.project.clone().expect("no project on the overlay"); let uuid = match project.as_str() { "alpha" => "11111111", _ => "22222222", }; assert!( detail.plain().contains(uuid), "the overlay opened another project's ticket: {project} {:?}", detail.plain() ); let screen = render(&board, SCREEN.width, SCREEN.height); let row = overlay_title_row(&screen, SCREEN.width, SCREEN.height); assert!(row.contains(&project), "the border does not say which project:\n{row}"); // The next card down is the other project's, and the modal follows it. board.select_card(1, SCREEN); let moved = board.detail.as_ref().expect("no detail"); assert_ne!(moved.project, Some(project), "the modal stayed on one project"); assert!(!moved.plain().contains(uuid), "{:?}", moved.plain()); } /// The board and the listing draw from the same palette, so a colour cannot exist /// for one and not the other. The enum makes that a compile error; this pins the /// mapping itself. #[test] fn the_priority_marks_use_the_shared_palette() { for level in PRIORITY_RANGE { let (_, colour) = priority_mark(Priority::Level(level)); let tui: ratatui::style::Color = colour.into(); assert_ne!(tui, ratatui::style::Color::Reset, "level {level} has no colour"); } } /// The style of the first cell drawing `symbol`, so a test can ask what colour a /// glyph actually reached the screen in rather than trusting the span it was built /// from. fn drawn_color( board: &Board, width: u16, height: u16, symbol: &str, ) -> Option { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); (0..buffer.area.height) .flat_map(|y| (0..buffer.area.width).map(move |x| (x, y))) .find(|(x, y)| buffer[(*x, *y)].symbol() == symbol) .map(|(x, y)| buffer[(x, y)].fg) } /// A board holding one relation, so the tests below have a block to look at. /// /// The section goes where `relate` writes it, ahead of the metadata, rather than in /// `write_ticket`'s trailer: the block has to be on screen for a test to read the /// colour off the drawn buffer. fn related_board() -> PathBuf { let dir = board_dir(); let holder = "11111111-0000-4000-8000-000000000000"; let target = "22222222-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{holder}_a-holder.md")), format!( "# A holder\n\n## Description\nA description.\n\n## Relations\n\ - blocked by {target}\n\n## Metadata\n\n- **ID**: {holder}\n\ - **Priority**: 2\n- **Status**: backlog\n" ), ) .unwrap(); write_ticket(&dir, "reviewing", target, "The target", ""); dir } /// The mark is a ratatui style, not an escape sequence in the body. Passing `true` /// to the body renderers would put `\x1b[33m` in the paragraph and draw it as literal /// bytes, which is 6d327df; this asserts the colour arrived and the escape did not. #[test] fn the_relation_mark_is_drawn_as_a_style_and_not_as_an_escape() { let dir = related_board(); let mut board = one_board(&dir); board.toggle_detail(); let (mark, colour) = relation_mark(RelationKind::BlockedBy); let detail = board.detail.as_ref().expect("no detail"); assert!( detail.plain().contains(mark), "the target's mark is not in the body: {:?}", detail.plain() ); assert!( !detail.plain().contains('\x1b'), "an escape reached the body: {:?}", detail.plain() ); assert_eq!( drawn_color(&board, SCREEN.width, SCREEN.height, mark), Some(colour.into()), "the mark was drawn without its colour" ); } /// One layout, two painters. The overlay draws the block from the same cells the CLI /// paints, so the two views cannot come to list different edges in a different order /// or pad them differently. #[test] fn the_overlay_and_the_listing_draw_the_same_block() { let dir = related_board(); let mut board = one_board(&dir); board.toggle_detail(); let content = std::fs::read_to_string(board.selected().expect("no selection").ticket.path.clone()) .unwrap(); let rows = relations_for(&content, &dir).unwrap(); let printed = render_relations(&rows, false); assert!(!printed.is_empty(), "the fixture has no relations"); assert!( board .detail .as_ref() .unwrap() .plain() .contains(printed.trim_end()), "the overlay drew a different block than the listing prints: {printed:?}" ); } /// The body is no longer one string, so the clamp and the draw could measure two /// different things. They take the same `Text`, and this is what says so: a ticket /// whose relations run past the overlay scrolls to its last row. #[test] fn the_scroll_measures_the_relations_block_with_the_rest_of_the_body() { let dir = board_dir(); let holder = "11111111-0000-4000-8000-000000000000"; let mut relations = String::from("\n## Relations\n"); for n in 0..20 { let target = format!("2222222{n:x}-0000-4000-8000-000000000000"); relations.push_str(&format!("- blocked by {target}\n")); write_ticket(&dir, "done", &target, &format!("Target {n:02}"), ""); } write_ticket(&dir, "backlog", holder, "A holder", &relations); let mut board = one_board(&dir); board.toggle_detail(); let area = detail_text_area(Rect::new(0, 0, SCREEN.width, SCREEN.height)); let last = last_offset(&board.detail.as_ref().unwrap().body, area); assert!(last > 0, "the fixture fits on one screen, so nothing is measured"); // Far past the end, so the clamp is what stops it. for _ in 0..20 { board.scroll_detail(1, SCREEN); } assert_eq!(board.offset, last, "the clamp and the body disagree"); // The relations sit at the end of this fixture, so the last row and the comments // line are what the last screenful has to hold. let screen = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( screen.contains("Target 19"), "the last relation is not on screen:\n{screen}" ); assert!( screen.contains("No comments yet."), "the body ends past the last screenful:\n{screen}" ); } /// The line of the body carrying `needle`, so a test can ask what colour a run of it /// is drawn in rather than reading the flattened text. fn body_line(detail: &Detail, needle: &str) -> Line<'static> { detail .body .lines .iter() .find(|line| { line.spans .iter() .map(|span| span.content.as_ref()) .collect::() .contains(needle) }) .cloned() .unwrap_or_else(|| panic!("no line holding {needle:?} in:\n{}", detail.plain())) } /// The colour of the span whose whole content is `text`, on that line. fn span_color(line: &Line<'static>, text: &str) -> Option { line.spans .iter() .find(|span| span.content.as_ref() == text) .map(|span| span.style.fg) .unwrap_or_else(|| panic!("no span {text:?} in {line:?}")) } /// A short id is red everywhere the CLI prints one, and the overlay was the one place /// it was not: the body arrived as flat text because a paragraph is no place for an /// escape. It is styled now, so the guideline holds in both views. /// /// Paired the way the guideline demands. The absence, no escape byte in the body, /// cannot pass on its own: a version that dropped every colour to stay safe would /// satisfy it, so the presence is asserted beside it. And the one character version /// of this, passing `true` to the body renderers, fails the absence. #[test] fn the_relation_id_is_red_in_the_overlay_and_no_escape_reached_the_body() { let dir = related_board(); let mut board = one_board(&dir); board.toggle_detail(); let detail = board.detail.as_ref().expect("no detail"); let row = body_line(detail, "blocked by"); assert_eq!( span_color(&row, "2222222"), Some(Color::Red.into()), "the target's id is not red: {row:?}" ); // The pair: colour arrived, and it arrived as a style rather than as bytes. assert!( row.spans.iter().any(|span| span.style.fg.is_some()), "nothing on the row is coloured at all, so the guard below is vacuous" ); assert!( !detail.plain().contains('\x1b'), "escapes reached the body: {:?}", detail.plain() ); } /// A target the board no longer holds keeps the id, which is the only thing left to /// go looking for, and says `_missing_` in the grey that means an unset value. The /// colour must not turn a gap into something that reads like a real target. #[test] fn a_missing_target_still_reads_as_missing_in_the_overlay() { let dir = board_dir(); let holder = "11111111-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{holder}_a-holder.md")), format!( "# A holder\n\n## Relations\n- blocked by 99999999-0000-4000-8000-000000000000\n\ \n## Metadata\n\n- **ID**: {holder}\n- **Status**: backlog\n" ), ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); let detail = board.detail.as_ref().expect("no detail"); let row = body_line(detail, "blocked by"); assert_eq!(span_color(&row, "_missing_"), Some(Color::Grey.into())); assert_eq!( span_color(&row, "9999999"), Some(Color::Red.into()), "the id went with the title it could not find" ); // The mark is the kind, read off this ticket's own file, so it survives a target // the board cannot find: only the name is gone. assert_eq!( span_color(&row, BLOCKED_MARK), Some(Color::BrightRed.into()), "the mark went with the title it could not find" ); } /// The detail view is the second renderer of a ticket body, so it resolves a /// relation the way `show` does rather than printing the uuid the file stores. /// /// The section goes in `extra`, after the metadata, which is not where `relate` /// writes it. Position is the CLI's test to make; this one is about the lookup. #[test] fn the_detail_view_resolves_a_relation_to_a_title() { let dir = board_dir(); let target = "22222222-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", target, "The target", ""); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "A holder", &format!("\n## Relations\n- blocked by {target}\n"), ); let mut board = one_board(&dir); board.toggle_detail(); let text = &board.detail.as_ref().expect("no detail").plain(); // Marked for its kind, and the mark sits ahead of the id. assert!( text.contains(&format!( "blocked by {BLOCKED_MARK} {} (2222222) The target", status_mark(Some("backlog")).0 )), "{text:?}" ); assert!(!text.contains(target), "the bare uuid was drawn: {text:?}"); } /// The far end of a relation stores nothing, so the board derives it too. #[test] fn the_detail_view_derives_the_other_end() { let dir = board_dir(); let holder = "11111111-0000-4000-8000-000000000000"; write_ticket( &dir, "backlog", holder, "A holder", "\n## Relations\n- blocked by 22222222-0000-4000-8000-000000000000\n", ); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "The target", ""); let mut board = one_board(&dir); // The holder sorts first by title, so the target is the card below it. board.select_card(1, SCREEN); board.toggle_detail(); let text = &board.detail.as_ref().expect("no detail").plain(); assert!( text.contains(&format!( "blocks {BLOCKED_MARK} {} (1111111) A holder", status_mark(Some("backlog")).0 )), "{text:?}" ); } /// The detail view resolves the Campaign field the way `show` does. The field stores /// a uuid, so an unresolved one would put thirty-six characters of hex on screen. #[test] fn the_detail_view_shows_the_campaign_title() { let dir = board_dir(); let campaign = "cccccccc-0000-4000-8000-000000000000"; std::fs::create_dir_all(dir.join("campaigns")).unwrap(); std::fs::write( dir.join("campaigns").join(format!("{campaign}_v1-release.md")), format!("# v1 release\n\n## Metadata\n\n- **ID**: {campaign}\n"), ) .unwrap(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "A member", &format!("- **Campaign**: {campaign}\n"), ); let mut board = one_board(&dir); board.toggle_detail(); let text = &board.detail.as_ref().expect("no detail").plain(); assert!(text.contains("(ccccccc) v1 release"), "{text:?}"); assert!(!text.contains(campaign), "the bare uuid reached the screen: {text:?}"); } /// A board with no campaigns directory is every board made before campaigns existed. /// The detail view still has to draw. #[test] fn a_board_with_no_campaigns_directory_still_draws_a_ticket() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "A ticket", "- **Campaign**: cccccccc-0000-4000-8000-000000000000\n", ); let mut board = one_board(&dir); board.toggle_detail(); let text = &board.detail.as_ref().expect("no detail").plain(); assert!(text.contains("A description."), "the body was lost: {text:?}"); // No campaigns to resolve against, so the reference reads as gone. assert!(text.contains("_missing_"), "{text:?}"); } /// The CLI refuses a relations line it cannot read, naming the ticket. The board /// cannot: one hand-edited file must not take every other card down with it. #[test] fn a_relations_line_that_cannot_be_read_still_draws_the_ticket() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "A holder", "\n## Relations\n- depends on 22222222-0000-4000-8000-000000000000\n", ); let mut board = one_board(&dir); board.toggle_detail(); let text = &board.detail.as_ref().expect("no detail").plain(); assert!(text.contains("A description."), "the body was lost: {text:?}"); } /// The overlay scrolls and nothing said where you were: a long ticket opened looking /// exactly like a short one. #[test] fn a_scrollable_ticket_shows_a_page_indicator_on_the_bottom_border() { let dir = board_dir(); let board = scrolling_board(&dir, 60); let screen = render(&board, SCREEN.width, SCREEN.height); let row = overlay_bottom_row(&screen, SCREEN.width, SCREEN.height); assert!(row.contains("pg 1/"), "no indicator on the bottom border:\n{row}"); // On the border, not on a text row: the row it is drawn on is the one carrying // the corners, so no line of the ticket was spent on it. assert!(row.starts_with('└'), "not the bottom border row:\n{row}"); assert!(row.ends_with('┘'), "not the bottom border row:\n{row}"); // Bottom right, so it is in the corner the eye goes to for a number and not // adrift in the middle of the border. let at = row.chars().position(|c| c == 'p').expect("no indicator"); let width = row.chars().count(); assert!( at > width - 12, "the indicator is not in the right-hand corner of a {width} cell border:\n{row}" ); // And the top border still carries the title alone. let title = overlay_title_row(&screen, SCREEN.width, SCREEN.height); assert!(title.contains("A long one"), "{title}"); assert!(!title.contains("pg "), "the indicator landed on the title row:\n{title}"); std::fs::remove_dir_all(&dir).ok(); } /// At the top of a scrollable ticket, page one. #[test] fn the_indicator_opens_on_page_one() { let dir = board_dir(); let board = scrolling_board(&dir, 60); let screen = render(&board, SCREEN.width, SCREEN.height); let row = overlay_bottom_row(&screen, SCREEN.width, SCREEN.height); assert!(row.contains("pg 1/"), "{row}"); std::fs::remove_dir_all(&dir).ok(); } /// The one the arithmetic is for: the clamp stops at the wrapped height less the /// viewport, not on a page boundary, so the last screenful is partial and dividing /// would claim there is more to read. #[test] fn the_furthest_scroll_reads_the_last_page() { let dir = board_dir(); let mut board = scrolling_board(&dir, 60); // Far past the end, so the clamp is what stops it. for _ in 0..40 { board.scroll_detail(1, SCREEN); } let text = detail_text_area(Rect::new(0, 0, SCREEN.width, SCREEN.height)); let last = last_offset(&board.detail.as_ref().unwrap().body, text); assert_eq!(board.offset, last, "the fixture did not reach the end"); let screen = render(&board, SCREEN.width, SCREEN.height); let row = overlay_bottom_row(&screen, SCREEN.width, SCREEN.height); let indicator = row .split_whitespace() .find(|word| word.contains('/')) .unwrap_or_else(|| panic!("no indicator on:\n{row}")) .to_string(); let (page, total) = indicator.split_once('/').expect("no separator"); assert_eq!(page, total, "the last page reads as the second to last: {indicator}"); std::fs::remove_dir_all(&dir).ok(); } /// A ticket that fits spends no indicator, the way an untagged card spends no row on /// tags. /// /// On a taller screen than the other overlay tests use: `write_ticket`'s own body is /// twenty-odd rows and scrolls in a twenty row terminal, so the fixture has to be /// given a terminal it fits in for the absence to mean anything. #[test] fn a_ticket_that_fits_shows_no_indicator() { let (width, height) = (120, 60); let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "A short one", ""); let mut board = one_board(&dir); board.toggle_detail(); let text = detail_text_area(Rect::new(0, 0, width, height)); assert_eq!( last_offset(&board.detail.as_ref().unwrap().body, text), 0, "the fixture scrolls, so it proves nothing" ); let screen = render(&board, width, height); assert!( !screen.join("\n").contains("pg "), "a ticket that fits drew an indicator:\n{}", screen.join("\n") ); std::fs::remove_dir_all(&dir).ok(); } /// The wrapped count and the viewport both move with the terminal, so the total has /// to move with them. Narrower and shorter means more pages of the same ticket. #[test] fn a_resize_repages_the_indicator() { let dir = board_dir(); let board = scrolling_board(&dir, 60); let total = |width: u16, height: u16| -> String { let screen = render(&board, width, height); let row = overlay_bottom_row(&screen, width, height); row.split_whitespace() .find(|word| word.contains('/')) .unwrap_or_else(|| panic!("no indicator at {width}x{height} on:\n{row}")) .split_once('/') .expect("no separator") .1 .to_string() }; let wide = total(120, 40); let narrow = total(60, 20); assert_ne!(wide, narrow, "the same total on two terminal sizes"); std::fs::remove_dir_all(&dir).ok(); } /// An overlay too narrow for the indicator drops it whole rather than cutting it, the /// rule a card's corner follows: half a page number reads as a different one. #[test] fn an_overlay_too_narrow_for_the_indicator_drops_it_whole() { // Six pages in a two cell overlay, so there is plenty to say and no room for it. assert_eq!(page_indicator(0, 50, 10, 2), None); assert_eq!(page_indicator(0, 50, 10, 8), None); // ` pg 1/7 ` is eight characters, so it needs ten cells of overlay. assert_eq!(page_indicator(0, 50, 10, 10).as_deref(), Some(" pg 1/7 ")); } /// The arithmetic on its own, so the cases that need no terminal are pinned where /// they can be read. #[test] fn the_page_numbers_count_in_the_step_the_keys_take() { // A 25 line ticket in a 10 line viewport: the step is nine, so the offsets the // keys reach are 0, 9 and 15, the last of them clamped. let (last, height) = (15, 10); assert_eq!(page_indicator(0, last, height, 40).as_deref(), Some(" pg 1/3 ")); assert_eq!(page_indicator(9, last, height, 40).as_deref(), Some(" pg 2/3 ")); assert_eq!(page_indicator(15, last, height, 40).as_deref(), Some(" pg 3/3 ")); // Nothing to scroll, nothing to say. assert_eq!(page_indicator(0, 0, height, 40), None); // One line over the viewport is two pages, and the second of them is one row. assert_eq!(page_indicator(0, 1, height, 40).as_deref(), Some(" pg 1/2 ")); assert_eq!(page_indicator(1, 1, height, 40).as_deref(), Some(" pg 2/2 ")); } /// The colour the indicator actually reached the screen in. /// /// Located on the bottom border row rather than by searching the buffer for a glyph: /// `p` and `g` are all over the board, and `drawn_color` would answer about whichever /// card holds the first one. fn indicator_color(board: &Board, width: u16, height: u16) -> Option { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); let overlay = detail_overlay(Rect::new(0, 0, width, height)); let row = overlay.y + overlay.height - 1; (overlay.x..overlay.x + overlay.width - 1) .find(|x| buffer[(*x, row)].symbol() == "p" && buffer[(x + 1, row)].symbol() == "g") .map(|x| buffer[(x, row)].fg) } /// Chrome, not a value: the guideline gives grey to what a reader skips, and the /// title on the opposite border keeps orange. #[test] fn the_indicator_is_drawn_as_chrome() { let dir = board_dir(); let board = scrolling_board(&dir, 60); assert_eq!( indicator_color(&board, SCREEN.width, SCREEN.height), Some(Color::Grey.into()), "the indicator was drawn in something other than the chrome colour" ); // Not the same colour as the title on the opposite border, or it would read as // part of the ticket's identity rather than as chrome. assert_ne!( indicator_color(&board, SCREEN.width, SCREEN.height), Some(Color::Orange.into()), "the indicator took the title's colour" ); std::fs::remove_dir_all(&dir).ok(); } // ------------------------------------------------------------- campaigns -- /// The campaign uuid of the board's first campaign, so a test can name one without /// writing a uuid out twice. const V1: &str = "22222222-0000-4000-8000-000000000000"; const BEAVER: &str = "33333333-0000-4000-8000-000000000000"; /// A board with two campaigns and a member in each, plus one ticket in neither. fn campaign_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), ); write_ticket( dir, "committed", "44444444-0000-4000-8000-000000000000", "Also in v1", &campaign_field(V1), ); write_ticket( dir, "backlog", "55555555-0000-4000-8000-000000000000", "In beaver", &campaign_field(BEAVER), ); write_ticket(dir, "backlog", "66666666-0000-4000-8000-000000000000", "In neither", ""); one_board(dir) } fn campaign_field(uuid: &str) -> String { format!("- **Campaign**: {uuid}\n") } /// 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. fn picker_rows(board: &Board, width: u16, height: u16) -> Vec { let rows = board.current().campaigns.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); (inner.y..inner.y + inner.height) .map(|y| { lines[y as usize] .chars() .skip(inner.x as usize) .take(inner.width as usize) .collect() }) .collect() } /// The card said nothing about which release a ticket belonged to, which is the one /// thing a board is read to decide. #[test] fn a_card_names_the_campaign_it_is_in() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); write_member_card(&dir, "Short", "cli, tui", V1); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 5, "the label row is missing: {rows:?}"); assert_eq!(rows[2], "~v1 #cli #tui", "the campaign is not on the row: {rows:?}"); std::fs::remove_dir_all(&dir).ok(); } /// The mark is not `#`, because the two sit on one row and the row would otherwise /// read as a list of tags with a stranger in it. #[test] fn the_campaign_mark_is_not_the_tag_mark() { assert_ne!(CAMPAIGN_MARK, "#"); assert_eq!(CAMPAIGN_MARK.chars().count(), 1, "the mark has to fit a card's row"); } /// The codename exists because a short id says nothing about what a campaign is for. /// Without one there is nothing better to draw, so the id is what the card falls back /// to: it says little, and it still resolves. #[test] fn a_campaign_with_no_codename_falls_back_to_its_short_id() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "", "For a public tag."); write_member_card(&dir, "Short", "_None_", V1); let rows = only_card(&dir, 120, 20); assert_eq!(rows[2], format!("~{}", short_id(V1)), "{rows:?}"); std::fs::remove_dir_all(&dir).ok(); } /// A ticket in no campaign renders exactly as it did before campaigns reached the /// card: no row, no marker, nothing spent. #[test] fn a_ticket_in_no_campaign_spends_no_row() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); write_member_card(&dir, "Short", "_None_", NOT_SET); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "a row was spent on nothing: {rows:?}"); assert!(!rows.iter().any(|row| row.contains(CAMPAIGN_MARK)), "{rows:?}"); std::fs::remove_dir_all(&dir).ok(); } /// A campaign the board does not hold marks nothing, the answer `mark_blocked` gives /// a blocker nobody holds: a uuid nothing carries is a bookkeeping fault rather than /// a fact about this ticket, and a card is no place to report one. #[test] fn a_campaign_the_board_does_not_hold_marks_nothing() { let dir = board_dir(); write_member_card(&dir, "Short", "_None_", "99999999-0000-4000-8000-000000000000"); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "{rows:?}"); assert!(!rows.iter().any(|row| row.contains("_missing_")), "{rows:?}"); std::fs::remove_dir_all(&dir).ok(); } /// The campaign takes the row first and the tags give way, the order a corner and a /// project label already follow: two cards in one campaign is what a reader looking /// for a campaign is looking for, and the tags are the context around it. #[test] fn the_campaign_keeps_the_row_and_the_tags_give_way() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); write_member_card(&dir, "Short", "frontend, operations", V1); // One character short of "~v1 #frontend #operations", and one over it. let narrow = only_card_at(&dir, 24); assert_eq!(narrow[2], "~v1", "the tags took the row from the campaign: {narrow:?}"); let fits = only_card_at(&dir, 25); assert_eq!(fits[2], "~v1 #frontend #operations", "{fits:?}"); std::fs::remove_dir_all(&dir).ok(); } /// And a campaign the row will not hold goes whole, never cut: half a codename is a /// different codename, which is the rule every other thing on a card follows. #[test] fn a_campaign_too_wide_for_the_column_is_dropped_whole() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "beaver", "For a public tag."); write_member_card(&dir, "Short", "_None_", V1); let narrow = only_card_at(&dir, 6); assert_eq!(narrow.len(), 4, "the label was kept: {narrow:?}"); let fits = only_card_at(&dir, 7); assert_eq!(fits[2], "~beaver", "{fits:?}"); std::fs::remove_dir_all(&dir).ok(); } /// The colour groups a campaign across the cards that carry it, from the same pure /// function a tag's colour comes from, and the bold is what stops it reading as a /// sixth tag on a card that has five. #[test] fn the_campaign_label_is_bold_and_coloured_by_its_codename() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); write_member_card(&dir, "Short", "cli", V1); let board = one_board(&dir); let card = board.selected().expect("no card"); let label = card_lines(card, false, 40) .iter() .flat_map(|line| line.spans.clone()) .find(|span| span.content == "~v1") .expect("no campaign span on the card"); assert_eq!(label.style.fg, Some(tag_color("v1").into()), "not the label colour"); assert!( label.style.add_modifier.contains(Modifier::BOLD), "the campaign does not jump out: {:?}", label.style ); std::fs::remove_dir_all(&dir).ok(); } /// A campaign with no codename is drawn in grey rather than in the red a uuid takes /// everywhere else, so no reserved meaning lands on a tag slot and the one thing the /// card has to say for itself is that this campaign has nothing to be called. #[test] fn a_codenameless_campaign_is_drawn_as_chrome() { let label = campaign_label(V1, None); assert_eq!(label.color, Some(Color::Grey)); let named = campaign_label(V1, Some("v1")); assert_eq!(named.color, Some(tag_color("v1"))); } /// An unreadable campaigns directory leaves every card in no campaign and the board /// drawable, which is the same bargain an unreadable status directory takes. #[test] fn an_unreadable_campaigns_directory_leaves_the_board_drawable() { let dir = board_dir(); // A file where the directory should be: `read_dir` fails on it, which a missing // directory does not, so this is the path the empty index is actually for. std::fs::write(dir.join(CAMPAIGNS_DIR), "not a directory").unwrap(); write_member_card(&dir, "Short", "cli", V1); let board = one_board(&dir); assert!(board.current().campaigns.is_empty(), "campaigns came from a file"); assert!( board.selected().expect("no card").campaign.is_none(), "a card was labelled" ); assert!(headings(&board, 100, 24).contains("backlog (1)"), "the board did not draw"); std::fs::remove_dir_all(&dir).ok(); } /// Selecting a campaign turns the four columns into that campaign's members grouped /// by status, which is the shape `campaign show` already answers the question in. #[test] fn selecting_a_campaign_filters_every_column_to_its_members() { let dir = board_dir(); let mut board = campaign_board(&dir); let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4, "the fixture changed"); board.select_campaign(Some(V1.to_string()), SCREEN); let titles: Vec = board .current() .columns .iter() .flat_map(|column| column.cards.iter().map(|card| card.ticket.title.clone())) .collect(); assert_eq!(titles, vec!["In v1".to_string(), "Also in v1".to_string()], "{titles:?}"); // Every column is kept, empty ones included: a campaign's shape is the flow. assert_eq!(board.current().columns.len(), status_dirs().len()); std::fs::remove_dir_all(&dir).ok(); } /// The frame says which campaign the columns belong to, and how far it has got, from /// the columns rather than from a second walk of the tree. #[test] fn the_frame_names_the_campaign_and_its_standing() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_campaign(Some(V1.to_string()), SCREEN); let rows = render(&board, 100, 24); assert!(rows[0].contains(short_id(V1)), "no id on the frame: {:?}", rows[0]); assert!(rows[0].contains("~v1"), "no codename on the frame: {:?}", rows[0]); assert!(rows[0].contains("First public release"), "no name: {:?}", rows[0]); assert!( rows[1].contains("Everything for a public tag."), "no summary: {:?}", rows[1] ); assert!(rows[2].contains("0/2 done"), "no standing: {:?}", rows[2]); assert!(rows[2].contains("[open]"), "no derived state: {:?}", rows[2]); // The way out, on the border of the thing it undoes. assert!(rows[2].contains("q board"), "no way out named: {:?}", rows[2]); std::fs::remove_dir_all(&dir).ok(); } /// The standing counts done whether the column is drawn or not: hiding done is a /// change to what is drawn and never to what is counted. #[test] fn the_standing_counts_done_members_while_the_column_is_hidden() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a tag."); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "Open one", &campaign_field(V1), ); write_ticket( &dir, "done", "44444444-0000-4000-8000-000000000000", "Finished one", &campaign_field(V1), ); let mut board = one_board(&dir); board.select_campaign(Some(V1.to_string()), SCREEN); assert!(!board.show_done, "done is hidden at startup"); let standing = board.current().standing(); assert_eq!((standing.done, standing.total), (1, 2)); std::fs::remove_dir_all(&dir).ok(); } /// The frame takes its three rows off the columns rather than off the footer, and /// every measurement of the board has to agree about that: a keypress that scrolled /// against the taller board would put the selection where the draw does not. #[test] fn the_frame_takes_its_rows_from_the_columns() { let dir = board_dir(); let mut board = campaign_board(&dir); let screen = Size { width: 100, height: 24 }; let plain = board_area(screen, board.chrome()); board.select_campaign(Some(V1.to_string()), screen); let framed = board_area(screen, board.chrome()); assert_eq!(framed.y, plain.y + Chrome::CAMPAIGN_ROWS, "the columns did not move down"); assert_eq!( framed.height, plain.height - Chrome::CAMPAIGN_ROWS, "the frame took its rows from somewhere else" ); std::fs::remove_dir_all(&dir).ok(); } /// `q` takes off one layer at a time, in the order they were put on: the overlay, then /// the campaign, then the board. Quitting out from under a filter is what `q` used to /// do to an open ticket. #[test] fn dismiss_takes_off_the_campaign_before_the_board() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_campaign(Some(V1.to_string()), SCREEN); board.dismiss(SCREEN); assert_eq!(board.current().campaign, None, "the campaign is still selected"); assert!(!board.should_quit, "the board quit out from under the filter"); // And the whole board is back, not an empty one. let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4); board.dismiss(SCREEN); assert!(board.should_quit, "nothing left to close and it did not quit"); std::fs::remove_dir_all(&dir).ok(); } /// And the overlay comes off before the campaign, so one press takes off one layer. #[test] fn dismiss_closes_the_overlay_before_the_campaign() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_campaign(Some(V1.to_string()), SCREEN); board.toggle_detail(); assert!(board.detail.is_some(), "nothing opened"); board.dismiss(SCREEN); assert!(board.detail.is_none(), "the overlay stayed open"); assert_eq!(board.current().campaign, Some(V1.to_string()), "the filter came off too"); std::fs::remove_dir_all(&dir).ok(); } /// 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. #[test] fn selecting_a_campaign_closes_an_open_ticket() { let dir = board_dir(); let mut board = campaign_board(&dir); board.toggle_detail(); assert!(board.detail.is_some(), "nothing opened"); board.select_campaign(Some(BEAVER.to_string()), SCREEN); assert!(board.detail.is_none(), "the overlay survived the filter"); std::fs::remove_dir_all(&dir).ok(); } /// The picker owns the keyboard while it is open, the rule the search prompt already /// holds: `d` must not toggle done and `q` must not quit while a campaign is being /// chosen. #[test] fn the_picker_swallows_every_key_it_is_given() { let dir = board_dir(); let mut board = campaign_board(&dir); board.open_picker(); for code in [KeyCode::Char('d'), KeyCode::Char('/'), KeyCode::Char('y')] { 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"); // Every other control combination is swallowed and does nothing, or `ctrl-d` would // reach the arm bound to `d`. board.picker_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL), SCREEN); assert!(!board.show_done, "ctrl-d reached the done column"); std::fs::remove_dir_all(&dir).ok(); } /// `ctrl-c` is the one key it declines, because a terminal application always honours /// it and a picker that ate it would leave no way off the board. #[test] fn the_picker_declines_ctrl_c() { let dir = board_dir(); let mut board = campaign_board(&dir); board.open_picker(); assert!( !board.picker_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL), SCREEN) ); std::fs::remove_dir_all(&dir).ok(); } /// The point of the list: move to a campaign, press enter, look at it. #[test] fn enter_in_the_picker_takes_the_highlighted_campaign() { let dir = board_dir(); let mut board = campaign_board(&dir); board.open_picker(); // By title, which is the index's order, so the first row is Beaver migration. let first = board.current().campaigns[0].uuid.clone(); assert_eq!(first, BEAVER, "the list is not in the index's order"); board.picker_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), SCREEN); 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(); } /// Esc leaves the board exactly as it was, so opening the list is never a commitment. #[test] fn esc_in_the_picker_changes_nothing() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_campaign(Some(V1.to_string()), SCREEN); board.open_picker(); board.picker_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE), SCREEN); board.picker_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), SCREEN); assert!(board.picker.is_none(), "the picker stayed open"); assert_eq!(board.current().campaign, Some(V1.to_string()), "the filter moved"); std::fs::remove_dir_all(&dir).ok(); } /// It opens on the campaign already selected, so `c` on a filtered board says where /// you are as well as offering somewhere to go. #[test] fn the_picker_opens_on_the_campaign_in_view() { let dir = board_dir(); let mut board = campaign_board(&dir); 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); std::fs::remove_dir_all(&dir).ok(); } /// A board with no campaigns says so in words rather than opening an empty box that /// has to be dismissed to learn it was empty. #[test] fn a_board_with_no_campaigns_says_so_rather_than_opening_an_empty_picker() { let dir = board_dir(); write_member_card(&dir, "Short", "cli", NOT_SET); let mut board = one_board(&dir); board.open_picker(); assert!(board.picker.is_none(), "an empty picker opened"); let notice = board.notice.as_ref().expect("nothing was said"); assert!(notice.text.contains("no campaigns"), "{:?}", notice.text); assert!(notice.failed, "a key that did nothing read as a key that worked"); std::fs::remove_dir_all(&dir).ok(); } /// The rows carry the three things a campaign is chosen by, and the description is the /// one of them that gives way, since it is the only one that is prose. #[test] fn the_picker_rows_name_the_id_the_codename_and_the_description() { let dir = board_dir(); let mut board = campaign_board(&dir); board.open_picker(); let rows = picker_rows(&board, 100, 24); let row = rows .iter() .find(|row| row.contains(short_id(BEAVER))) .expect("no row for the campaign"); assert!(row.contains("~beaver"), "{row:?}"); assert!(row.contains("Move the store off one disk."), "{row:?}"); // And the footer is the picker's while it is open, for the reason the prompt takes // it: the board's key list describes nothing that currently works. assert!(footer(&board, 100, 24).contains("enter view"), "the footer is the board's"); std::fs::remove_dir_all(&dir).ok(); } /// A campaign with no codename shows the id once, not twice: the row already opens /// with it, so the card's fallback would say nothing the second time. #[test] fn a_picker_row_does_not_repeat_the_id_as_a_codename() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "", "For a public tag."); write_member_card(&dir, "Short", "cli", V1); let mut board = one_board(&dir); board.open_picker(); let rows = picker_rows(&board, 100, 24); let row = rows .iter() .find(|row| row.contains(short_id(V1))) .expect("no row for the campaign"); assert_eq!(row.matches(short_id(V1)).count(), 1, "the id is on the row twice: {row:?}"); assert!(!row.contains(CAMPAIGN_MARK), "a mark with nothing after it: {row:?}"); std::fs::remove_dir_all(&dir).ok(); } /// A campaign filed elsewhere has to reach the board, and the digest is what decides /// whether anything is re-read. Without the campaigns directory in it a new campaign /// was invisible until some ticket happened to change. #[test] fn the_digest_moves_when_a_campaign_is_filed_or_edited() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "A ticket", ""); let mut board = one_board(&dir); assert!(board.current().campaigns.is_empty()); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); assert!(board.tick().unwrap(), "the tick saw nothing"); assert_eq!(board.current().campaigns.len(), 1, "the campaign never arrived"); // And an edit in place, which a directory's own mtime would miss. write_campaign(&dir, V1, "First public release", "beaver", "For a public tag."); assert!(board.tick().unwrap(), "an edited campaign moved nothing"); assert_eq!(board.current().campaigns[0].codename.as_deref(), Some("beaver")); std::fs::remove_dir_all(&dir).ok(); } /// A selection whose campaign has left the board goes back to the whole board rather /// than filtering it to nothing, which would read as a board that had lost its /// tickets. #[test] fn a_campaign_that_leaves_the_board_returns_the_tab_to_it() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_campaign(Some(V1.to_string()), SCREEN); std::fs::remove_dir_all(dir.join(CAMPAIGNS_DIR)).unwrap(); board.reload().unwrap(); assert_eq!(board.current().campaign, None, "the filter outlived its campaign"); let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4, "the board stayed filtered to nothing"); 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] fn the_footer_names_the_campaign_key_where_it_is_found() { let dir = board_dir(); let mut board = campaign_board(&dir); assert!(footer(&board, 120, 24).contains("c campaign"), "the key is unfindable"); board.select_campaign(Some(V1.to_string()), SCREEN); let footer = footer(&board, 120, 24); assert!(footer.contains("ctrl-c quit"), "q still claims to quit: {footer:?}"); assert!(!footer.contains("q quit"), "{footer:?}"); std::fs::remove_dir_all(&dir).ok(); } /// The filter belongs to the tab, not the board: a campaign is resolved inside one /// `.worklane`, so one carried across would empty another project's tab and say /// nothing about why. #[test] fn the_campaign_filter_belongs_to_the_tab() { let one = board_dir(); let two = board_dir(); write_campaign(&one, V1, "First public release", "v1", "For a public tag."); write_ticket( &one, "backlog", "11111111-0000-4000-8000-000000000000", "In v1", &campaign_field(V1), ); write_ticket(&two, "backlog", "44444444-0000-4000-8000-000000000000", "Elsewhere", ""); let mut board = boards(&[("one", &one), ("two", &two)]); // The merge tab lists every board's campaigns, each carrying the project it was // filed in, since an id there does not say which board holds it. assert_eq!(board.current().campaigns.len(), 1); assert_eq!(board.current().campaigns[0].project.as_deref(), Some("one")); board.select_campaign(Some(V1.to_string()), SCREEN); assert_eq!(board.current().campaign, Some(V1.to_string())); board.select_tab(1, SCREEN); assert_eq!(board.current().campaign, None, "the filter followed the tab change"); // And the tab it was set on kept it. board.select_tab(-1, SCREEN); assert_eq!(board.current().campaign, Some(V1.to_string())); std::fs::remove_dir_all(&one).ok(); std::fs::remove_dir_all(&two).ok(); } }