//! The board as one column per status, redrawn when the tree underneath it moves. The //! two terminal columns are hidden until `d` reveals them, one step of the rotation at //! a time. //! //! 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. //! //! **Reads by keypress, writes by command.** Every key on the board observes; `:` opens a //! prompt whose line is a worklane command, run through the same `dispatch` the shell //! reaches. Nothing here is a second front end to the board: there is no grammar the CLI //! does not have, and no handler this file calls directly. use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, HashMap}; use std::hash::{Hash, Hasher}; use std::io::Write as _; 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, Padding, Paragraph, Tabs, Wrap}; use crate::campaign::{CAMPAIGNS_DIR, CampaignIndex, Standing}; use crate::command::{Cli, Command}; use crate::history::{HistoryPart, history_parts, history_root, read_history}; use crate::split::{Unclosed, split_line}; use crate::tag::{NO_ANNOTATION, TAGS_FILE, TagIndex}; use crate::util::*; /// How long the event poll waits before letting the tick run. pub const POLL: Duration = Duration::from_millis(250); /// The file the lines typed on a board are kept in, in the board's own folder beside the /// status directories. /// /// The one file under `.worklane` the board writes rather than a command, and the only /// one that is not markdown: it is a list of lines, read by nobody but the prompt. Not in /// `digest`, so appending to it never counts as the tree moving and never provokes a /// reload. pub const RECALL_FILE: &str = ".wlhistory"; /// 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 `screen_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, /// The frame above the columns, at the height it is drawn, or `None` for a tab showing /// the whole board. /// /// A state rather than the bool it was, because the frame has two heights now and every /// measurement of the board has to agree about which one it is at. `Option` rather than a /// third variant, so "there is no frame" stays the shape it was and the two heights are /// only ever compared with each other. /// /// Named after the frame and not after the campaign that first filled it: a tag filter /// draws the same three rows of prose between the same two borders, so the geometry has /// one answer and only what is drawn into it depends on which filter is on. Which /// filter that is, [`Filter`] holds; this says nothing about it, which is what keeps /// every measurement of the board from having to ask. pub frame: Option, } /// How much of the board the frame above the columns is taking. /// /// Collapsed is where it opens and where it goes back to. Expanded is what `enter` asks for /// while the frame holds the selection, and it outlives the selection: the height is a view /// the reader chose, not a property of where the selection happens to be. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FrameSize { Collapsed, Expanded, } impl Chrome { /// The rows of prose the campaign frame holds. /// /// A constant rather than a height fitted to the description it is drawing. Every /// measurement of the board goes through `screen_rows`, so a frame that grew and shrank /// with the campaign would resize the columns whenever the filter changed, and a reader /// would look for a card where the previous campaign's description had put it. /// /// Three, up from the one row the frame opened with. A line and a half of prose was the /// wrong amount for the place the question it answers gets asked, and the two extra rows /// cost two rows of cards: on a 24 row terminal the columns go from 20 rows to 18, which /// is a card and a half of the four or five rows a card takes. Scrolling is what covers /// a description longer than this, which is why the constant does not have to be right /// for the longest one. const FRAME_PROSE_ROWS: u16 = 3; /// The rows the campaign frame takes: a border either side of its prose. /// /// The frame says the rest of what it has to say on its borders: the identity on the top /// one, and the standing, the way out and the page indicator on the bottom, the trade /// the detail overlay already makes with its title and its own indicator. Every row /// spent here is a row of cards. const FRAME_ROWS: u16 = Self::FRAME_PROSE_ROWS + 2; /// The rows the frame takes out of a board `height` rows tall. /// /// The height comes in because the expanded frame is a *share* rather than a second /// constant, and `screen_rows` is the one place that already has an area to take a share /// of — which is what keeps `Chrome` itself cheap and pure and copied from /// `Board::chrome` without a screen to hand. /// /// Half of what the frame and the columns divide between them: the board less the tab /// row and the footer, both a fixed length above and below. Half rather than most of it, /// and against the shared rows rather than against the whole screen, for the same reason /// the frame is not an overlay: the columns below it are the campaign's members, and a /// reader inspecting the campaign has to be able to go on seeing what it is made of. /// Floored, so the odd row goes to the cards. /// /// Bounded at both ends, and the upper bound is the one that matters: /// `Constraint::Min(COLUMN_MIN_ROWS)` would take the rows back silently, and the frame's /// own measurement would then disagree with what is drawn, which is the fault `Chrome` /// exists to prevent. The lower bound is [`Self::FRAME_ROWS`], since expanding must /// never shrink the frame — so on a board too short to divide, `enter` gives the /// collapsed frame back rather than a height nothing measured. fn frame_rows(self, height: u16) -> u16 { let Some(size) = self.frame else { return 0 }; let shared = height.saturating_sub(u16::from(self.tabbed) + FOOTER_ROWS); match size { FrameSize::Collapsed => Self::FRAME_ROWS, FrameSize::Expanded => { let room = shared.saturating_sub(COLUMN_MIN_ROWS).max(Self::FRAME_ROWS); (shared / 2).clamp(Self::FRAME_ROWS, room) } } } } /// The rows the columns are never asked to give up, and the footer's one row. /// /// Named because two places read each of them: `screen_rows` lays them out and /// `Chrome::frame_rows` bounds its share against them. A share computed against a /// reservation written out by hand is a share that comes to disagree with the layout. const COLUMN_MIN_ROWS: u16 = 3; const FOOTER_ROWS: u16 = 1; /// Where a tab's selection is: among its cards, or on the campaign frame above them. /// /// The board had no focus beyond a column and a card, and `select_card` clamped at zero. A /// frame that can hold the selection is a third place focus can be, so it is named rather /// than left as a bool beside the card index: every key that acts on a card has to answer /// for it, and a `match` on two variants is what makes an unanswered key something the /// reader can be told about instead of whatever the clamp happened to do. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Focus { /// A card in a column, which is where the board opens and where every jump lands. #[default] Cards, /// The campaign frame. Only ever set while the tab is filtered to a campaign, which /// `select_campaign` and `reload` are what keep true: a frame that is not drawn must /// never be holding the selection. Frame, } /// What a tab's columns are cut down to: one campaign, one tag, no campaign at all, or the /// whole board. /// /// A type rather than two `Option` fields and a rule that only one may be set. The /// board has one frame slot above the columns and it names what the columns are showing, so /// a tab filtered by a campaign *and* a tag would have two things to say there and no room /// to say either; a reader would also have no way to tell which of the two emptied a /// column. Making them mutually exclusive here is what stops that state existing at all, /// the way [`Focus`] made the third place a selection can be something every key answers /// for. /// /// A campaign is held by uuid, which is what a card names and what resolves inside one /// `.worklane`. A tag is held as itself: it has no id, it is the string `--tag` matches /// whole and case sensitively, and the same word means the same thing on every board. That /// is why the merge tab can carry a tag filter where it could not carry another project's /// campaign. /// /// The absence of a campaign is its own variant rather than a value inside [`Filter::Campaign`]: /// [`retain_campaign`] compares the field to the uuid it is given, so the tickets in no /// campaign are a different predicate over the field and not a different value in it — and a /// magic uuid meaning none is exactly the kind of thing that later matches a real one. Being /// keyed on nothing is also why it crosses boards where a campaign cannot, the property a /// tag filter already has on the merge tab. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub enum Filter { /// Every card the tab holds, which is where a tab opens. #[default] Whole, Campaign(String), Tag(String), /// Only the cards whose Campaign field is unset: the pile no campaign gathers. NoCampaign, } impl Filter { /// The campaign this filters to, or nothing for any other filter. /// /// What tells a filter that resolves against the campaigns directory from one that /// resolves against nothing. The no-campaign filter answers nothing here too, being a /// predicate over the field rather than a value in it; the frame, the focus and the /// geometry ask [`Filter::is_whole`] instead: every filter draws a frame, so any can /// hold the selection above the columns. pub fn campaign(&self) -> Option<&str> { match self { Filter::Campaign(uuid) => Some(uuid), _ => None, } } pub fn tag(&self) -> Option<&str> { match self { Filter::Tag(name) => Some(name), _ => None, } } /// Whether the tab is showing everything it holds. /// /// What `dismiss` asks, and what the footer asks to decide whether `q` takes a filter /// off or leaves the board: both are about there being a filter at all rather than /// about which kind it is. pub fn is_whole(&self) -> bool { matches!(self, Filter::Whole) } } /// 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, } /// What one reload builds for one tab: its columns, what it can be filtered by, and how /// many tickets on it name no campaign. type Reloaded = (Vec, Vec, Vec, usize); /// 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 whole description is carried off that read rather than /// the opening line it used to be cut to, because the file is only in hand while the /// directory is being read and the frame now pages through the rest of it. The cut lives on /// [`CampaignRow::summary`], for the caller that still wants one line. /// /// The standing is counted here too, off the cards the reload is already holding rather /// than by the walk of the status directories per campaign that `campaign ls` pays. A /// keypress must not pay that, and the picker needs every campaign's standing and not just /// the selected one's: the split into open and completed is what it decides. #[derive(Clone, Debug)] pub struct CampaignRow { pub uuid: String, pub title: String, pub codename: Option, /// The description as the file spells it, or empty for a campaign with none. pub description: String, /// When it was filed, as the file spells it. What the completed section is ordered by, /// so the couple that survive the truncation are the ones just finished. Compared as a /// string: `%Y-%m-%d %H:%M:%S` is lexicographic in chronological order, the property /// `by_status_order` already leans on. pub created_at: String, /// How far it has got, from the cards this board holds. pub standing: Standing, /// The project it was filed in, on the All tab only. A campaign is resolved inside one /// `.worklane`, so across several boards the id alone does not say which board holds /// it — the same reason a card carries its project there. 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()) } /// The opening line of the description, or empty for a campaign with none. /// /// For the picker, which has one row per campaign and no room for the rest. Taken off /// the description rather than held beside it: two fields, one cut from the other, are /// two strings free to come from different reads of the same file. pub fn summary(&self) -> &str { self.description.lines().next().unwrap_or_default() } /// Whether every member is done, which is what puts the row under `completed`. /// /// Off `Standing::state`, so the section a campaign lands in and the state the frame /// draws cannot come to disagree about what finished means. A campaign with no members /// is neither, per that method, and lists as open: completed means every member is /// done, and this one holds none to be done. fn completed(&self) -> bool { self.standing.state() == Some(DONE) } } /// A tag as the board holds it: what the picker lists and what the frame will draw. /// /// The union of the two vocabularies, built at reload: the tags the tickets carry, counted /// off the cards the reload is already holding, and the tags `.worklane/tags.md` declares, /// which no ticket has to carry for the board to know about them. Which of the two a row /// came from is the split the picker draws, so it is a field rather than something derived /// from the count: a declared tag nothing carries and an undeclared tag are both real, and /// telling them apart is the whole reason the vocabulary file exists. /// /// The annotation is carried whole rather than as the one line the picker row shows, the /// trade [`CampaignRow`] makes with its description: the file is only in hand while the /// board is being read, and the frame that pages through the rest of it is the next ticket. #[derive(Clone, Debug)] pub struct TagRow { /// The tag itself, which is also its identity: `--tag` matches it whole and case /// sensitively, and there is no id to hold it by. pub name: String, /// What the vocabulary says the tag means, or `None` for a tag no board declares. /// /// `Some("")` is a tag declared with nothing said about it, which is a different answer /// from `None` and the reason this is not a bare string: one was agreed on and left /// unexplained, the other was never agreed on at all. pub annotation: Option, /// How many cards on this tab carry it, drawn or not. /// /// Every column, done included, for the reason `standings_of` counts every column: /// hiding done changes what is drawn and never what is counted. Zero is what a declared /// tag nothing carries shows, which is what makes picking it and getting an empty board /// something the reader saw coming. pub count: usize, } impl TagRow { /// Whether the vocabulary file declares this tag, which is the section it lands in. pub fn declared(&self) -> bool { self.annotation.is_some() } /// The opening line of what it means, or empty for a tag with nothing said about it. /// /// The cut lives here rather than on the field, the way [`CampaignRow::summary`] takes /// one line off a description held whole. pub fn summary(&self) -> &str { let annotation = self.annotation.as_deref().unwrap_or_default(); match annotation == NO_ANNOTATION { true => "", false => annotation.lines().next().unwrap_or_default(), } } } /// 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 tags this tab can be filtered to: every tag its board declares or carries, and /// on the merge the union across every board. Rebuilt at reload beside the columns. /// /// A union rather than a per-board list, unlike `campaigns`, which carries the project /// each was filed in. A tag is a string and the same string on every board, so the merge /// tab's `bug` is one row standing for every board's, and filtering to it cuts all of /// them at once. pub tags: Vec, /// How many tickets on this tab name no campaign, drawn or not. /// /// Counted at reload off the columns before either filter is applied to them, for the /// reason the standings are: how many tickets are in no campaign is not a question about /// what the tab is currently showing, and a count taken off the filtered columns would /// answer zero about itself. The picker's first row draws it and the frame repeats it. /// /// On the merge tab it is every board's, summed — an unset field means the same thing in /// every `.worklane`, which is why this filter crosses boards where a campaign cannot. pub no_campaign: usize, /// What the columns are cut down to: one campaign, one tag, no campaign, or 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. A tag would survive the crossing, being a string every /// board can carry, but it goes on the tab beside the campaign because the two are one /// filter and one field. pub filter: Filter, /// Whether the selection is on a card or on the campaign frame above the columns. /// /// Per tab like the rest of the selection, so switching away and back returns to where /// the tab was left. A tab showing the whole board has no frame to hold it, which is /// the invariant `select_campaign` and `reload` keep. pub focus: Focus, /// Whether the frame is drawn at its expanded height. /// /// Per tab like the filter it belongs to. Not per focus: `enter` on the frame is what /// sets it and `enter` on the frame is what takes it back, so the height survives the /// selection moving down to the cards — the reader chose a view of the campaign, not a /// thing about where the highlight is. pub expanded: bool, /// First visible line of the frame's prose, counted in wrapped lines the way /// `Board::offset` counts the overlay's. /// /// Per tab beside the filter, since the filter is per tab: the frame draws the campaign /// this tab is showing, so how far into its description the reader has got is a fact /// about this tab and not about the board. pub frame_offset: u16, } impl Tab { fn new(name: String) -> Self { Tab { name, columns: Vec::new(), column: 0, card: 0, offsets: Vec::new(), campaigns: Vec::new(), tags: Vec::new(), no_campaign: 0, filter: Filter::default(), focus: Focus::default(), expanded: false, frame_offset: 0, } } /// 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.filter.campaign()?; self.campaigns.iter().find(|row| row.uuid == uuid) } /// The selected tag, or nothing when the tab is not filtered to one. /// /// Looked up in the tab's own rows rather than answered from the filter string alone, /// because the frame draws what the row carries and not just the word: the annotation /// off the vocabulary file and the count off the cards, both read at reload. A tag the /// board neither declares nor carries resolves to nothing, which `reload` then clears, /// the answer `selected_campaign` gives a campaign that has left the board. fn selected_tag(&self) -> Option<&TagRow> { let name = self.filter.tag()?; self.tags.iter().find(|row| row.name == name) } /// The columns that are drawn: all of them, or everything up to the reach of the /// visibility. /// /// A prefix rather than a filter, which is what keeps `column` and `offsets` usable /// as indices into either. Taken from where done and discarded actually sit instead /// of assuming positions, with `the_terminal_columns_are_last_in_the_order_drawn` /// pinning the order so the two cannot drift apart. fn visible(&self, visibility: Visibility) -> &[Column] { &self.columns[..self.visible_count(visibility)] } fn visible_count(&self, visibility: Visibility) -> usize { match visibility.next_reveal() { Some(status) => self .columns .iter() .position(|column| column.status == status) .unwrap_or(self.columns.len()), None => self.columns.len(), } } /// Keep the selection on a card that exists, after the board changes under it. fn clamp(&mut self, visibility: Visibility) { let visible = self.visible_count(visibility); 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), }; } /// The selected card, or nothing while the frame holds the selection. /// /// Nothing rather than the card the selection was last on. That card draws no highlight /// while the frame is focused, so handing it back here would leave `y` copying and /// `enter` opening a ticket the reader can no longer see picked out — a stale card, and /// the one thing a third focus must not introduce. `enter` being inert on the frame /// falls out of this rather than being written into the dispatch. /// /// It is also what closes an open overlay when a tab whose selection is on its frame is /// switched to: `refresh_detail` follows the selection, and there is no ticket there to /// follow. fn selected(&self) -> Option<&Card> { if self.focus == Focus::Frame { return None; } 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 vertical stretches, each one drawn and measured whole. /// /// A flow stretch runs full width; a quoted one is laid out as two columns at draw /// time — a gutter the bar fills top to bottom, and the body beside it. That is what /// keeps a comment's bar over every row its prose wraps onto, which a bar riding in /// the text cannot do: the wrapper folds continuations underneath it. Sections are /// also what the clamp measures, summed, so the scroll and the draw cannot disagree /// about where any of them ends. pub sections: Vec, } /// One vertical stretch of the overlay, drawn and measured as a unit. #[derive(Debug)] pub enum DetailSection { /// Description, metadata, mechanical history rows and the blanks between them: /// full width, wrapped by the widget as always. Flow(Text<'static>), /// Somebody's words, from a [`HistoryPart::Quoted`] run. Carries the body only — /// the bar is the gutter the draw lays beside it, not text under which a wrapped /// row would lose it. Quote(Text<'static>), } impl DetailSection { fn text(&self) -> &Text<'static> { match self { DetailSection::Flow(text) | DetailSection::Quote(text) => text, } } /// The width this section wraps at: the gutter takes its two cells from the rest. fn width(&self, full: u16) -> u16 { match self { DetailSection::Flow(_) => full, DetailSection::Quote(_) => full.saturating_sub(GUTTER_WIDTH), } } } /// How wide a quoted run's gutter is: the bar and the gap before the body, so a quoted /// row reads exactly as wide as one the CLI prefixes. const GUTTER_WIDTH: u16 = 2; 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. A quote's rows carry /// no bar here, since on screen the bar is the gutter and not part of the line. #[cfg(test)] pub fn plain(&self) -> String { self.sections .iter() .flat_map(|section| section.text().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, } /// The open command prompt: the line, where the cursor is in it, and what the last enter /// had to say about it. /// /// One field on `Board` rather than a buffer beside a bool, for the reason [`Search`] is /// one: "the prompt is open" and "what is in it" cannot disagree, and closing it leaves /// nothing to reset. /// /// The cursor is a byte offset into `line`, which is what `String` inserts and removes at /// and what [`crate::split::split_line`] reads. Every key that moves it moves it by whole /// characters, so it is never inside one. #[derive(Debug, Default)] pub struct Prompt { pub line: String, pub cursor: usize, /// What the last enter could not do, cleared by the next edit of the line. The message /// is about the line that was refused, so it goes the moment the line changes; moving /// the cursor leaves it up, since the line it is about has not changed. `Search::missed` /// is the same rule with nothing to say but "no match". pub refused: Option, /// How far back `up` has walked into the tab's [`Recall`], or `None` while the line on /// the row is the reader's own. /// /// Here rather than on the recall, so closing the prompt forgets the position and not /// the lines: the next `:` opens at the end of the list again, which is where a shell /// opens. The lines outlive one opening of the prompt and the position does not. position: Option, /// The half typed line `up` walked away from, put back by walking down past the newest /// entry. `Some` exactly while `position` is. pending: Option, } impl Prompt { /// Every key that only edits the line or moves the cursor, which is all of them but /// `esc` and `enter`: those two are the mode's rather than the line's, and they are /// answered by [`Board::prompt_key`] before it gets here. /// /// Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell. There /// is no `tab`: suggesting the selected ticket is 00a14e7, and until then it is a key /// that must not reach the project tabs. Every other control combination lands on the /// last arm and does nothing, which is what stops `ctrl-d` reaching the action bound /// to `d`. fn key(&mut self, key: KeyEvent, control: bool) { match key.code { KeyCode::Left if !control => self.cursor = self.left_of(), KeyCode::Right if !control => self.cursor = self.right_of(), KeyCode::Home if !control => self.cursor = 0, KeyCode::End if !control => self.cursor = self.line.len(), // The three that change the line, so the message about what it used to say goes // with it. Movement above deliberately does not clear it. KeyCode::Backspace if !control => self.cut(self.left_of()), KeyCode::Char('w') if control => self.cut(self.word_start()), KeyCode::Char(typed) if !control => { self.line.insert(self.cursor, typed); self.cursor += typed.len_utf8(); self.refused = None; } _ => {} } } /// The offset one character to the left of the cursor, or the cursor itself at the /// start of the line. By characters, so a cursor never lands inside one. fn left_of(&self) -> usize { match self.line[..self.cursor].chars().next_back() { Some(c) => self.cursor - c.len_utf8(), None => self.cursor, } } /// The same one character to the right, or the cursor itself at the end. fn right_of(&self) -> usize { match self.line[self.cursor..].chars().next() { Some(c) => self.cursor + c.len_utf8(), None => self.cursor, } } /// Where the word before the cursor starts, which is what `ctrl-w` takes off: the /// separators immediately behind the cursor, and then the run of everything that is /// not one behind those. /// /// The separators first, so `ctrl-w` at the end of `mv 1b78a24 ` takes the id rather /// than the space alone, which is what a shell does with it. fn word_start(&self) -> usize { let back = |at: usize| { self.line[..at] .chars() .next_back() .map(|c| (at - c.len_utf8(), c)) }; let mut at = self.cursor; while let Some((before, c)) = back(at) { if !c.is_whitespace() { break; } at = before; } while let Some((before, c)) = back(at) { if c.is_whitespace() { break; } at = before; } at } /// Take everything between `from` and the cursor off the line, and put the cursor /// where it was taken from. Nothing to remove writes nothing. fn cut(&mut self, from: usize) { if from >= self.cursor { return; } self.line.replace_range(from..self.cursor, ""); self.cursor = from; self.refused = None; } /// Put a recalled line on the row with the cursor at its end, the way a shell hands /// one back: what a reader does with a recalled command is append to it or fix its /// tail, and the end is where both start. /// /// The message about the last enter goes with it, for the reason every edit in `key` /// takes it away: it was about a line that is no longer on the row. fn show(&mut self, line: String) { self.cursor = line.len(); self.line = line; self.refused = None; } } /// The lines already typed against one tab, and the file they outlive the run in. /// /// One per tab and parallel to [`Board::tabs`], so the tab in view decides which list `up` /// walks. A project's lines are the ones naming its ticket ids, and handing another /// board's `mv` back on this one would offer an id that resolves to nothing there. The /// tabs are fixed for the run, so the two cannot drift apart. /// /// `file` is `None` on the merge tab, which is the one tab that is not a board. /// `Board::current_project` resolves to nothing there and a command typed there is refused /// for that reason, see ebc5755, so there is no board to attribute the line to and nothing /// to append it to. Those lines are still recalled for the run: a refused line is the one /// most worth getting back, and it goes when the board does. pub struct Recall { /// Oldest first, so `up` walks backwards from the end. lines: Vec, /// The board's own [`RECALL_FILE`], or `None` for a recall that is kept nowhere. file: Option, } impl Recall { /// What a board has already been typed at, oldest first. /// /// A file that is missing or unreadable is an empty recall rather than a failure. A /// board with no history yet is the ordinary case and not worth a message, and one /// whose file cannot be read is a convenience gone rather than a board that will not /// start. Blank lines are dropped on the way in, so a file truncated or edited by hand /// cannot put an empty entry in the walk. fn load(dir: &Path) -> Self { let file = dir.join(RECALL_FILE); let lines = std::fs::read_to_string(&file) .unwrap_or_default() .lines() .filter(|line| !line.trim().is_empty()) .map(str::to_string) .collect(); Recall { lines, file: Some(file) } } /// A recall with no file behind it, which is the merge tab's. fn unkept() -> Self { Recall { lines: Vec::new(), file: None } } /// Keep a line that was entered, and append it to the file. /// /// Consecutive duplicates are kept once, so holding `up` steps through distinct /// commands rather than through the same `mv` typed four times. The rule is applied /// against what is already held, which after a [`load`](Self::load) is the file's last /// line, so it spans runs as well as one sitting. A blank line is no command and is /// not kept. /// /// Nothing is trimmed: the file is every line ever typed against that board. /// /// **A write that fails is silent.** The line is in `lines` either way, so the recall /// still works for the run on a board whose folder is read only, and a notice about a /// history file would be about the one thing the reader did not ask for. The line /// itself is what they asked for, and `run` already has the row for what came of it. fn keep(&mut self, line: &str) { if line.trim().is_empty() || self.lines.last().is_some_and(|last| last == line) { return; } self.lines.push(line.to_string()); let Some(file) = &self.file else { return }; let _ = std::fs::OpenOptions::new() .create(true) .append(true) .open(file) .and_then(|mut handle| handle.write_all(format!("{line}\n").as_bytes())); } } /// What a line that ends half typed is waiting for, or nothing when it is whole. /// /// The splitter reports the state rather than raising an error, and this is the sentence /// the row carries for it. Said here rather than at the call site so the three states are /// spelled in one place. fn unclosed_message(unclosed: Unclosed) -> Option<&'static str> { match unclosed { Unclosed::Closed => None, Unclosed::Single => Some("the line ends inside a ' quote"), Unclosed::Double => Some("the line ends inside a \" quote"), Unclosed::Escape => Some("the line ends on a backslash"), } } /// What clap resolved the line to, as the words a reader typed: `mv`, or `campaign show` /// for a command inside a group. /// /// Off the matches rather than off a `match` on `Command`, which would be a second list of /// every verb the CLI has — one that goes stale the day a command is added, and silently, /// since a missing arm would only ever be seen by whoever typed that verb. `None` is the /// bare form, which names no command at all. fn command_name(matches: &clap::ArgMatches) -> Option { let (name, inner) = matches.subcommand()?; Some(match command_name(inner) { Some(rest) => format!("{name} {rest}"), None => name.to_string(), }) } /// The one line the row carries for a line clap would not take. /// /// Clap's own message, because the grammar is clap's: a complaint written here would /// describe a rule this file does not own. What is dropped is the usage block and the /// `--help` line after it, which are a paragraph — the synopsis is d7e493e's, and until /// then the row says what is wrong rather than what would have been right. /// /// `--help` is the exception. It parses as an error of the kind that means *print this*, /// and what it would print is a page: caught here, or clap's help lands on the alternate /// screen the way an unsunk `println!` would. `--version` goes through the ordinary path /// because what it prints is one line by construction, which is exactly what fits. fn refusal(err: &clap::Error) -> String { if matches!( err.kind(), clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand ) { return "help is a page and this is a row: try it in a shell".to_string(); } let rendered = err.render().to_string(); rendered .lines() .take_while(|line| !line.starts_with("Usage:")) .map(str::trim) .filter(|line| !line.is_empty()) .collect::>() .join(" ") } /// What a handler's failure says on the board: its own message, and every cause under it /// on a line of its own. /// /// The message is the handler's for the reason its output is — `mv` names each open /// blocker on a line and tells the reader about `-f`, and a sentence written here would /// have to be kept in step with that one. Painted, since an error is built with /// `color_text` rather than through a sink, so the escapes come off before it is drawn. /// /// The causes are joined by newlines rather than by `: `, which is what anyhow's own /// `Debug` does, because the box has the rows and a chain folded onto one line is where /// the useful half ends up off the right edge. fn error_lines(err: &anyhow::Error) -> String { let mut lines = vec![err.to_string()]; lines.extend(err.chain().skip(1).map(|cause| cause.to_string())); without_escapes(&lines.join("\n")).trim_end().to_string() } /// What the board has to say in words until the next keypress takes it away. /// /// 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. /// /// **The text is what a command said, so it is as many lines as the command used.** A /// handler's answer is written for a person and already spells its own paragraphs; cutting /// it to the one row the footer has would drop the half of `mv` that names the blockers. /// Where it is drawn follows from that and is `Board::notice_on_row`: one line goes on the /// footer row where a copy's has always gone, and anything the row cannot hold is a box /// over the columns instead. #[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 lines to draw, never none: an empty notice is one empty line rather than a box /// with nothing in it, since `lines()` on `""` yields nothing at all. fn lines(&self) -> Vec<&str> { match self.text.lines().collect::>() { rows if rows.is_empty() => vec![""], rows => rows, } } } /// 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 { /// Which list is open, since the box is one piece of machinery over two. /// /// On the picker rather than on the board, for the reason the row and the query are: /// "a picker is open" and "what it is choosing between" cannot disagree, and closing it /// leaves nothing to reset. Everything about moving, querying and scrolling is the same /// either way; this decides only what `picker_list` builds, the answer carrying its own /// kind back to `take_picked`. pub kind: PickerKind, /// Which *drawn* row the highlight is on, headings and the truncation line included, /// so it and `offset` are counted in the same units and `picker_list` is the one place /// that decides what a row number means. pub row: usize, /// First visible row, counted in rows, since a picker row is one line. pub offset: u16, /// The query while it is open, on the terms `search` is on the board: `None` is the /// picker reading its keys as movement, and `Some("")` is an open query nothing has /// been typed into yet, which filters nothing. pub query: Option, } /// The picker's section headings. /// /// Lowercase like the column headings, since they are the same kind of chrome, and /// `completed` rather than the `done` `Standing::state` spells: a campaign sits in no /// status directory, so it is not *in* done the way a ticket under that heading is. /// Which of the two lists a picker is showing. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum PickerKind { #[default] Campaign, Tag, } const OPEN_SECTION: &str = "open"; const COMPLETED_SECTION: &str = "completed"; const DECLARED_SECTION: &str = "declared"; const UNDECLARED_SECTION: &str = "undeclared"; /// How many completed campaigns the list shows before it starts keeping them back. /// /// A couple. The completed tail only grows, and the reason to see any of it is to /// recognise what was finished recently; the rest is what `/` is for. const COMPLETED_SHOWN: usize = 2; /// One drawn row of the picker: a campaign, or a line of chrome about the ones around it. /// /// Only `Campaign` is selectable, which is what `move_picker` steps over and `take_picked` /// takes: a highlight resting on a heading would give `enter` nothing to do. /// /// Borrowed from the tab rather than owned, so the list stays what `Tab::campaigns` says it /// is. Nothing here is held on the `Picker`: the rows are derived on every draw and every /// keypress, which is what lets a campaign filed elsewhere reach an open picker on the next /// tick instead of being missing from a copy taken when it opened. #[derive(Debug)] enum PickerRow<'a> { /// A section heading, naming what the rows under it are. Heading(&'static str), Campaign(&'a CampaignRow), Tag(&'a TagRow), /// The tickets whose Campaign field is unset, with how many they are. NoCampaign(usize), /// How many older completed campaigns the truncation is keeping back. Hidden(usize), /// The query matched nothing, said in the box rather than left as an empty one. Missed, } /// What taking a picker row selects, kept across a rebuild of the list. /// /// A campaign is keyed by its uuid and a tag by itself — both strings the tab can be /// filtered by, which is what [`PickerRow::key`] handed back when those were the only two /// rows. The third answer names nothing on any file: the no-campaign row filters on the /// *absence* of a value, so it is its own variant here rather than an empty string standing /// in for one, and `take_picked` reads the kind off the key instead of off which list was /// open. /// /// Owned rather than borrowed, because the highlight has to outlive the rows it was read /// from: `reload` takes it before the lists are rebuilt and puts it back after. #[derive(Clone, Debug, PartialEq, Eq)] enum PickerKey { Campaign(String), Tag(String), NoCampaign, } impl PickerKey { /// What a test would call this answer, so a highlight can be named without reaching /// for a row number the sections have already moved. #[cfg(test)] fn name(&self) -> &str { match self { PickerKey::Campaign(uuid) => uuid, PickerKey::Tag(name) => name, PickerKey::NoCampaign => NO_CAMPAIGN_ROW, } } } /// What the no-campaign row and its frame are called, everywhere they are drawn. const NO_CAMPAIGN_ROW: &str = "no campaign"; impl PickerRow<'_> { /// What taking this row would filter the board to, or nothing for a row of chrome. /// /// One accessor for both kinds, which is what lets everything between the keypress and /// the filter — the step over selectable rows, the highlight kept across a rebuild, the /// value `enter` takes — be written once. /// /// `None` is also the test of whether a row can be highlighted at all, so a heading or /// the truncation line is stepped over rather than landed on. fn key(&self) -> Option { match self { PickerRow::Campaign(campaign) => Some(PickerKey::Campaign(campaign.uuid.clone())), PickerRow::Tag(tag) => Some(PickerKey::Tag(tag.name.clone())), PickerRow::NoCampaign(_) => Some(PickerKey::NoCampaign), _ => None, } } } /// The rows the picker draws: open campaigns above completed, filtered by the query. /// /// One flat list ordered by title put the completed campaigns among the open ones forever. /// The tail only grows, so on a board that has run for a while the ones worth picking were /// pushed towards the bottom and off it by the ones that are finished. /// /// The open section keeps the index's order, which is by title. The completed section is by /// `Created At` newest first, because what a reader recognises in a finished campaign is /// that it was finished recently, and it is truncated to [`COMPLETED_SHOWN`] behind a line /// saying how many are being kept back. An unstamped campaign sinks below every stamped one, /// the rule `by_status_order` holds for a column: a missing time is unknown rather than /// ancient, and unknown must not claim the head of a list. /// /// A query turns the truncation off, which is the point of having one: the campaign a reader /// is searching for is exactly the one the truncation hid. /// /// A heading is drawn only over rows that exist. An `open` heading over nothing is a row of /// the box spent saying there is nothing to say, the bargain an untagged card's label row /// already makes — and a section that is there always says which kind its rows are, which /// is what a query filtering down to completed campaigns alone has to keep saying. fn picker_list<'a>(tab: &'a Tab, picker: &Picker) -> Vec> { let query = picker.query.as_deref().unwrap_or_default(); let mut rows = match picker.kind { PickerKind::Campaign => campaign_picker_rows(tab, query), PickerKind::Tag => tag_picker_rows(tab, query), }; // A box with nothing in it says nothing about why, and the query that emptied it is // still on the footer to be corrected. if rows.is_empty() { rows.push(PickerRow::Missed); } rows } /// The campaign rows: the tickets in no campaign above open above completed. fn campaign_picker_rows<'a>(tab: &'a Tab, query: &str) -> Vec> { let (mut completed, open): (Vec<&CampaignRow>, Vec<&CampaignRow>) = tab .campaigns .iter() .filter(|campaign| picker_matches(campaign, query)) .partition(|campaign| campaign.completed()); completed.sort_by(|a, b| b.created_at.cmp(&a.created_at)); let found = completed.len(); if query.is_empty() { completed.truncate(COMPLETED_SHOWN); } let mut rows: Vec = Vec::new(); // First and never truncated, so it is reachable without scrolling on a board whose // completed tail would otherwise push it down: the pile is the one question about a // board of campaigns that no single campaign answers. Not under either heading — it // is not a campaign, and a section naming what its rows are would be lying about it. if no_campaign_matches(query) { rows.push(PickerRow::NoCampaign(tab.no_campaign)); } if !open.is_empty() { rows.push(PickerRow::Heading(OPEN_SECTION)); rows.extend(open.into_iter().map(PickerRow::Campaign)); } if !completed.is_empty() { rows.push(PickerRow::Heading(COMPLETED_SECTION)); rows.extend(completed.iter().copied().map(PickerRow::Campaign)); } if found > completed.len() { rows.push(PickerRow::Hidden(found - completed.len())); } rows } /// The tag rows: declared above undeclared, and neither truncated. /// /// The same two-section shape as the campaigns and the opposite reason for the second /// section. A completed campaign is finished with and the tail of them is truncated because /// it only grows; an undeclared tag is the one a reader most wants to see, since it is a /// word somebody typed onto a ticket that the board never agreed on. `campaign` and /// `campaigns` would have sat one under the other here, in different sections, the day the /// second was invented. /// /// So nothing is kept back, and the headings are drawn even when only one section has rows: /// which of the two a tag is in is the fact the split is for, and a single unlabelled list /// would leave the reader to guess it. fn tag_picker_rows<'a>(tab: &'a Tab, query: &str) -> Vec> { let (declared, undeclared): (Vec<&TagRow>, Vec<&TagRow>) = tab .tags .iter() .filter(|tag| tag_matches(tag, query)) .partition(|tag| tag.declared()); let mut rows: Vec = Vec::new(); if !declared.is_empty() { rows.push(PickerRow::Heading(DECLARED_SECTION)); rows.extend(declared.into_iter().map(PickerRow::Tag)); } if !undeclared.is_empty() { rows.push(PickerRow::Heading(UNDECLARED_SECTION)); rows.extend(undeclared.into_iter().map(PickerRow::Tag)); } rows } /// Whether a campaign answers the query: its short id, its codename or its title. /// /// The three things a picker row is chosen by, which is the three things the row draws. /// Case insensitive for the reason `first_match` is: a title has to be to be worth typing, /// and an id given the same treatment matches whatever case it was pasted in. /// /// An empty query matches everything, the opposite of the answer `first_match` gives and /// right for the opposite reason: a jump with nothing typed has nowhere to go, while a /// filter with nothing typed is not filtering. Pressing `/` must not empty the list. The /// query is trimmed, so a space typed while composing one does not blank it either. fn picker_matches(campaign: &CampaignRow, query: &str) -> bool { let query = query.trim().to_lowercase(); if query.is_empty() { return true; } let codename = campaign.codename.as_deref().unwrap_or_default(); short_id(&campaign.uuid).to_lowercase().contains(&query) || codename.to_lowercase().contains(&query) || campaign.title.to_lowercase().contains(&query) } /// Whether the no-campaign row answers the query: the words a reader would type for it. /// /// "no campaign" is what the row says, and "none" is the shorter way to ask for the same /// thing; both are matched as substrings, so a query still being typed narrows the same way /// it does over the campaigns. The row carries no id, no codename and no title — there is /// nothing else on it to be found by, which is the rule `picker_matches` holds: a row is /// found by what it draws. fn no_campaign_matches(query: &str) -> bool { let query = query.trim().to_lowercase(); if query.is_empty() { return true; } NO_CAMPAIGN_ROW.to_lowercase().contains(&query) || "none".contains(&query) } /// Whether a tag answers the query: the tag itself, or what it is annotated to mean. /// /// The two things the row draws, which is the rule `picker_matches` follows for a campaign. /// The annotation is in because a reader who cannot remember the word can often remember /// what it was for, which is the whole reason the vocabulary is written down. /// /// Case insensitive, unlike `--tag` itself. Matching a tag is the filter and has to keep /// `Bug` and `bug` apart; searching for one is a reader typing, and a query that had to be /// cased right would be a worse way to find the tag than scrolling. fn tag_matches(tag: &TagRow, query: &str) -> bool { let query = query.trim().to_lowercase(); if query.is_empty() { return true; } tag.name.to_lowercase().contains(&query) || tag .annotation .as_deref() .is_some_and(|annotation| annotation.to_lowercase().contains(&query)) } /// How much of the flow's tail is drawn: neither terminal column, done alone, or both. /// /// The states are cumulative rather than independent, which is what keeps hiding a /// prefix of the columns and the selection arithmetic that rests on it working /// unchanged. `d` walks the rotation in this order and wraps; discarded sits last in /// it because it is the least likely thing to be looking for. The default is the /// board's opening state, the opinion `ls` holds: both are counted everywhere and /// drawn nowhere until asked for. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Visibility { #[default] Neither, Done, Both, } impl Visibility { /// The next state of the rotation, wrapping back to hidden from the top. fn advance(self) -> Self { match self { Visibility::Neither => Visibility::Done, Visibility::Done => Visibility::Both, Visibility::Both => Visibility::Neither, } } /// The status whose column this state reveals on the next press, which is also the /// boundary the drawn prefix stops short of: everything before it is on screen. /// Nothing left to reveal means nothing is hidden. fn next_reveal(self) -> Option<&'static str> { match self { Visibility::Neither => Some(DONE), Visibility::Done => Some(DISCARDED), Visibility::Both => None, } } } /// 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 command prompt while it is open, on the same terms as `search`. Only one of the /// two can be open at once: `:` is reachable from the action arms alone, and while /// either prompt has the keyboard the other's key is a character in a line. pub prompt: 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, /// How many of the terminal columns are drawn. Hidden 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 visibility: Visibility, pub should_quit: bool, projects: Vec, /// The lines typed against each tab, parallel to `tabs`. See [`Recall`] for why it is /// per tab rather than one list for the board. recalls: 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()))); // One per tab and in the same order, the merge's first when there is one. Read here // rather than at the first `:`, so a board that has been typed at before opens with // the walk already behind it and no keypress pays for a file read. let mut recalls: Vec = Vec::new(); if projects.len() > 1 { recalls.push(Recall::unkept()); } recalls.extend(projects.iter().map(|project| Recall::load(&project.dir))); let mut board = Board { tabs, tab: 0, detail: None, offset: 0, search: None, prompt: None, picker: None, notice: None, visibility: Visibility::default(), should_quit: false, projects, recalls, 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. /// /// Off the filter being on rather than off which filter it is, since the frame is one /// slot either of them fills. A tag frame that measured differently from a campaign one /// would be a second geometry to keep in step with the draw, which is what `Chrome` /// exists to stop there being. pub fn chrome(&self) -> Chrome { let tab = self.current(); Chrome { tabbed: self.tabbed(), frame: (!tab.filter.is_whole()).then_some(match tab.expanded { true => FrameSize::Expanded, false => FrameSize::Collapsed, }), } } pub fn current(&self) -> &Tab { &self.tabs[self.tab] } fn current_mut(&mut self) -> &mut Tab { &mut self.tabs[self.tab] } /// The recall of the tab in view: the lines `up` walks there, and where a line entered /// there is kept. /// /// Indexed by `tab` like `current`, because `recalls` is built parallel to `tabs` and /// both are fixed for the run. Switching tabs therefore switches the recall with it, /// with nothing to keep in step. fn recall_mut(&mut self) -> &mut Recall { &mut self.recalls[self.tab] } /// The project whose board the tab in view is showing, or nothing on the merge. /// /// The merge tab is the one tab that is not a board: its cards came from several /// `.worklane` directories and the tab itself is none of them. Routing a write there /// is ebc5755, which resolves the board off the card a command names; until then a /// command typed on it is refused rather than landing on whichever project came first. /// /// Resolved by index rather than by the tab's name, which is a label two projects can /// share — e1d79c3 is exactly that, and a write routed by name would be that bug with /// a file changing at the end of it. fn current_project(&self) -> Option<&Project> { // The merge takes index 0 when there is one, so the projects start one along. let first = usize::from(self.tabbed()); self.projects.get(self.tab.checked_sub(first)?) } /// Where a command typed on this tab runs, which is the project *above* its board. /// /// A handler takes the path to start looking from and walks up to the first /// `.worklane`, the way every shell invocation does, so what it wants is the directory /// holding the board rather than the board itself. Handing it `.worklane` would walk /// from inside the board and find the same one, but only by accident of there being /// nothing in the way; a `.worklane/.worklane` would take the write. fn command_root(&self) -> Option { let dir = &self.current_project()?.dir; Some(dir.parent().unwrap_or(dir).to_path_buf()) } /// 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(); let mut per_tags: Vec> = Vec::new(); let mut per_no_campaign: Vec = Vec::new(); for project in &self.projects { let (columns, campaigns, tags) = 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, }; // The standing on each row is counted off these columns, before the campaign // filter is applied to them further down: a campaign's standing is how far it // has got, which is not a question about what the tab is currently showing. per_campaigns.push(campaign_rows(&campaigns, label, &columns)); // Counted off the same unfiltered columns, and for the same reason: how many // tickets carry a tag is not a question about what the tab is showing. per_tags.push(tag_rows(&tags, &columns)); // And this one beside them: how many tickets name no campaign at all. per_no_campaign.push(no_campaign_count(&columns)); per_columns.push(columns); } // The campaign the picker is highlighting, taken before the lists are rebuilt. The // row is an index into a list a tick can reshape, so it is the uuid that has to // survive the rebuild, the way `Tab::campaign` is a uuid and not an index. let highlighted = self.picked(); let mut built: 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. // The tags merge by name instead, since the same word is the same tag on every // board. The unset field adds across boards, being keyed on nothing. let campaigns = per_campaigns.iter().flatten().cloned().collect(); built.push(( merge(&per_columns, &self.projects), campaigns, merged_tag_rows(&per_tags), per_no_campaign.iter().sum(), )); } built.extend( per_columns .into_iter() .zip(per_campaigns) .zip(per_tags) .zip(per_no_campaign) .map(|(((columns, campaigns), tags), no_campaign)| { (columns, campaigns, tags, no_campaign) }), ); for (tab, (columns, campaigns, tags, no_campaign)) in self.tabs.iter_mut().zip(built) { tab.campaigns = campaigns; tab.tags = tags; tab.no_campaign = no_campaign; // 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.filter.campaign().is_some() && tab.selected_campaign().is_none() { tab.filter = Filter::Whole; } // A tag filter outlives its cards, which a campaign filter does not: a declared // tag nothing carries is a real thing to be looking at, and an empty board is // the honest answer to picking it. What it does not outlive is leaving the // vocabulary altogether, when it is neither declared nor carried anywhere. if let Some(tag) = tab.filter.tag() && !tab.tags.iter().any(|row| row.name == tag) { tab.filter = Filter::Whole; } // The frame goes with the filter, both the focus and the place its prose was // scrolled to: a frame that is no longer drawn must not be holding the // selection, and the next thing selected starts at the top of its own prose // rather than partway down the last one's. Keyed off there being a filter at // all, since either kind draws a frame and both are cleared just above. if tab.filter.is_whole() { tab.focus = Focus::Cards; tab.expanded = false; tab.frame_offset = 0; } // The campaign filter and its opposite are two predicates over the one field, // which is why they are decided in the same breath here rather than by a flag // somewhere on the filter. let columns = match &tab.filter { Filter::Campaign(uuid) => retain_campaign(columns, uuid), Filter::NoCampaign => retain_no_campaign(columns), Filter::Whole | Filter::Tag(_) => columns, }; tab.columns = retain_tag(columns, tab.filter.tag()); // 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.visibility); } self.digest = digest_of(&self.projects); // And put back, on the campaign rather than on the number: one filed or finished // elsewhere splits the list differently, so the row that held it has moved. if self.picker.is_some() { self.place_picker(highlighted.as_ref()); } // 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.visibility) } fn visible_count(&self) -> usize { self.current().visible_count(self.visibility) } /// 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 — terminal columns 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 visibility = self.visibility; self.current_mut().clamp(visibility); self.follow_selection(screen); self.refresh_detail(); } /// Advance the rotation one step: hide both, show done, show both, and back around. /// /// `ls` already holds the opinion the first state takes: it counts both terminal /// statuses in its summary and leaves them out of the listing. Done only grows, so /// a quarter of the width went to the column least often read; discarded is the /// same again, and the least likely thing to be looking for, which is why it is /// last in the rotation. /// /// Hiding is a change to what is drawn, never to what is read: the directories stay /// scanned and stay in the digest, so the counts in the footer are right and /// revealing a column needs no rescan. /// /// Showing a column appends it, 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. pub fn rotate_visibility(&mut self, screen: Size) { self.visibility = self.visibility.advance(); 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 visibility = self.visibility; self.current_mut().clamp(visibility); self.detail = None; self.offset = 0; self.follow_selection(screen); } pub fn selected(&self) -> Option<&Card> { self.current().selected() } /// Whether the footer row itself carries the notice, rather than a box over the columns. /// /// **One rule, two readers**: `draw_footer` asks it before spending the row, and `draw` /// asks it to decide whether to put the box up. Written twice they would come to /// disagree, and the way that shows is a message drawn in both places or in neither. /// /// The row holds a notice when it is one line and nothing else has taken the row. A /// command's answer is as many lines as the command used, and an error leaves the /// prompt open on the row it would otherwise have gone on, so both of those go in the /// box. It is where a copy's notice has always gone, which is the case this keeps /// unchanged: one line, on the row, no box. pub fn notice_on_row(&self) -> bool { let Some(notice) = &self.notice else { return false; }; notice.lines().len() == 1 && self.prompt.is_none() && self.search.is_none() && self.picker.is_none() } /// Move between columns, keeping the card index where it can land. /// /// Inert while the frame holds the selection. The frame spans the width of the board, so /// there is nothing beside it to move to, and moving the column underneath would change /// nothing on screen until the selection came back down — a keypress that quietly /// relocates where `↓` returns to is worse than one that does nothing. pub fn select_column(&mut self, delta: isize, screen: Size) { if self.current().focus == Focus::Frame { return; } 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 visibility = self.visibility; let tab = self.current_mut(); tab.column = (tab.column as isize + delta).clamp(0, last) as usize; tab.clamp(visibility); // 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(); } /// Move up and down the focused column, and on and off the frame above it. /// /// A step up from the top card reaches the frame, whichever filter drew it, and a step /// down from the frame comes back to the column the selection left, since the column /// index is never what changed. An empty column reaches it too: a column with no card to stand on must /// not be a column the reader is stuck in. /// /// Not from under an open ticket. There, up and down step through the tickets and the /// overlay follows, so a selection that reached the frame would have to either close the /// overlay on an arrow key or leave it showing a ticket nothing is selecting. The clamp /// at the top card is what it has always been while a ticket is open, and the frame is /// one `q` away. pub fn select_card(&mut self, delta: isize, screen: Size) { if self.current().focus == Focus::Frame { // Up has nowhere further to go, the answer the top card of a column gives. if delta > 0 { self.current_mut().focus = Focus::Cards; self.follow_selection(screen); self.refresh_detail(); } return; } let open = self.detail.is_some(); let tab = self.current(); let Some(column) = tab.columns.get(tab.column) else { return; }; let count = column.cards.len(); if delta < 0 && tab.card == 0 && !tab.filter.is_whole() && !open { self.current_mut().focus = Focus::Frame; 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; // A jump lands on a card, so it takes the selection off the frame: `/` reaching a // ticket the frame still held would leave the highlight where none of the keys that // act on a ticket do anything. tab.focus = Focus::Cards; 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), }; } /// Open a picker on the filter in view, or say there is nothing to pick from. /// /// A board with nothing of that kind 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 filter already applied, so `c` or `t` on a filtered board is a way /// to look at where you are as much as a way to move — and only when the open list is /// the kind that filter is, since a tag picker has nothing to highlight on a board /// filtered to a campaign. On the first row otherwise. pub fn open_picker(&mut self, kind: PickerKind, screen: Size) { let tab = self.current(); let (empty, held) = match kind { PickerKind::Campaign => ( tab.campaigns.is_empty(), // Either campaign answer holds its row: a filter to one campaign opens on // it, and a filter to no campaign opens on that row. match &tab.filter { Filter::Campaign(uuid) => Some(PickerKey::Campaign(uuid.clone())), Filter::NoCampaign => Some(PickerKey::NoCampaign), Filter::Whole | Filter::Tag(_) => None, }, ), PickerKind::Tag => ( tab.tags.is_empty(), tab.filter.tag().map(|tag| PickerKey::Tag(tag.to_string())), ), }; if empty { let what = match kind { PickerKind::Campaign => "campaigns", PickerKind::Tag => "tags", }; self.notice = Some(Notice::failed(format!("no {what} on this board"))); return; } self.picker = Some(Picker { kind, ..Picker::default() }); self.place_picker(held.as_ref()); // The list is taller than the box on a board with many tags, so the highlight has // to be brought into it rather than left at an offset the last picker had. self.align_picker(screen); } /// What the highlight is on, as the answer taking it would filter the board to: a /// campaign, a tag, or no campaign. Nothing when the picker is closed or the highlight /// is on chrome. /// /// Through the drawn list rather than by indexing the tab's own list, because that is /// what the row number counts: the sections reorder the rows and add rows of their own, /// so the two lists agree about no number past the first heading. /// /// Owned rather than borrowed, unlike the campaign row it used to hand back. Every /// caller wanted the key and cloned it, and a borrow of the board is exactly what a /// caller about to mutate the board cannot hold. fn picked(&self) -> Option { let picker = self.picker.as_ref()?; picker_list(self.current(), picker).get(picker.row)?.key() } /// Put the highlight on `key`, or on the first row that can be taken. /// /// By key rather than by keeping the number, the answer `Tab::campaign` gives for the /// filter: a query typed into or a tick that finishes a campaign reshapes the list, and /// a number kept across that names whichever campaign now sits at it. A row the list no /// longer holds leaves nothing to hold on to, so the highlight goes to the top of what /// is there — which is where an incremental filter puts it anyway. /// /// The top is deliberately not where it starts: the fallback skips the no-campaign row /// and lands on the first campaign, which is what this picker has always opened on and /// still the common thing asked of it. The no-campaign row sits above the list without /// claiming it — reachable in one step up, and holding the highlight whenever it was the /// row selected. Only when every campaign is hidden — a query matching the pile alone — /// does it take the opening highlight. /// /// A list of nothing but chrome puts it on row zero, where `take_picked` finds no /// campaign and does nothing. fn place_picker(&mut self, key: Option<&PickerKey>) { let Some(picker) = &self.picker else { return }; let rows = picker_list(self.current(), picker); let held = key.and_then(|key| rows.iter().position(|row| row.key().as_ref() == Some(key))); let at = held .or_else(|| { rows.iter() .position(|row| row.key().is_some_and(|key| key != PickerKey::NoCampaign)) }) .or_else(|| rows.iter().position(|row| row.key().is_some())) .unwrap_or(0); if let Some(picker) = &mut self.picker { picker.row = at; } } /// 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 move the highlight, and `hjkl`'s `k` and `j` beside them while no query /// is open. `enter` takes the highlighted campaign, `/` starts a query, and `esc` and /// `q` leave the board as it was. /// /// `/` has the role the board's own dispatch gives it, which is why the picker can take /// it at all: the key that searches a list of cards searches a list of campaigns. While /// the query is open every printable key goes into it — `q` types and so does `j` — and /// `esc` takes the query off before it takes the picker off, one layer at a time, the /// order `dismiss` closes the board's own layers in. Movement and `enter` stay live /// under an open query: a filtered list nothing can move in is a list nothing can be /// chosen from, which is what the filter was for. pub fn picker_key(&mut self, key: KeyEvent, screen: Size) -> bool { if self.picker.is_none() { return false; } let control = key.modifiers.contains(KeyModifiers::CONTROL); if control && key.code == KeyCode::Char('c') { return false; } let querying = self.picker.as_ref().is_some_and(|picker| picker.query.is_some()); match key.code { // Shared, query or no query, so the arms below can be about the letters alone. KeyCode::Up if !control => self.move_picker(-1, screen), KeyCode::Down if !control => self.move_picker(1, screen), KeyCode::Enter if !control => self.take_picked(screen), // The query, which owns every printable key while it is open. Ahead of the // letters below rather than ordered against them by hand. KeyCode::Esc if querying => self.requery(screen, |query| *query = None), KeyCode::Backspace if querying => self.requery(screen, |query| { if let Some(query) = query { query.pop(); } }), KeyCode::Char(typed) if querying && !control => self.requery(screen, |query| { if let Some(query) = query { query.push(typed); } }), KeyCode::Esc | KeyCode::Char('q') if !control => self.picker = None, KeyCode::Char('/') if !control => { self.requery(screen, |query| *query = Some(String::new())); } KeyCode::Char('k') if !control => self.move_picker(-1, screen), KeyCode::Char('j') if !control => self.move_picker(1, screen), KeyCode::Char(' ') if !control => self.take_picked(screen), _ => {} } true } /// Change the query, and keep the highlight on the campaign it was on. /// /// The campaign rather than the row number, for the reason `place_picker` gives: typing /// reshapes the list under the highlight. One that no longer matches drops it to the /// first row that does. /// /// Opening and closing the query go through here too, since both change the list: an /// empty query filters nothing but a closed one also untruncates nothing, and closing /// one that had cut the list down gives every hidden row back. fn requery(&mut self, screen: Size, edit: impl FnOnce(&mut Option)) { let held = self.picked(); let Some(picker) = &mut self.picker else { return; }; edit(&mut picker.query); self.place_picker(held.as_ref()); self.align_picker(screen); } /// Move the highlight, clamped like a card rather than cycled like a tab. /// /// A list has a top and a bottom, and running off one end of a list of campaigns to /// the other is how a reader loses their place in it. fn move_picker(&mut self, delta: isize, screen: Size) { let Some(row) = self.stepped_picker_row(delta) else { return; }; if let Some(picker) = &mut self.picker { picker.row = row; } self.align_picker(screen); } /// The row a step of `delta` lands the highlight on, over selectable rows only. /// /// Section headings and the truncation line take no number: they are not campaigns, so /// the step walks on past them rather than stopping on one. A step that runs out of /// campaigns in that direction is no move at all — the highlight stays where it is, /// which is what a card at the end of a column does. fn stepped_picker_row(&self, delta: isize) -> Option { let picker = self.picker.as_ref()?; let rows = picker_list(self.current(), picker); let mut at = picker.row as isize; loop { at += delta; let at = usize::try_from(at).ok()?; if rows.get(at)?.key().is_some() { return Some(at); } } } /// Bring the highlight into the box's window. /// /// Split from the move because the query moves the highlight too, and because the list /// it is scrolling changes length: an offset left where a longer list put it would draw /// the box scrolled past its own rows. The draw caps it again on its own geometry, the /// way an unfocused column is capped, so a stale offset after a tick is corrected in /// the frame that draws it. fn align_picker(&mut self, screen: Size) { let Some(picker) = &self.picker else { return }; let count = picker_list(self.current(), picker).len() as u16; let height = picker_text_area(Rect::new(0, 0, screen.width, screen.height)).height; let Some(picker) = &mut self.picker else { return; }; let start = picker.row as u16; picker.offset = aligned_offset(picker.offset, start, start + 1, height, count); } /// Take the highlighted row and close the picker. /// /// A highlight on nothing takeable — the `no match` row, or a list of chrome — leaves /// the picker and the query exactly as they are, so the query can be corrected in place. /// That is what the search prompt does with a miss, and for the same reason: doing /// nothing visible is what makes a reader retype a query that was already right. fn take_picked(&mut self, screen: Size) { let Some(key) = self.picked() else { return; }; self.picker = None; // The key carries which list it came from: a campaign row keys a campaign and a tag // row keys a tag, so the kind is read off the answer rather than asked of a picker // that has just been put away. let filter = match key { PickerKey::Campaign(uuid) => Filter::Campaign(uuid), PickerKey::Tag(name) => Filter::Tag(name), PickerKey::NoCampaign => Filter::NoCampaign, }; self.select_filter(filter, screen); } /// Cut the tab in view down to one campaign or one tag, or back to the whole board. /// /// **The one place either filter is set**, which is what makes picking a tag clear a /// campaign and picking a campaign clear a tag: they are one field, so setting either /// is replacing whatever was there. Two setters keeping each other in step is the state /// [`Filter`] exists to stop being representable, and this is the other half of that — /// one writer, the way one command writes each field of a ticket. /// /// 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_filter(&mut self, filter: Filter, screen: Size) { if self.current().filter == filter { return; } self.current_mut().filter = filter; 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); // The frame is a different campaign's or a different tag's now, or gone, so the // selection comes back to the cards and its prose starts at the top — the answer // `refresh_detail` gives the overlay when the ticket under it changes. tab.focus = Focus::Cards; tab.expanded = false; tab.frame_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().filter.is_whole() { self.select_filter(Filter::Whole, 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; } } } } /// Open the command prompt on an empty line. /// /// Empty rather than the last line kept, for the reason `open_search` opens empty: the /// command that was typed has been dealt with, and reopening on it would make `:` and /// enter repeat something nobody asked for. Recalling a line is `a9bd6f0`. pub fn open_prompt(&mut self) { self.prompt = Some(Prompt::default()); } /// Feed a keypress to the open command prompt, and say whether it was taken. /// /// The same contract as `search_key` and `picker_key`, and it runs beside them for the /// same reason: the prompt owns the keyboard while it is open, so `q` typed into a /// command has to be a letter, `d` must not rotate the columns and `tab` must not /// change project. `ctrl-c` is the one key it declines, because a terminal application /// always honours it and a prompt that ate it would leave no way off the board. /// /// `esc` and `enter` are the mode's own two keys and are answered here; everything else /// belongs to the line and goes to `Prompt::key`. That split is also what keeps the /// borrow straight: closing the prompt takes the whole board, editing takes the prompt. /// /// The screen is enter's: a command that moves a ticket has to leave the selection on /// it, and bringing a card into view is the measurement `follow_selection` takes. pub fn prompt_key(&mut self, key: KeyEvent, screen: Size) -> bool { if self.prompt.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 if !control => self.prompt = None, KeyCode::Enter if !control => self.submit(screen), // The mode's, like `esc` and `enter`, and for the same reason: the walk is over // the tab's lines and the line on the row is only where it lands, so it takes // the whole board rather than the prompt alone. KeyCode::Up if !control => self.recall_back(), KeyCode::Down if !control => self.recall_forward(), _ => { if let Some(prompt) = &mut self.prompt { prompt.key(key, control); } } } true } /// `up`: one line further back, or the newest line when the reader is still on their /// own. /// /// The line being typed is put aside on the first press and comes back on the way down, /// so walking away from a half typed command never costs it. The oldest line is a stop /// rather than a wrap, which is what a shell does with it: holding `up` settles on the /// far end instead of cycling past it and offering the newest line again. /// /// An empty recall does nothing, and that includes leaving the line alone. `up` on a /// board that has not been typed at must not be a way to lose what is on the row. fn recall_back(&mut self) { // Two fields, borrowed apart: the lines are read while the prompt is written to. let lines = &self.recalls[self.tab].lines; let Some(prompt) = self.prompt.as_mut() else { return; }; let at = match (prompt.position, lines.len()) { (_, 0) => return, (None, len) => { prompt.pending = Some(prompt.line.clone()); len - 1 } (Some(0), _) => return, (Some(at), _) => at - 1, }; prompt.position = Some(at); prompt.show(lines[at].clone()); } /// `down`: one line nearer the present, and past the newest the line that was being /// typed, which is where the walk started. /// /// `down` with no walk under way does nothing. There is nothing in front of a line the /// reader is still typing, and emptying the row would be a keypress that destroys work. fn recall_forward(&mut self) { let lines = &self.recalls[self.tab].lines; let Some(prompt) = self.prompt.as_mut() else { return; }; let Some(at) = prompt.position else { return }; if at + 1 < lines.len() { prompt.position = Some(at + 1); prompt.show(lines[at + 1].clone()); return; } // Off the end of the walk and back on the reader's own line, which is unset when // `up` was pressed on an empty row. let pending = prompt.pending.take().unwrap_or_default(); prompt.position = None; prompt.show(pending); } /// What enter does with the line: run the command it resolved to, or say why it did /// not resolve to one. /// /// The grammar is clap's, with nothing restated. The line is tokenised the way a shell /// tokenises one, the binary's own name is put in front of the arguments, and the /// result goes to the same `Cli` definition the shell reaches: a flag added to a /// command is typeable here the day it is added, and no list of verbs lives on the /// board to go stale. /// /// The matches are what `command_name` walks to name what resolved; `from_arg_matches` /// on the same matches is what gives `run` the typed values. One parse, two readings, /// rather than a second `match` over every `Command` variant to name a verb. /// /// A line that does not resolve keeps the prompt open with the line and the cursor /// exactly as they were, and puts the message on the row, so a typo is corrected in /// place instead of retyped from `:`. That is `Search`'s hit-closes-miss-stays rule, /// and the reason both are true of one field. fn submit(&mut self, screen: Size) { let Some(prompt) = &self.prompt else { return }; let (line, cursor) = (prompt.line.clone(), prompt.cursor); // Kept before anything can refuse it, since a line that was refused is the one most // worth getting back: the fix is usually two characters, and retyping it from `:` // is what the walk exists to stop. `keep` drops a blank line and a repeat of the // line already at the end, so neither needs deciding here. self.recall_mut().keep(&line); // Before clap sees anything, because a line ending inside a quote is not a line // that failed to parse: it is one the reader has not finished typing, and handing // its half-open argument to clap would report a grammar fault about a sentence // nobody finished. let split = split_line(&line, cursor); if let Some(open) = unclosed_message(split.unclosed) { self.refuse(open.to_string()); return; } // Enter on an empty line closes the prompt and leaves the board as it was, the way // esc does. A line of nothing but separators is the same line: it names no command, // and the bare form of the CLI opens a board, which is already on the screen. if split.args.is_empty() { self.prompt = None; return; } let mut command = ::command().color(clap::ColorChoice::Never); let argv = std::iter::once(command.get_name().to_string()).chain(split.args); let matches = match command.try_get_matches_from_mut(argv) { Ok(matches) => matches, Err(err) => return self.refuse(refusal(&err)), }; let named = command_name(&matches); let parsed = match ::from_arg_matches(&matches) { Ok(cli) => cli, // Unreachable in practice, the derive reading back the matches it just made. // Reported rather than unwrapped, since a panic here takes the terminal down // with the alternate screen still on. Err(err) => return self.refuse(refusal(&err)), }; // No subcommand is the bare form, which opens a board: there is one on the screen, // so there is nothing to name and nothing to do but close. let Some(command) = parsed.command else { self.prompt = None; return; }; self.run(&command, named.as_deref(), screen); } /// Run a parsed command against the tab in view, and redraw the board on what it wrote. /// /// The handler is the same one `main` reaches, through the same `dispatch`: this is a /// caller of that table, never a second copy of it. It writes into a buffer rather than /// stdout, which under the board is the alternate screen in raw mode, so nothing a /// handler says can land on the frame — that is what `Sink` is for, and it is why the /// buffer is plain: the words come back as text and the board styles them itself. /// /// **What the handler said is what the board reports.** Those messages are already /// written for a person, and a second set kept here would go stale the first time one /// of them changed. A handler that says nothing gets the verb and `done`, since the /// row saying nothing at all reads as a keypress that missed. /// /// A handler that returns `Err` leaves the prompt open with the line intact: the usual /// cause is an ambiguous id, and the fix is two more characters rather than the whole /// line retyped from `:`. /// /// The reload is unconditional and runs either way. `tick` reloads on the digest, which /// is right for a change made in another pane and needless latency for one the board /// just made — the reader would watch their own `mv` take up to a poll interval to /// appear. Either way, because a handler that failed part way through has still /// written, and the columns must not go on drawing what is no longer on disk. fn run(&mut self, command: &Command, named: Option<&str>, screen: Size) { let Some(root) = self.command_root() else { self.refuse("a command needs a board: type it on a project tab".to_string()); return; }; // Taken before the reload, while the indices still point at the card the reader was // on. `mv` puts it in another column, `set --title` renames its file and a filter // can drop it out of view entirely, so an index kept across the rebuild is a // different ticket and the reader loses their place on every write. // // A ticket whose ID field is unset reads as the sentinel every unset field reads // as, which is not an address: two malformed tickets would carry the same one and // the selection would land on whichever came first. Nothing to follow, so the // clamp has it, the way it does for a selection that was on the frame. let held = self .selected() .map(|card| (card.ticket.uuid.clone(), card.ticket.id.clone())) .filter(|(uuid, _)| !is_unknown_value(uuid)); let mut buffer: Vec = Vec::new(); let outcome = { let mut sink = Sink::buffer(&mut buffer); crate::dispatch(command, &root, &mut sink).and_then(|()| sink.flush()) }; // Plain by construction, since the sink is: stripped anyway, because an escape // drawn into a ratatui paragraph is printed rather than obeyed, and this is the // one seam where a handler's bytes become a frame. let said = without_escapes(&String::from_utf8_lossy(&buffer)) .trim_end() .to_string(); if let Err(err) = self.reload() { self.notice = Some(Notice::failed(format!("reload failed: {err}"))); return; } // The board is redrawn on what the command wrote before anything is said about it, // so the sentence about where the selection went is about the board now on screen. let moved = held.and_then(|(uuid, id)| self.reselect(&uuid, &id, screen)); match outcome { Err(err) => self.notice = Some(Notice::failed(error_lines(&err))), Ok(()) => { self.prompt = None; let words = match said.is_empty() { true => format!("{}: done", named.unwrap_or("the command")), false => said, }; self.notice = Some(Notice::done(match moved { Some(gone) => format!("{words}\n{gone}"), None => words, })); } } } /// Put the selection back on the ticket it was on before the reload, and say so when /// the board no longer draws it. /// /// By uuid, never by index, for the reason `Tab::campaign` is a uuid: the slot is not /// the ticket. A `mv` moves the card to another column and a `set --title` renames its /// file, and either leaves the old indices pointing at whatever has taken that place. /// /// Three answers, and the second is the one worth the sentence. The card is in a drawn /// column, so the selection goes to it. It is on the board but in a column the rotation /// is hiding, which is where a `mv --status done` lands by default: the selection /// cannot follow it there, so the notice says where it went and which key shows it. Or /// it is not on the tab at all, which is a filter that no longer holds it — say that /// too, since a card silently vanishing from under the highlight reads as a bug. fn reselect(&mut self, uuid: &str, id: &str, screen: Size) -> Option { let visibility = self.visibility; let tab = self.current(); // Where the card is now, and whether that column is one of the drawn ones. let found = tab.columns.iter().enumerate().find_map(|(index, column)| { let card = column.cards.iter().position(|card| card.ticket.uuid == uuid)?; Some((index, card, column.status)) }); let drawn = tab.visible_count(visibility); let gone = match found { Some((column, card, _)) if column < drawn => { let tab = self.current_mut(); tab.column = column; tab.card = card; // The frame cannot hold the selection while a card does, and a command run // from the frame is a command run about no ticket at all. tab.focus = Focus::Cards; None } // On the board, in a column `d` has not revealed. The status is named rather // than the column number, since that is what the reader asked for. Some((_, _, status)) => { self.current_mut().clamp(visibility); Some(format!("({id}) is in {status}, which d shows")) } None => { self.current_mut().clamp(visibility); Some(format!("({id}) is no longer on this tab")) } }; self.follow_selection(screen); self.refresh_detail(); gone } /// Keep the prompt open, with the line untouched, carrying what enter had to say. fn refuse(&mut self, message: String) { if let Some(prompt) = &mut self.prompt { prompt.refused = Some(message); } } /// 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 { // On the frame it is what the frame names, since that is what the selection is on // and what its own top border prints. `y copy id` means the id of the selected thing // in every state the selection can be in, rather than a key that stops working one // row above the cards. if self.current().focus == Focus::Frame { return self.frame_id(); } self.selected().map(|card| card.ticket.id.clone()) } /// What the frame above the columns is addressed by, or nothing when none is drawn. /// /// A campaign's seven characters, which is what its own border prints and what every /// command that takes a campaign resolves. A tag has no id to shorten: it *is* its name, /// which is what `ls --tag` matches whole and case sensitively, so the whole word goes /// on the clipboard and the hash the border draws does not — `--tag` would not match it. /// /// The no-campaign frame has neither: no id to shorten, and no word a command line takes, /// since `ls --campaign` cannot say none — that spelling is its own ticket. `y` on this /// frame answers "nothing to copy", and the footer leaves it unnamed rather than naming /// a key into a notice. fn frame_id(&self) -> Option { let tab = self.current(); match &tab.filter { Filter::Whole | Filter::NoCampaign => None, Filter::Campaign(_) => tab .selected_campaign() .map(|campaign| short_id(&campaign.uuid).to_string()), Filter::Tag(name) => Some(name.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 = detail_last_offset(&detail.sections, text) as isize; self.offset = (self.offset as isize + pages.saturating_mul(step)).clamp(0, last) as u16; } /// Scroll whatever `pgup` and `pgdn` belong to: the open ticket, or the campaign frame. /// /// The precedence is here rather than in the dispatch, the rule `dismiss` follows: the /// match arms in `main.rs` are not reachable from a test, so a layering rule written /// into one of them is a rule nothing can check. /// /// An open ticket wins, whatever holds the selection behind it. It is the thing the /// reader put on and the thing they are reading, and it has had these two keys since /// 1b78a24; the frame takes them only when there is no overlay to take them first. With /// neither open they do nothing, which is what they did on the board before the frame /// could be scrolled. pub fn scroll_page(&mut self, pages: isize, screen: Size) { if self.detail.is_some() { self.scroll_detail(pages, screen); return; } if self.current().focus == Focus::Frame { self.scroll_frame(pages, screen); } } /// Scroll the frame's prose by whole screenfuls, one line kept for overlap. /// /// The overlay's arithmetic, deliberately: `scroll_step` decides the step and /// `last_offset` the clamp there, and prose wrapped into a viewport is prose wrapped /// into a viewport. Two sets of rules is how the same two keys come to move different /// distances in the two places a reader presses them. /// /// A campaign's description or a tag's annotation, whichever the frame is drawing, /// through `frame_content` rather than a second look at the filter: the clamp has to be /// measured against the text the draw wraps, and prose reached two ways is two texts /// free to disagree about where the end of it is. The title it builds and this throws /// away is a `Vec` of two spans, which is cheaper than the second dispatch would be to /// keep in step. /// /// Inert on prose that fits, since `last` is zero and the clamp leaves the offset where /// it is — which is what leaves a short description's frame selectable rather than /// making it a place the keys had to be kept away from. The screen comes in for the /// reason `scroll_detail` takes it. pub fn scroll_frame(&mut self, pages: isize, screen: Size) { let chrome = self.chrome(); let text = frame_text_area(screen, chrome); // The frame spans the board, so its border width is the screen's: `screen_rows` // only ever splits vertically. let Some(content) = frame_content(self.current(), screen.width) else { return; }; let step = scroll_step(text.height) as isize; let last = last_offset(&content.prose, text) as isize; let tab = self.current_mut(); let at = tab.frame_offset as isize + pages.saturating_mul(step); tab.frame_offset = at.clamp(0, last) as u16; } /// What `enter` does: the frame's height on the frame, the overlay on a card. /// /// The routing is here rather than in the dispatch, the rule `dismiss` and `scroll_page` /// follow: the arms in `main.rs` are not reachable from a test. It is also what stopped /// being automatic — `enter` was inert on the frame because `Tab::selected` hands back /// nothing there and `toggle_detail` had nothing to open, and that answer is now the /// thing in the way. pub fn toggle_focused(&mut self, screen: Size) { match self.current().focus { Focus::Frame => self.toggle_frame(screen), Focus::Cards => self.toggle_detail(), } } /// Give the frame's prose half the board, or give the rows back. /// /// Only from the frame, since it is the frame's own height and `enter` on a card is the /// overlay's. `q` is not involved: it takes the campaign filter off from either height, /// because the expanded frame is the frame at its other height and not a layer laid over /// the board — putting a press between the reader and the board is what a fourth layer /// would cost, and `enter` already undoes what `enter` did. /// /// Nor does the selection take it back. Up and down go on moving on and off the frame /// and leave it where it was, so the columns stay short with the selection on a card. /// That is the point: the height is a view of the campaign the reader chose. pub fn toggle_frame(&mut self, screen: Size) { if self.current().focus != Focus::Frame { return; } self.current_mut().expanded = !self.current().expanded; // The viewport changed height, so where the reader was may be past the end of it: a // taller frame has a smaller last offset than a shorter one. A scroll of no pages is // that clamp and nothing else, which keeps it in the one place it lives — and it // leaves the reader where they were rather than back at the top of the description. self.scroll_frame(0, screen); } 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 history. /// /// Styled spans rather than painted text, since an escape sequence in a ratatui /// 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).ok()) .unwrap_or_default(); let history = match worklane_dir { Some(worklane_dir) => read_history(worklane_dir, &uuid).unwrap_or_default(), None => Vec::new(), }; // Colour on, and nothing here is painted: the body arrives as cells, the relations // as rows and the history block as segments, and `detail_sections` turns them into // stretches of spans. An escape sequence never enters, which is what a ratatui // paragraph would draw as literal bytes. let mut parts = content_parts(&content, true, &resolved); parts.push(BodyPart::Cells(vec![Cell::plain("\n")])); let sections = detail_sections(&parts, &history_parts(&history)); Detail { title: ticket.title.clone(), id: ticket.id.clone(), project: card.project.clone(), sections, } } /// One piece of the overlay, from either source: the ticket's own body or the log. /// /// A private fold over the two input shapes, so [`detail_sections`] takes one walk /// instead of two that could disagree about where a quote begins and ends. enum Piece { Cells(Vec), Relations(Vec), Quoted(String), } /// The overlay as vertical sections. /// /// Flow pieces accumulate exactly as the one text used to — an unterminated run runs on /// into the next part, so the seam between text and relations is wherever the body put /// it. A quoted piece closes what is open, banks it as its own flow section, and becomes /// a quote section carrying the bare body: the bar is geometry the draw lays beside these /// rows, which is what keeps it over every row the prose wraps onto. /// /// The one newline after a quoted run is consumed rather than drawn. It used to close /// the quote's last line; now the section boundary does that, and drawing the newline /// would bank a blank row no entry ever had. History always writes exactly that cell /// after a quote — a comment body and a reason alike — so consuming one leading newline /// from the next flow piece is exact, not heuristic. fn detail_sections(parts: &[BodyPart], history: &[HistoryPart]) -> Vec { let mut pieces: Vec = parts .iter() .map(|part| match part { BodyPart::Cells(cells) => Piece::Cells(cells.clone()), BodyPart::Relations(rows) => Piece::Relations(rows.clone()), }) .chain(history.iter().map(|part| match part { HistoryPart::Flow(cells) => Piece::Cells(cells.clone()), HistoryPart::Quoted(body) => Piece::Quoted(body.clone()), })) .collect(); let mut sections: Vec = Vec::new(); let mut lines: Vec> = Vec::new(); let mut open: Vec> = Vec::new(); // Set while the previous section was a quote, so the next flow piece knows to give // up the newline that closed the quote before sections existed. let mut after_quote = false; for piece in pieces.drain(..) { match piece { Piece::Quoted(body) => { if !open.is_empty() { lines.push(Line::from(std::mem::take(&mut open))); } if !lines.is_empty() { sections.push(DetailSection::Flow(Text::from(std::mem::take(&mut lines)))); } sections.push(DetailSection::Quote(Text::from( body.split('\n') .map(|line| Line::from(span_from(line, None, None))) .collect::>>(), ))); after_quote = true; } Piece::Cells(cells) => { for cell in cells { let mut rest = cell.text.as_str(); if after_quote && rest.starts_with('\n') { after_quote = false; rest = &rest[1..]; if rest.is_empty() { continue; } } while let Some((line, tail)) = rest.split_once('\n') { if !line.is_empty() { open.push(span_from(line, cell.color, cell.modifier)); } lines.push(Line::from(std::mem::take(&mut open))); rest = tail; } if !rest.is_empty() { open.push(span_from(rest, cell.color, cell.modifier)); } } } // One line each, from the same cells `render_relations` paints, so the block // cannot read differently here than it does in `show`. Piece::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)); } if !lines.is_empty() { sections.push(DetailSection::Flow(Text::from(lines))); } sections } /// A cell as the board draws it: the same text in the same style, as a span. /// /// The other half of `paint_cells`, which is the CLI's. `From` and /// `From` are what make the two agree about what the style is. fn span_of(cell: Cell) -> Span<'static> { span_from(cell.text, cell.color, cell.modifier) } /// The same, for a renderer holding the parts of a cell rather than the cell. /// /// The bold on magenta is not a flourish. `Color::Magenta.ansi()` is `\x1b[1;35m`, so /// the CLI draws every bold run bold as well as magenta, and a board that dropped the /// modifier would be painting the same cell differently from the CLI. The colour is the /// only thing `From` can carry, so the attribute has to be added on this side. /// /// A cell's own modifier is the other one, and it arrives on cells with no colour too, so /// there is no early return for the uncoloured case any more: a struck plain run is a /// styled span with no foreground rather than a raw one. `crate::util::Modifier` is spelled /// out because `Modifier` in this file is ratatui's, which is what the style asks for. fn span_from( text: impl Into, color: Option, modifier: Option, ) -> Span<'static> { let mut style = Style::default(); if let Some(color) = color { style = style.fg(color.into()); if color == Color::Magenta { style = style.add_modifier(Modifier::BOLD); } } if let Some(modifier) = modifier { style = style.add_modifier(modifier.into()); } if style == Style::default() { return Span::raw(text.into()); } Span::styled(text.into(), style) } /// The 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, TagIndex) { let campaigns = CampaignIndex::load(worklane_dir).unwrap_or_default(); // Unreadable is an empty vocabulary here, where the CLI treats it as an error: the CLI // is about to rewrite the file and an empty read would erase it, and the board only // draws. A board that refused to open because of one unreadable file would be the fault // `unwrap_or_default` on the campaigns index already avoids. let tags = TagIndex::load(worklane_dir).unwrap_or_default(); // Over `Status::ALL`: the board draws every status, and hiding the two terminal // ones is a change to what is drawn, never to what is read. The footer counts are // read off these columns while the columns are hidden, so revealing one needs no // rescan. Each column is ordered by its own entry stamp, so the build needs the // status itself and not just the directory to read. let mut columns: Vec = Status::ALL .into_iter() .map(|status| { // An absent or unreadable directory is an empty column, not a missing one: // every status is the shape of the board. let mut cards: Vec = collect_ticket_items(worklane_dir.join(status.as_str())) .unwrap_or_default() .into_iter() .map(|ticket| Card { campaign: campaign_of(&ticket, &campaigns), ticket, project: None, blocked: false, }) .collect(); cards.sort_by(|a, b| by_status_order(status, &a.ticket, &b.ticket)); Column { status: status.as_str(), cards } }) .collect(); mark_blocked(&mut columns); (columns, campaigns, tags) } /// 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>, columns: &[Column], ) -> Vec { let standings = standings_of(columns); campaigns .iter() .map(|campaign| CampaignRow { uuid: campaign.uuid.clone(), title: campaign.title.clone(), codename: campaign.codename.clone(), description: section_prose(&campaign.content, &DESCRIPTION).unwrap_or_default(), created_at: parse_ticket_field(&campaign.content, "Created At"), standing: standings .get(campaign.uuid.as_str()) .copied() .unwrap_or_default(), project: project.map(|name| name.to_string()), }) .collect() } /// The tags of one board as the picker holds them. /// /// The union of what the file declares and what the cards carry, which is the same union /// `tags ls` prints and for the same reason: a declared tag nothing carries is a word the /// board agreed on and has not used, and a carried tag nothing declares is a word somebody /// invented in a hurry. Either one is worth being able to pick. /// /// Ordered by byte, which is what `BTreeMap` gives and what `worklane tags` prints in: /// `Bug` and `bug` stay two rows and land next to each other, which is where a near /// duplicate is spotted. Case is kept apart because `--tag` keeps it apart. fn tag_rows(tags: &TagIndex, columns: &[Column]) -> Vec { let mut counts: BTreeMap<&str, usize> = BTreeMap::new(); // Declared first, so a tag nothing carries still gets a row, at zero. for name in tags.names() { counts.entry(name).or_default(); } for column in columns { for card in &column.cards { for tag in &card.ticket.tags { *counts.entry(tag.as_str()).or_default() += 1; } } } counts .into_iter() .map(|(name, count)| TagRow { name: name.to_string(), annotation: tags.annotation(name).map(str::to_string), count, }) .collect() } /// Every board's tags as one list, for the merge tab. /// /// By name, unlike the campaigns on that tab, which are concatenated and each labelled with /// the project it was filed in. A tag is the same string wherever it appears, so two boards /// carrying `bug` are one row here and filtering to it cuts both: that is what makes a tag /// the axis the merge tab can actually be cut along. /// /// The counts add. The annotation is the first one any board declares, in tab order, and a /// tag declared differently on two boards is therefore shown as the first board means it. /// That is a real ambiguity and this is the cheap answer to it: the alternative is a row per /// board, which is the per-board list this function exists to avoid. fn merged_tag_rows(per_project: &[Vec]) -> Vec { let mut merged: BTreeMap<&str, TagRow> = BTreeMap::new(); for rows in per_project { for row in rows { match merged.get_mut(row.name.as_str()) { Some(held) => { held.count += row.count; if held.annotation.is_none() { held.annotation = row.annotation.clone(); } } None => { merged.insert(row.name.as_str(), row.clone()); } } } } merged.into_values().collect() } /// The columns filtered to the cards carrying one tag, or left as they are when none is /// selected. /// /// Matched whole and case sensitively, which is exactly how `ls --tag` matches: the board /// and the listing must not disagree about what carrying a tag means, or the same question /// asked two ways gives two answers. Every column is kept, empty ones included, for the /// reason `retain_campaign` keeps them. fn retain_tag(mut columns: Vec, tag: Option<&str>) -> Vec { let Some(tag) = tag else { return columns; }; for column in columns.iter_mut() { column .cards .retain(|card| card.ticket.tags.iter().any(|held| held == tag)); } columns } /// How far every campaign on one board has got, counted in one pass over its cards. /// /// The cards are already in hand here, and a campaign's members are exactly the cards /// naming its uuid, so this is what `Standing::of` builds for `campaign ls` without the /// walk of the status directories that one pays per campaign. Every column, drawn or not: /// hiding the terminal columns is a change to what is drawn and never to what is counted. /// /// A discarded member counts as finished, the rule `Standing::of` and `campaign ls` /// already hold: the work was decided out of the campaign rather than left in it. One /// spelling of that through [`is_open`], so the two counters cannot drift. /// /// A campaign nothing names is absent rather than zeroed, which `campaign_rows` reads as /// the default standing — `no members`, the same answer `campaign show` gives it. fn standings_of(columns: &[Column]) -> HashMap<&str, Standing> { let mut standings: HashMap<&str, Standing> = HashMap::new(); for column in columns { for card in &column.cards { let Some(uuid) = card.ticket.campaign.as_deref() else { continue; }; let standing = standings.entry(uuid).or_default(); standing.total += 1; standing.done += usize::from(!is_open(column.status)); } } standings } /// 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 one column per status 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, uuid: &str) -> Vec { for column in columns.iter_mut() { column .cards .retain(|card| card.ticket.campaign.as_deref() == Some(uuid)); } columns } /// The opposite predicate over the same field: only the tickets that name no campaign. /// /// A different question from [`retain_campaign`] and not a different value in it — comparing /// against a uuid that means none would be one rename or one reused id away from matching a /// real campaign. The field's absence is the whole test: a ticket whose Campaign names a uuid /// no campaign carries is *set* wrongly, not unset, and stays out of this view the way it /// draws `_missing_` on its own card rather than nothing at all. /// /// Every column kept, empty ones included, for the reason `retain_campaign` keeps them. The /// count beside this filter is [`Tab::no_campaign`], taken off the unfiltered columns; what /// this answers is which cards survive it. fn retain_no_campaign(mut columns: Vec) -> Vec { for column in columns.iter_mut() { column.cards.retain(|card| card.ticket.campaign.is_none()); } columns } /// How many tickets name no campaign, counted off one board's columns. fn no_campaign_count(columns: &[Column]) -> usize { columns .iter() .map(|column| { column .cards .iter() .filter(|card| card.ticket.campaign.is_none()) .count() }) .sum() } /// 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_cells` 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 is_open(status)) }); } } } /// Every board's columns as one set, 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 { // All five, matching what `columns_of` builds: the merge is indexed beside the // project tabs, and hiding is decided by the visibility, never by leaving a status // out here. Status::ALL .into_iter() .map(Status::as_str) .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(); // The vocabulary, for the reason the campaigns are: a tag declared elsewhere has to // reach the picker, and an annotation changed by `tags set` has to reach the row that // draws it. One file rather than a directory, so it is stamped here rather than visited, // and stamped before the walk so the closure below owns the borrow uncontested. let vocabulary = worklane_dir.join(TAGS_FILE); if let Ok(meta) = std::fs::metadata(&vocabulary) { let modified = meta .modified() .ok() .and_then(|at| at.duration_since(SystemTime::UNIX_EPOCH).ok()) .unwrap_or_default(); entries.push((vocabulary.to_string_lossy().to_string(), meta.len(), modified)); } 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)); // History entries live one level deeper, a directory per ticket. if let Ok(read) = std::fs::read_dir(history_root(worklane_dir)) { 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 = screen_rows(area, chrome); if chrome.tabbed { draw_tabs(frame, board, rows[TAB_ROW]); } if chrome.frame.is_some() { draw_frame(frame, board.current(), rows[FRAME_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); } // Last, so it is over everything: it is the newest thing said, it lives one keypress, // and what it is usually about is the ticket the overlay behind it is showing. // // A box rather than more rows of footer, and that is the whole reason it is an overlay: // a footer that grew and shrank as notices came and went would reflow the columns on // every keypress, moving every card the reader is looking at. Nothing here measures // into `Chrome`, so the columns are the same height with the box up as without it. if !board.notice_on_row() && let Some(notice) = &board.notice { draw_notice_box(frame, notice, rows[BOARD_ROW]); } } /// The notice as a box at the foot of the columns, for the answers the footer row cannot /// hold: a command that said several lines, and any command at all while the prompt is /// still open on an error. /// /// Bottom left, against the row the one-line notice would have used, so a reader who has /// just pressed enter looks in one place either way. Sized to the text rather than to the /// board — a two line answer draws a two line box — and cut to what the columns leave when /// the answer is longer than the screen, with the count of what was dropped on the last /// row so a cut never passes for the whole of it. /// /// Red for a failure, where `no match` and the refused line are red, and cyan otherwise: /// the accent this tool draws its keys and its focused border in. fn draw_notice_box(frame: &mut Frame, notice: &Notice, area: Rect) { let accent = match notice.failed { true => Color::BrightRed, false => Color::Cyan, }; // Two rows of border and at least one of text, and the same on the other axis: a box // too small for a line of the answer says nothing at all, and is worse than a cut one. // The width guard is also what keeps the clamp below from being asked for a range that // runs backwards, which panics — and a panic here takes the terminal down with it. let Some(room) = area.height.checked_sub(2).filter(|rows| *rows > 0) else { return; }; if area.width < 3 { return; } let lines = notice.lines(); let mut rows: Vec = lines.iter().take(room as usize).map(|l| l.to_string()).collect(); if lines.len() > room as usize { // The last row spends itself saying so, rather than the box ending mid-answer as // though that were all of it. let dropped = lines.len() - room as usize + 1; rows.pop(); rows.push(format!("… {dropped} more lines")); } // A border either side of the text, and a space either side of that, the padding the // overlay's own prose keeps. let width = rows.iter().map(|row| row.chars().count()).max().unwrap_or(0); let width = (width as u16).saturating_add(4).clamp(1, area.width); let height = rows.len() as u16 + 2; let box_area = Rect { x: area.x, y: area.y + area.height - height, width, height, }; let text: Vec = rows .into_iter() .map(|row| Line::from(Span::styled(row, Style::default().fg(accent.into())))) .collect(); frame.render_widget(Clear, box_area); frame.render_widget( Paragraph::new(text).block( Block::default() .borders(Borders::ALL) .border_style(Style::default().fg(accent.into())) .padding(Padding::horizontal(1)), ), box_area, ); } /// The rows of the frame, in the order `screen_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 FRAME_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 screen_rows(area: Rect, chrome: Chrome) -> std::rc::Rc<[Rect]> { Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(u16::from(chrome.tabbed)), Constraint::Length(chrome.frame_rows(area.height)), Constraint::Min(COLUMN_MIN_ROWS), Constraint::Length(FOOTER_ROWS), ]) .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, ); } /// What the frame above the columns draws, whichever filter put it there. /// /// Three fields because the frame is three slots: what it is filtered to, on the top /// border; how much of the board that is, on the bottom right; and what it means, in the /// rows between them. A struct rather than the draw asking which filter is on three times, /// so a slot added later is added to both frames at once — which is the whole reason the /// slot is shared rather than doubled. struct FrameContent { /// The top border: `(id) ~codename · Name` for a campaign, `#tag` for a tag. Cut by /// hand, because ratatui truncates a block title at whatever cell it reaches. title: Vec>, /// The bottom right: how far the campaign has got, or how many tickets carry the tag. /// Where the frame says what it is *about*, which is why the page indicator is on the /// other end of that border and gives way to `q board` before it. standing: Vec>, /// The rows between the borders: a description or an annotation, or the grey /// placeholder where there is neither. prose: Text<'static>, } /// What the tab's filter has to say for itself, or nothing when it is showing the whole /// board. /// /// **The one place the filters are told apart above the columns.** Everything the draw /// does with this is the same either way — the borders, the colour, the way out, the page /// indicator and the scroll are all the campaign frame's, and a tag fills its slots rather /// than inventing a second shape. A second `match` on the filter anywhere below here is how /// the frames come to behave differently in a way nobody decided. /// /// The no-campaign filter fills the same slots in its own words rather than being left /// frameless: `is_whole()` is what decides both that a frame is drawn and that /// [`Focus::Frame`] can hold the selection, and exempting one variant from either half would /// be a state where the selection rests on a frame that is not drawn — the one thing /// [`Focus`] exists to make unrepresentable. /// /// Nothing, too, for a filter that resolves to no row: `reload` clears both of those, so /// this is the answer to a draw that arrives before it rather than a state the board holds. fn frame_content(tab: &Tab, width: u16) -> Option { match &tab.filter { Filter::Whole => None, Filter::Campaign(_) => tab.selected_campaign().map(|campaign| FrameContent { title: campaign_title(campaign, width), standing: standing_spans(&campaign.standing), prose: campaign_prose(campaign), }), Filter::Tag(_) => tab.selected_tag().map(|tag| FrameContent { title: tag_title(&tag.name, width), standing: count_spans(tag.count), prose: tag_prose(tag), }), Filter::NoCampaign => Some(FrameContent { title: no_campaign_title(width), standing: count_spans(tab.no_campaign), prose: no_campaign_prose(), }), } } /// The frame above the columns: what the tab is filtered to, what it means, and how much of /// the board it is. /// /// The columns below are what the filter left, so this is the row that says what left them. /// [`Chrome::FRAME_ROWS`] rows for it, of which [`Chrome::FRAME_PROSE_ROWS`] are prose: the /// identity goes on the top border and the standing, the way out and the page indicator on /// the bottom one, the trade the detail overlay already makes with its title and its own /// indicator, and every row taken here is a row of cards. /// /// The tab comes in rather than the campaign or the tag alone, because the frame draws three /// of the tab's facts and not one: what it is filtered to, how far into that filter's prose /// the reader has scrolled, and whether the selection is on the frame or on a card below it. /// Cyan when it holds the selection, the colour the focused column's border and the /// overlay's already take. fn draw_frame(frame: &mut Frame, tab: &Tab, area: Rect) { let Some(content) = frame_content(tab, area.width) else { return; }; let focused = tab.focus == Focus::Frame; // The same rectangle `frame_text_area` reaches from the screen size for the keypress, // measured here off the area the draw was actually given: the relationship // `column_text_height` has with `draw_columns`, so a resize between a keypress and the // frame that follows it is corrected in the frame. let text = area.inner(Margin::new(1, 1)); // One measurement, three derivations, the rule `wrapped_height` holds for the overlay. // Clamped here as well as on the keypress for the same two reasons: the terminal may // have been resized since, and a tick can put shorter prose in front of a reader who was // at the end of the old. let last = last_offset(&content.prose, text); let offset = tab.frame_offset.min(last); let mut block = Block::default() .borders(Borders::ALL) .border_style(Style::default().fg(match focused { true => Color::Cyan.into(), false => Color::Grey.into(), })) .title(Line::from(content.title)); // 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. Drawn as a key hint and not as grey // chrome, because that is what it is, and it is the one key on the board named anywhere // but the footer: a reader who has learnt where the cyan letter is should not have to // learn a second convention to find this one. The indicator beside it keeps the chrome // colour, having no key in it. // // The page indicator follows it on the same border rather than going up beside the // title where the overlay's sits. The title is cut against the border it is on, so an // indicator up there would shorten a long campaign name the moment its description grew // past three rows, and the bottom right is the standing's — which is what the frame is // about, where this is only where the reader has got to in it. let mut hint = vec![Span::raw(" ")]; hint.extend(key_hint("q", "board")); hint.push(Span::raw(" ")); let indicator = page_indicator(offset, last, text.height, area.width).unwrap_or_default(); let room = area.width.saturating_sub(2) as usize; let taken = spans_width(&content.standing); let hint_width = spans_width(&hint); let indicator_width = indicator.chars().count(); // Dropped whole rather than cut, the rule the indicator follows on the overlay: half of // either reads as something else. The indicator goes first when the two cannot both fit, // because with a filter on the footer's last slot names `ctrl-c quit` and this is the // only place on the board that says `q` gives it back. Measured over the spans rather // than over one string, since the hint is three of them now. let left = match (hint_width + indicator_width + taken <= room, hint_width + taken <= room) { (true, _) => { let mut both = hint; both.push(Span::styled(indicator, Style::default().fg(Color::Grey.into()))); both } (false, true) => hint, (false, false) => Vec::new(), }; if !left.is_empty() { block = block.title_bottom(Line::from(left)); } block = block.title_bottom(Line::from(content.standing).right_aligned()); // Wrapped and scrolled, where the one row it opened with was cut at the border: with // three rows the prose has somewhere to go, and `pgup` and `pgdn` reach whatever is // past them. `Wrap` cannot push the frame taller than the geometry says it is — the rows // past the bottom are simply not drawn, which is what the offset is for. frame.render_widget( Paragraph::new(content.prose) .block(block) .wrap(Wrap { trim: false }) .scroll((offset, 0)), area, ); } /// How far the campaign has got, for the bottom right of its frame. /// /// Right-aligned 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. fn standing_spans(standing: &Standing) -> Vec> { let mut spans = vec![Span::raw(format!(" {}", standing.label()))]; if let Some(state) = standing.state() { spans.push(Span::styled( format!(" [{state}]"), Style::default().fg(Color::Orange.into()), )); } spans.push(Span::raw(" ")); spans } /// How many tickets carry the tag, for the same corner the standing takes. /// /// The count off the row, which `tag_rows` took over every column of the unfiltered board, /// done included — and with the tag filter on those columns *are* the tickets carrying it, /// so this counts what is drawn below without counting it a second way. Hiding the done /// column changes what is drawn and never what is counted, the rule the standing holds. /// /// Plain, with no derived state beside it: a tag is a word and not a piece of work, so there /// is no `[open]` to be in. The noun is spelled out because a bare number on a border says /// nothing about what was counted, and it is pluralised for the reason `ls` pluralises its /// own counts. fn count_spans(count: usize) -> Vec> { let noun = match count == 1 { true => "ticket", false => "tickets", }; vec![Span::raw(format!(" {count} {noun} "))] } /// The campaign's description as the frame draws it, or the placeholder for a campaign with /// none. /// /// The placeholder rather than a blank row, the bargain the one-row frame already took: the /// rows are spent either way, and an empty frame reads as one that failed to draw. Grey, /// because it is the absence of prose rather than prose. /// /// One place, for the reason `wrapped_height` is one place: the draw, the scroll clamp and /// the page indicator all measure this, and prose measured twice is two heights free to /// disagree about where the end of it is. fn campaign_prose(campaign: &CampaignRow) -> Text<'static> { match campaign.description.is_empty() { true => Text::from(Line::from(Span::styled( DESCRIPTION.placeholder, Style::default().fg(Color::Grey.into()), ))), false => Text::from(campaign.description.clone()), } } /// What the tag means, as the frame draws it, or the placeholder where the board has never /// said. /// /// [`NO_ANNOTATION`] rather than the description section's placeholder, because it is what /// the vocabulary file itself holds under a heading with nothing under it: the frame and /// `tags.md` say the same thing about the same tag. Grey, the answer a campaign with no /// description gets, and the frame's way of saying the tag was never declared — the reader /// deciding whether the next ticket belongs in it is exactly who needs to know that. /// /// A tag declared with nothing said about it draws the same placeholder as one that was /// never declared. The two are told apart where the difference is actionable, in the /// picker's two sections; here they have the same nothing to show. fn tag_prose(tag: &TagRow) -> Text<'static> { let annotation = tag.annotation.as_deref().unwrap_or_default(); match annotation.is_empty() { true => Text::from(Line::from(Span::styled( NO_ANNOTATION, Style::default().fg(Color::Grey.into()), ))), false => Text::from(annotation.to_string()), } } /// What the no-campaign view is, as its frame says it. /// /// The title names the filter and this says what the columns under it are, which a tag's /// annotation and a campaign's description answer for their own frames. No file holds words /// for an absence, so the sentence is the board's own — grey like the title, being the same /// fact about the same unset field rather than prose anyone wrote. fn no_campaign_prose() -> Text<'static> { Text::from(Line::from(Span::styled( "Tickets that name no campaign.", Style::default().fg(Color::Grey.into()), ))) } /// The tag frame's title: `#tag`, in the colour a card draws it in, cut to the border. /// /// The hash is what a card and `labels_line` already put in front of a tag, and it earns its /// cell here for the reason it earns one there: the frame is a slot a campaign can be in /// too, and `~v1` against `#bug` is what says at a glance which filter emptied the columns. /// The colour is `tag_color`, a pure function of the word, so the frame, the picker row and /// every card agree without anything being stored. /// /// Bare otherwise: no id, because a tag has none — it *is* its name, which is what /// `ls --tag` matches whole — and nothing after it, because there is no longer name it is /// shorthand for. Cut by hand like `campaign_title` and `detail_title`, since ratatui /// truncates a block title at whatever cell it reaches. fn tag_title(tag: &str, frame_width: u16) -> Vec> { let room = frame_width.saturating_sub(2) as usize; // The hash and the space either side of it are part of what has to fit, so they are // 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. let whole = format!(" #{tag} "); let text = match whole.chars().count() <= room { true => whole, false => match room.checked_sub(3).filter(|keep| *keep > 0) { Some(keep) => format!(" #{} ", with_ellipsis(tag, keep)), None => String::new(), }, }; vec![Span::styled( text, Style::default().fg(tag_color(tag).into()), )] } /// 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())), ] } /// The no-campaign frame's title: the words, and nothing else. /// /// No id — there is no thing on the board to address — and no mark, which keeps `~` meaning /// a campaign and `#` meaning a tag. Grey, because this view is the Campaign field's unset /// state drawn out, and grey is what the palette gives `_Not set_`: the border around it says /// where the reader is, the words say what they are looking at. Cut by hand like /// [`tag_title`] and [`campaign_title`], since ratatui truncates a block title at whatever /// cell it reaches. fn no_campaign_title(frame_width: u16) -> Vec> { let room = frame_width.saturating_sub(2) as usize; let whole = format!(" {NO_CAMPAIGN_ROW} "); let text = match whole.chars().count() <= room { true => whole, false => match room.checked_sub(3).filter(|keep| *keep > 0) { Some(keep) => format!(" {} ", with_ellipsis(NO_CAMPAIGN_ROW, keep)), None => String::new(), }, }; vec![Span::styled(text, Style::default().fg(Color::Grey.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()); // Whether a card can be picked out at all. While the frame above holds the selection no // card is selected, so none is drawn reversed — that highlight is what `y` and `enter` // act on, and one left up there would be pointing at a ticket neither key would touch. // The focused column keeps its cyan border regardless, because it is where `↓` comes // back to, and that is the one thing about the columns still worth saying. let on_cards = board.current().focus == Focus::Cards; 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 && on_cards && 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 { screen_rows(Rect::new(0, 0, screen.width, screen.height), chrome)[BOARD_ROW] } /// The rows of the campaign frame that hold prose: inside its border. /// /// Through `screen_rows` rather than by arithmetic on [`Chrome::FRAME_PROSE_ROWS`], for /// the reason `board_area` is: geometry reproduced by hand is geometry that comes to /// disagree with the draw. What `scroll_frame` measures its step and its clamp against, /// which is why it takes the screen — the same relationship `column_text_height` has with /// `draw_columns`. Zero-height with no campaign selected, which is why `scroll_frame` asks /// for one before it measures. fn frame_text_area(screen: Size, chrome: Chrome) -> Rect { screen_rows(Rect::new(0, 0, screen.width, screen.height), chrome)[FRAME_ROW] .inner(Margin::new(1, 1)) } /// 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, vec![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); } // Comments then criteria, and the comment count goes first when the column is too // narrow for both: how far along a ticket is outranks whether anybody has said // something about it. Nothing at all when the count is zero, not a zero and not a // blank, so an uncommented card is the row it has always been. let mut right = Vec::new(); if ticket.comments > 0 { // The one coloured thing on the row, where the owner and the criteria count are // grey: a count that has just appeared is the row's news, and the mark is what // says which kind of count it is. right.push(Span::styled( format!("{}{}", ticket.comments, COMMENT_MARK), Style::default().fg(Color::Cyan.into()), )); } if let Some(progress) = ticket.criteria { right.push(Span::styled( format!("[{}/{}]", progress.met, progress.total), Style::default().fg(Color::Grey.into()), )); } lines.push(corner_line( vec![Span::styled( ticket.owner.clone(), Style::default().fg(Color::Grey.into()), )], right, 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) -> Span<'static> { let colour = match is_unknown_value(due) { true => Color::Grey, false => Color::Cyan, }; 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. /// /// An item of `right` 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. /// /// `right` is a group, single-spaced, and it gives up its items **from the front**. The /// item nearest the edge is the one the corner is about and the ones to its left are what /// has been added beside it, so a narrow column loses the additions and keeps the answer: /// the bottom row drops its comment count before its criteria count. One space is /// separator enough, and the spacing lives here rather than in a caller for the reason the /// gap does, that geometry reproduced by hand drifts from the draw. fn corner_line(left: Vec>, right: Vec>, width: u16) -> Line<'static> { let mut spans = left; let used = spans_width(&spans); // One space minimum between the corners, so they never touch, and one between each // pair of items in the group. No room for even the last item and the right corner // goes entirely rather than the line growing past the column. let mut kept = 0; let gap = loop { let group = &right[kept..]; if group.is_empty() { return Line::from(spans); } let wanted = spans_width(group) + group.len() - 1; match (width as usize).checked_sub(used + wanted + 1) { Some(gap) => break gap, None => kept += 1, } }; spans.push(Span::raw(" ".repeat(gap + 1))); for (index, span) in right.into_iter().skip(kept).enumerate() { if index > 0 { spans.push(Span::raw(" ")); } spans.push(span); } 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 } /// The gap between two hints on a row of keys. const KEY_GAP: &str = " "; /// One key hint: the key, and what pressing it does. /// /// Two spans either way, the key and the rest of it. The key is cyan and bold and the /// description takes the terminal's default foreground, which is the row frig and pantop /// draw with the same division — one accent colour per tool, cyan here and magenta there. /// The row as a whole is still chrome, but a key nobody can pick out of it is chrome that /// has to be read word by word to be used. /// /// **The key is merged into the description when it is the description's first letter**, so /// `quit` is drawn with a cyan `q` and nothing in front of it while `y copy id` keeps both /// halves. Two cells back on a row already at its width naming eight keys, and the letter /// on screen is the key either way. The prefix test is case sensitive for that reason: a /// board naming both `r` and `R` would draw one word for the two of them otherwise, and the /// merged form can only say which key it is while the letter it colours *is* that key. fn key_hint(key: &str, description: &str) -> [Span<'static>; 2] { let rest = match description.strip_prefix(key) { Some(rest) => rest.to_string(), None => format!(" {description}"), }; [ Span::styled( key.to_string(), Style::default() .fg(Color::Cyan.into()) .add_modifier(Modifier::BOLD), ), Span::raw(rest), ] } /// A run of hints, gap separated, closed by the space every row ends on. /// /// The opening space is the caller's: the footer starts on one, and the prompt and the /// picker's query row put what was typed there instead. fn key_hints(hints: &[(&str, &str)]) -> Vec> { let mut spans = Vec::new(); for (key, description) in hints { if !spans.is_empty() { spans.push(Span::raw(KEY_GAP)); } spans.extend(key_hint(key, description)); } spans.push(Span::raw(" ")); spans } fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { // The command prompt takes the whole row on the same terms as the search prompt below, // and is asked first: an input cannot be covered, and it is the newest of the three // things that can hold the row. Only one of the two prompts can be open at a time. if let Some(prompt) = &board.prompt { draw_prompt(frame, prompt, area); return; } // 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 let Some(picker) = &board.picker { draw_picker_row(frame, picker, 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. // // Only the notice the row can hold, which is `Board::notice_on_row` rather than a // condition written here: `draw` asks the same question to decide whether to put the // box up, and two spellings of it would draw the message twice or not at all. if board.notice_on_row() && let Some(notice) = &board.notice { draw_notice(frame, notice, area); return; } // The next press names itself here, whichever state the rotation is in, and the // column it would reveal keeps its count until it is drawn. That is the board's // version of the summary line `ls` prints above a listing that leaves the terminal // statuses out. let d = match board.visibility.next_reveal() { Some(status) => format!("show {} ({})", status, column_count(board, status)), None => "hide both".to_string(), }; // 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 filter on the honest answer // is `ctrl-c`, the only key left that quits in one press. Going on drawing the merged // `quit` there would be the fault 1b78a24 was, a footer describing a key by what it // used to do — and with a filter on, the frame names what that press actually does // instead. Split either way once the key is `ctrl-c`, which is no word's first letter. let quit = match board.detail.is_some() || !board.current().filter.is_whole() { true => ("ctrl-c", "quit"), false => ("q", "quit"), }; // `c` and `t` are named where a reader has to find them: on the board, with nothing // filtered. With either filter on the slot is spent on nothing, because the frame above // the columns names what the board is filtered to and says `q board` on its own border — // so the row is not at its width naming nine keys to repeat what is already on screen. // The tag used to be drawn here for want of a frame to draw it in, which is the one // thing 2a83bd4 took away. let filter: &[(&str, &str)] = match board.current().filter { Filter::Whole => &[("c", "campaign"), ("t", "tag")], _ => &[], }; // Which way `↵` will go, since the key is a toggle and the frame is already at one of // its two heights. Naming it `expand` while it collapses would be the fault 1b78a24 // was, a footer describing a key by what it used to do. let height = match board.current().expanded { true => "collapse", false => "expand", }; // What `y` copies where the selection is. A tag is its own id, so naming it one would // send the reader looking for seven characters on a border that prints a word. Nothing // on the no-campaign frame, which has neither — the key is left out of its footer // rather than named into a notice. let copied = match board.current().filter { Filter::Tag(_) => Some("copy tag"), Filter::NoCampaign => None, Filter::Whole | Filter::Campaign(_) => Some("copy id"), }; let mut hints: Vec<(&str, &str)> = Vec::new(); // Only when there is a tab to move to, since the footer names keys that work. if board.tabbed() { hints.push(("tab", "project")); } // Three states, because the frame is a third place the selection can be and the row // must describe the keys that work where it is. An open ticket wins over both, which is // what owning `pgup` and `pgdn` means. // // On the frame, `↓` is the way back to the cards and the two scroll keys are the // frame's; `y` is named because it still copies what the frame names. `↵` and `←→` // are left out because they do nothing there. Incomplete rather than wrong, the trade // this row is allowed to make — what it must never do is name a key by what it used to // do. `↑ frame` is not named on the board for the same reason `c` is dropped from a // filtered board: the frame is drawn right above the columns and up is the key that // reaches it, and the row has no cells to spend saying so. match (board.detail.is_some(), board.current().focus) { (true, _) => hints.extend([ ("←→↑↓", "select"), ("pgup/pgdn", "scroll"), ("/", "search"), (":", "command"), ("y", "copy id"), ("↵/q", "close"), ]), (false, Focus::Frame) => { hints.extend([ ("↓", "board"), ("↵", height), ("pgup/pgdn", "scroll"), ("/", "search"), (":", "command"), ]); if let Some(copied) = copied { hints.push(("y", copied)); } } (false, Focus::Cards) => { hints.extend([ ("←→", "column"), ("↑↓", "card"), ("/", "search"), (":", "command"), ]); hints.extend_from_slice(filter); hints.extend([("y", "copy id"), ("↵", "detail")]); } } hints.push(("d", d.as_str())); hints.push(quit); // The leading space is the row's own, the way every other row of the board opens on // one; `key_hints` closes it. let mut spans = vec![Span::raw(" ")]; spans.extend(key_hints(&hints)); frame.render_widget(Paragraph::new(Line::from(spans)), 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. /// /// The two keys are drawn the way every other row draws them, cyan on the key and the /// default foreground on the word, so they are findable on a row whose other half is an /// input. That the query sits in the same foreground as the descriptions is what the /// house style costs here, and the cursor is what says which of the two is being typed /// into — which it does in a terminal with no colour at all. A miss stays brightred /// beside the query it is about, being the one thing on the row that is neither a key nor /// what was typed. 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::raw(KEY_GAP)); spans.extend(key_hints(&[("↵", "jump"), ("esc", "cancel")])); 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)); } /// What the row spends on the command prompt before the line starts: its own opening space /// and the key that opened it, drawn where a search draws its `/`. const PROMPT_OPENING: &str = " :"; /// The command prompt, in place of the key list, and the line windowed to what is left of /// the row. /// /// The keys are drawn the way `draw_search` draws its two, and their width is taken off the /// row *before* the line is windowed, so they keep their place rather than being pushed off /// the end by a long command. A message takes the row from them instead: the reader has /// just been told something and that is the thing to read, while `esc` and `enter` still do /// what they did. It is brightred beside the line it is about, the one thing on the row /// that is neither a key nor what was typed, which is where `no match` sits. /// /// `run` and not `check`: enter hands the line to the same handler the shell reaches, and /// the row has to say which of the two it is about to do. fn draw_prompt(frame: &mut Frame, prompt: &Prompt, area: Rect) { let keys = key_hints(&[("↵", "run"), ("esc", "cancel")]); let spent: usize = PROMPT_OPENING.chars().count() + KEY_GAP.chars().count() + keys .iter() .map(|span| span.content.chars().count()) .sum::(); // At least one cell, so a terminal too narrow for the keys still draws a cursor to type // at rather than nothing at all. let room = (area.width as usize).saturating_sub(spent).max(1); let (visible, at) = prompt_window(&prompt.line, prompt.cursor, room); let mut spans = vec![Span::raw(format!("{PROMPT_OPENING}{visible}"))]; match &prompt.refused { Some(message) => spans.push(Span::styled( format!("{KEY_GAP}{message}"), Style::default().fg(Color::BrightRed.into()), )), None => { spans.push(Span::raw(KEY_GAP)); spans.extend(keys); } } frame.render_widget(Paragraph::new(Line::from(spans)), area); // Held on the row, the way the search prompt holds its own: a line longer than the // terminal leaves the cursor on the last cell rather than off the frame. let column = (PROMPT_OPENING.chars().count() + at) as u16; frame.set_cursor_position((area.x + column.min(area.width.saturating_sub(1)), area.y)); } /// The part of `line` a field `room` cells wide shows with the cursor at `cursor`, and the /// column the cursor lands on inside it. /// /// The window is anchored on the cursor's right edge, so a line longer than the row scrolls /// as it is typed instead of being cut off at the end of the field, and scrolls back as the /// cursor moves left. What it costs is the text *after* the cursor on a long line, which is /// off the window until the cursor reaches it. A window that kept both ends needs a scroll /// offset held in state, and the draw is where the width is known and the state is not /// writable, so that offset would have to be maintained by every key that moves the cursor /// against a width the keypress cannot see. /// /// Counted in characters, which is what the rest of this row is measured in. The cursor is /// counted rather than sliced, so an offset that is somehow not on a character boundary /// gives a window rather than a panic on the board. fn prompt_window(line: &str, cursor: usize, room: usize) -> (String, usize) { let before = line .char_indices() .take_while(|(offset, _)| *offset < cursor) .count(); // One cell of the field is the cursor's own, so a line whose head fills the row keeps // the cursor on it rather than one cell past its end. let start = before.saturating_sub(room.saturating_sub(1)); let visible = line.chars().skip(start).take(room).collect(); (visible, before - start) } /// The picker's footer: its query while one is open, and the keys it answers to otherwise. /// /// The same division `draw_search` makes, and the same reason for it: while every printable /// key is going into a buffer, a list of keys describes nothing that currently works. So `/` /// is named only on the closed query, where it is the key to press, and the query's own row /// names what `esc` does to it rather than what it does to the picker. fn draw_picker_row(frame: &mut Frame, picker: &Picker, area: Rect) { let Some(query) = &picker.query else { let mut spans = vec![Span::raw(" ")]; spans.extend(key_hints(&[ ("↑↓", "select"), ("↵", "view"), ("/", "search"), ("esc", "cancel"), ])); frame.render_widget(Paragraph::new(Line::from(spans)), area); return; }; let prompt = format!(" /{query}"); let mut spans = vec![Span::raw(prompt.clone()), Span::raw(KEY_GAP)]; spans.extend(key_hints(&[("↑↓", "select"), ("↵", "view"), ("esc", "clear")])); frame.render_widget(Paragraph::new(Line::from(spans)), area); // Held on the row, the way the search prompt's cursor is, so a query longer than the // terminal leaves it on the last cell rather than off the frame. let at = (prompt.chars().count() as u16).min(area.width.saturating_sub(1)); frame.set_cursor_position((area.x + at, area.y)); } /// How many tickets are in one status on the tab in view, drawn or not. fn column_count(board: &Board, status: &str) -> usize { board .current() .columns .iter() .find(|column| column.status == status) .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 the rows those two are drawn in. /// /// `rows` is the *drawn* rows, from `picker_list`, and not the campaigns: the sections and /// the truncation line take a row each, and a box measured against the campaigns alone /// would be short by however much chrome the split added. fn picker_overlay(area: Rect, rows: usize) -> Rect { let width = area .width .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 rows = picker_list(tab, picker); let overlay = picker_overlay(area, rows.len()); let text = overlay.inner(Margin::new(1, 1)); let lines: Vec = rows .iter() .enumerate() .map(|(at, row)| picker_row_line(row, at == picker.row, text.width)) .collect(); let block = Block::default() .borders(Borders::ALL) .border_style(Style::default().fg(Color::Cyan.into())) .title(Span::styled( picker_title(tab, picker), Style::default().fg(Color::Orange.into()), )); // Followed on the geometry this frame is drawing, not the one the keypress // measured. Opening aligns against the screen the dispatch hands it, but a resize // between that keypress and here shrinks the window under an offset sized to the // old one, and a tick puts the highlight back by key without touching the scroll at // all. The stored value is left alone, the way a column's is: what is drawn is // corrected immediately and the next navigation writes the correction back. The cap // against blank space past the last row falls out of the same call. // Followed on the geometry this frame is drawing, not the one the keypress // measured. Opening aligns against the screen the dispatch hands it, but a resize // between that keypress and here shrinks the window under an offset sized to the // old one, and a tick puts the highlight back by key without touching the scroll at // all. The stored value is left alone, the way a column's is: what is drawn is // corrected immediately and the next navigation writes the correction back. The cap // against blank space past the last row falls out of the same call. let offset = aligned_offset( picker.offset, picker.row as u16, picker.row as u16 + 1, text.height, lines.len() as u16, ); frame.render_widget(Clear, overlay); frame.render_widget(Paragraph::new(lines).block(block).scroll((offset, 0)), overlay); } /// The picker's own title: how many campaigns the board has, and how many a query left. /// /// The bare count while nothing is typed, because that is what the box is. A query that /// cuts the list down makes the total alone a lie about what is on screen, so it says both /// — and the reader can see at a glance whether the query is narrow enough. fn picker_title(tab: &Tab, picker: &Picker) -> String { let query = picker.query.as_deref().unwrap_or_default(); let (what, total, found) = match picker.kind { PickerKind::Campaign => ( "campaigns", tab.campaigns.len(), tab.campaigns .iter() .filter(|campaign| picker_matches(campaign, query)) .count(), ), PickerKind::Tag => ( "tags", tab.tags.len(), tab.tags.iter().filter(|tag| tag_matches(tag, query)).count(), ), }; if query.trim().is_empty() { return format!(" {what} ({total}) "); } format!(" {what} ({found} of {total}) ") } /// One drawn row: a campaign, a section heading, the truncation line, or the miss. /// /// The chrome is never highlighted, because the highlight only ever sits on a campaign. /// A heading is bold with its grey so it is not read as the summary of the row above it, /// and `no match` is brightred where the search prompt's is, since grey is exactly what a /// reader skips and this is the one row that has to be read. fn picker_row_line(row: &PickerRow, selected: bool, width: u16) -> Line<'static> { let grey = Style::default().fg(Color::Grey.into()); match row { PickerRow::Campaign(campaign) => picker_line(campaign, selected, width), PickerRow::Tag(tag) => tag_picker_line(tag, selected, width), PickerRow::NoCampaign(count) => no_campaign_line(*count, selected), PickerRow::Heading(name) => { Line::from(Span::styled((*name).to_string(), grey.add_modifier(Modifier::BOLD))) } PickerRow::Hidden(count) => Line::from(Span::styled(hidden_line(*count), grey)), PickerRow::Missed => Line::from(Span::styled( "no match".to_string(), Style::default().fg(Color::BrightRed.into()), )), } } /// The truncation line: how many completed campaigns are being kept back, and that they /// are the older ones. /// /// Named rather than merely counted. `… 3` beside a list says nothing about what the three /// are, and the whole reason to draw the line is that the rows it stands for are not there /// to be read. fn hidden_line(count: usize) -> String { let campaigns = match count { 1 => "campaign", _ => "campaigns", }; format!("… {count} older completed {campaigns} hidden") } /// One tag row: `bug 23 What the tag means`. /// /// The tag in its own colour and nothing else, which is how a card draws it: the mark and /// the bold belong to a campaign label, and this list holds no campaigns to be told apart /// from. `tag_color` is a pure function of the word, so the row and the card agree without /// anything being stored. /// /// The count is what the row is chosen on as much as the name: it says what picking this /// will give, and a declared tag at zero says the board is about to go empty before the /// reader presses anything. Grey, because it is context around the word being chosen. /// /// The annotation takes what is left and gives way first, the trade `picker_line` makes /// with a description: half a sentence still says what a tag is for. fn tag_picker_line(tag: &TagRow, selected: bool, width: u16) -> Line<'static> { let emphasis = match selected { true => Modifier::REVERSED, false => Modifier::empty(), }; let grey = Style::default().fg(Color::Grey.into()).add_modifier(emphasis); let mut spans = vec![ Span::styled( tag.name.clone(), Style::default() .fg(tag_color(&tag.name).into()) .add_modifier(emphasis), ), Span::raw(" "), Span::styled(tag.count.to_string(), grey), ]; let used = spans_width(&spans); let summary = tag.summary(); if !summary.is_empty() && 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, grey)); } Line::from(spans) } /// The no-campaign row: `no campaign 12`. /// /// Words where a campaign carries an id, because that is what the filter is: not a thing on /// the board but the absence of one, with nothing to mark and nothing to shorten. Grey, for /// the same reason the frame's title is — the Campaign field of everything this view holds is /// unset, and grey is what the palette gives `_Not set_`. /// /// The count is what the row is chosen on as much as its name, the trade `tag_picker_line` /// makes: it says what picking this will give, including zero, so an empty board is seen /// coming before the reader presses anything. fn no_campaign_line(count: usize, selected: bool) -> Line<'static> { let emphasis = match selected { true => Modifier::REVERSED, false => Modifier::empty(), }; let grey = Style::default().fg(Color::Grey.into()).add_modifier(emphasis); Line::from(vec![ Span::styled(NO_CAMPAIGN_ROW.to_string(), grey), Span::raw(" "), Span::styled(count.to_string(), grey), ]) } /// One picker row: `(1b78a24) ~beaver What the campaign is for 0/1`. /// /// 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. The /// standing trails it, grey like a card's criteria count, so how far each campaign has got /// is on the list rather than only on the frame. 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), )); } // The standing, `2/3`, is what the reader picks a campaign by, so it is reserved // before the prose is cut, the way a corner is: half a count reads as the wrong // number, so the whole of it drops when the row will not hold it. A campaign with no // members shows nothing, the way a card with no criteria spends no corner on it. let used_base = spans_width(&spans); let standing = match campaign.standing.total { 0 => None, _ => { let text = format!("{}/{}", campaign.standing.done, campaign.standing.total); let room = (width as usize).saturating_sub(used_base + 2); if text.chars().count() <= room { Some(text) } else { None } } }; let standing_w = standing.as_ref().map_or(0, |text| text.chars().count() + 2); // 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 = used_base + standing_w; let summary = match campaign.summary().is_empty() { true => campaign.title.as_str(), false => campaign.summary(), }; 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), )); } if let Some(text) = standing { spans.push(Span::raw(" ")); spans.push(Span::styled( text, 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) } /// How tall the whole overlay is, section by section. /// /// Each section wraps at its own width — a quote's body shares its row with the gutter — /// and the total is what the clamp and the indicator are derived from. One measurement /// per section by the same [`wrapped_height`], so the draw and the scroll cannot /// disagree about where any of them ends. fn detail_height(sections: &[DetailSection], width: u16) -> u16 { sections .iter() .map(|section| wrapped_height(section.text(), section.width(width))) .fold(0u16, |total, height| total.saturating_add(height)) } /// The furthest the overlay scrolls: every section's wrapped height less the viewport. fn detail_last_offset(sections: &[DetailSection], text: Rect) -> u16 { detail_height(sections, 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. /// /// Shared by the detail overlay and the campaign frame, which is why the width is the /// border's and not one view's: a reader who learns what `pg 2/3` means on a ticket reads /// it the same way above the columns. It says only whether the indicator fits the border at /// all; a caller with something else on that border checks against that itself, which the /// frame does and the overlay has no need to. fn page_indicator(offset: u16, last: u16, height: u16, border_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. match indicator.chars().count() <= border_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 = detail_last_offset(&detail.sections, text); 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(block, overlay); // The sections stack into one scroll: `top` walks the virtual rows, each section is // clipped to what the viewport still holds, and one straddling the top is scrolled // within itself by however much of it is above. The bar of a quote rides in its own // column, so scrolling never has to move it. let mut top: u16 = 0; for section in &detail.sections { let height = wrapped_height(section.text(), section.width(text.width)); let bottom = top.saturating_add(height); let visible = bottom > offset && top < offset.saturating_add(text.height); if visible { let within = offset.saturating_sub(top); let y = text.y + top.max(offset) - offset; let clip = Rect { x: text.x, y, width: text.width, height: text.bottom().saturating_sub(y), }; match section { DetailSection::Flow(body) => frame.render_widget( Paragraph::new(body.clone()) .wrap(Wrap { trim: false }) .scroll((within, 0)), clip, ), DetailSection::Quote(body) => { let [bars, prose] = Layout::horizontal([Constraint::Length(GUTTER_WIDTH), Constraint::Min(0)]) .areas(clip); frame.render_widget(gutter_bars(clip.height), bars); frame.render_widget( Paragraph::new(body.clone()) .wrap(Wrap { trim: false }) .scroll((within, 0)), prose, ); } } } top = bottom; if top >= offset.saturating_add(text.height) { break; } } } /// The gutter beside a quoted run: the bar repeated down every row the run occupies. /// /// Geometry rather than text, which is the whole point — a comment's prose wraps inside /// the body column and cannot take the mark off any row, paragraph breaks included. /// Grey, as chrome; [`QUOTE_BAR`] for the same reason the CLI prefixes with it, so both /// renderers draw one glyph. fn gutter_bars(height: u16) -> Text<'static> { let bar = Span::styled(format!("{QUOTE_BAR} "), Style::default().fg(Color::Grey.into())); Text::from(vec![Line::from(bar); height as usize]) } /// 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` and holds the four status directories. /// `board_dir()` deliberately does not create the campaigns directory beside them, so /// every test that does not write one is also the test that a board with no campaigns /// draws. /// /// A [`Fixture`], so it goes when the test that made it does, whether the test passed or /// not. It used to be a `PathBuf` and a `remove_dir_all` at the end of the tests that /// remembered one, which is b74dc5a: the line does not run when an assertion fails, and /// most tests here never had it. fn board_dir() -> Fixture { let dir = Fixture::new("worklane-tui"); 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, frame: None }; /// 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 overlay's text rows, cut out of the drawn screen by the layout's own /// geometry, right-trimmed so an assertion reads what is on it rather than its /// padding. fn overlay_text_rows(lines: &[String], width: u16, height: u16) -> Vec { let text = detail_text_area(Rect::new(0, 0, width, height)); lines[text.y as usize..(text.y + text.height) as usize] .iter() .map(|row| { row.chars() .skip(text.x as usize) .take(text.width as usize) .collect::() .trim_end() .to_string() }) .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 campaign frame's rows, cut out of the drawn buffer by its own geometry. /// /// Through `screen_rows` for the reason `headings` goes through the layout: the frame sits /// a row lower when a tab row is drawn above it, and it grew from three rows to five when /// its prose became scrollable. A test counting rows by hand goes on measuring whichever /// rows used to be the frame. fn frame_lines(board: &Board, width: u16, height: u16) -> Vec { let area = screen_rows(Rect::new(0, 0, width, height), board.chrome())[FRAME_ROW]; let lines = render(board, width, height); lines[area.y as usize..(area.y + area.height) as usize].to_vec() } /// 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 cells of the footer row, as symbol, colour and modifier. /// /// The row is the only place on the board where what a thing *is* is carried by its /// colour alone: the key merged into its description is one letter of a word, so the /// flattened row cannot say whether `quit` is a key or the tail of `ctrl-c quit`. fn footer_cells( board: &Board, width: u16, height: u16, ) -> Vec<(String, ratatui::style::Color, Modifier)> { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); let row = buffer.area.height - 1; (0..buffer.area.width) .map(|x| { let cell = &buffer[(x, row)]; (cell.symbol().to_string(), cell.fg, cell.modifier) }) .collect() } /// Where `text` starts on the footer, in cells. fn footer_at(cells: &[(String, ratatui::style::Color, Modifier)], text: &str) -> Option { let wanted: Vec = text.chars().map(|c| c.to_string()).collect(); (0..=cells.len().saturating_sub(wanted.len())).find(|&at| { cells[at..at + wanted.len()] .iter() .zip(&wanted) .all(|((symbol, ..), c)| symbol == c) }) } /// How many cells the first `text` on the footer opens with in the key colour, and /// `None` when the row does not hold it at all. /// /// One number answers both forms the row draws. Merged, `quit` is `Some(1)`: the `q` /// alone is a key and the rest of the word is description. Split, `ctrl-c quit` is /// `Some(6)`, and asking about `quit` on that row is `Some(0)` — the word is there and /// no part of it is a key. The flattened row cannot tell those two apart, since the /// split form contains the merged one, and which key quits from where is exactly what /// the tests below are about. fn keys_on(board: &Board, width: u16, height: u16, text: &str) -> Option { let cells = footer_cells(board, width, height); let at = footer_at(&cells, text)?; let key: ratatui::style::Color = Color::Cyan.into(); Some( cells[at..at + text.chars().count()] .iter() .take_while(|(_, colour, _)| *colour == key) .count(), ) } /// The colour and modifier the first cell of `text` reached the screen in. fn footer_style( board: &Board, width: u16, height: u16, text: &str, ) -> (ratatui::style::Color, Modifier) { let cells = footer_cells(board, width, height); let at = footer_at(&cells, text).unwrap_or_else(|| panic!("no `{text}` on the footer")); let (_, colour, modifier) = cells[at].clone(); (colour, modifier) } /// 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_every_status_as_a_column_once_both_are_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", ""); write_ticket(&dir, DISCARDED, "55555555-0000-4000-8000-000000000000", "Gone one", ""); let mut board = one_board(&dir); board.rotate_visibility(SCREEN); board.rotate_visibility(SCREEN); let row = headings(&board, 140, 20); for heading in [ "backlog (1)", "committed (1)", "reviewing (0)", "done (0)", "discarded (1)", ] { assert!(row.contains(heading), "no {heading:?} in:\n{row}"); } } /// The terminal columns only grow, and they are the ones least often read. `ls` /// already leaves them out of its listing while counting them in the summary; the /// first state of the rotation is the same opinion. #[test] fn the_board_opens_with_the_terminal_columns_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", ""); write_ticket(&dir, DISCARDED, "55555555-0000-4000-8000-000000000000", "Dropped one", ""); let board = one_board(&dir); assert_eq!(board.visibility, Visibility::Neither, "a column 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}"); assert!(!row.contains("discarded"), "discarded is still a column:\n{row}"); // Hidden, not unread: the counts are right and revealing either needs no rescan. assert_eq!(board.current().columns.len(), Status::ALL.len()); assert_eq!(board.visible().len(), 3); assert_eq!(column_count(&board, DONE), 1); assert_eq!(column_count(&board, DISCARDED), 1); let screen = render(&board, 120, 20).join("\n"); assert!(!screen.contains("Finished one"), "a hidden done ticket was drawn"); assert!(!screen.contains("Dropped one"), "a hidden discarded ticket was drawn"); } /// The rotation itself, one press at a time: hide both, show done, show both, and /// back to hidden. Done first because it is the more likely thing to be looking /// for; discarded last because it is the least. #[test] fn d_rotates_hidden_then_done_then_both_and_back_to_hidden() { let dir = board_dir(); write_ticket(&dir, "reviewing", "33333333-0000-4000-8000-000000000000", "Ready", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); write_ticket(&dir, DISCARDED, "55555555-0000-4000-8000-000000000000", "Dropped", ""); let mut board = one_board(&dir); board.rotate_visibility(SCREEN); assert_eq!(board.visibility, Visibility::Done); assert_eq!(board.visible().len(), 4); assert!(headings(&board, 120, 20).contains("done (1)"), "done was not drawn"); assert!( !render(&board, 140, 20).join("\n").contains("Dropped"), "discarded came with done" ); board.rotate_visibility(SCREEN); assert_eq!(board.visibility, Visibility::Both); assert_eq!(board.visible().len(), Status::ALL.len()); let row = headings(&board, 140, 20); assert!(row.contains("discarded (1)"), "{row}"); board.rotate_visibility(SCREEN); assert_eq!(board.visibility, Visibility::Neither); assert_eq!(board.visible().len(), 3); assert!( !render(&board, 140, 20).join("\n").contains("Finished"), "done stayed drawn after the wrap" ); } /// 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.rotate_visibility(SCREEN); let shown = headings(&board, 120, 20); assert_eq!(shown.matches('┌').count(), 4, "{shown}"); assert!(shown.ends_with('┐'), "{shown}"); board.rotate_visibility(SCREEN); let both = headings(&board, 140, 20); assert_eq!(both.matches('┌').count(), 5, "{both}"); assert!(both.ends_with('┐'), "{both}"); } /// Hiding is a prefix of the columns, which only holds while done and discarded are /// the last two of what the board draws. The board leans on that, so the assumption /// is pinned rather than assumed. Discarded being last overall is the other decided /// order: the stamp arrival rule truncates by `Status::ALL`, so discarded after done /// is what lets a discard keep the journey the ticket made. #[test] fn the_terminal_columns_are_last_in_the_order_drawn() { let last: Vec<&str> = Status::ALL.iter().map(|status| status.as_str()).collect(); assert_eq!(&last[last.len() - 2..], &[DONE, DISCARDED]); assert_eq!(status_dirs().last(), Some(&DISCARDED)); } /// Each state names what the next press does, and a column still hidden keeps its /// count until it is drawn. #[test] fn the_footer_names_the_next_press_of_d_and_carries_the_hidden_count() { let dir = board_dir(); for (n, title) in [("44444444", "One"), ("55555555", "Two")] { write_ticket(&dir, "done", &format!("{n}-0000-4000-8000-000000000000"), title, ""); } write_ticket(&dir, DISCARDED, "66666666-0000-4000-8000-000000000000", "Three", ""); let mut board = one_board(&dir); // Hidden: the next press reveals done, whose count is carried here. let neither = footer(&board, 120, 20); assert!(neither.contains("d show done (2)"), "{neither}"); board.rotate_visibility(SCREEN); // Done shown: the next press reveals discarded, whose count is carried here. let done = footer(&board, 120, 20); assert!(done.contains("d show discarded (1)"), "{done}"); board.rotate_visibility(SCREEN); // Both shown: their own headings carry the counts, so nothing is printed twice. let both = footer(&board, 140, 20); assert!(both.contains("d hide both"), "{both}"); assert!(!both.contains("(2)"), "the count is printed twice:\n{both}"); assert!(!both.contains("(1)"), "the count is printed twice:\n{both}"); // And around again. board.rotate_visibility(SCREEN); assert_eq!(board.visibility, Visibility::Neither, "the rotation did not wrap"); } /// 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. /// Reaching hidden from both shown takes the rest of the rotation. #[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.rotate_visibility(SCREEN); board.select_column(3, SCREEN); assert_eq!(selected_title(&board), Some("Finished".to_string())); // Through both, where done stays drawn and the selection stays put... board.rotate_visibility(SCREEN); assert_eq!(selected_title(&board), Some("Finished".to_string())); // ...and back to hidden, where the selection has to move. board.rotate_visibility(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.rotate_visibility(SCREEN); board.select_column(3, SCREEN); board.toggle_detail(); assert!(board.detail.is_some()); board.rotate_visibility(SCREEN); assert!(board.detail.is_some(), "the detail closed while done was still drawn"); board.rotate_visibility(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.rotate_visibility(SCREEN); board.rotate_visibility(SCREEN); board.rotate_visibility(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.rotate_visibility(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.rotate_visibility(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 ticket `write_card`, `write_tagged_card` and `write_member_card` all write. /// /// A const rather than a literal in each, now that a test has to name it from outside /// them: the history of a ticket lives in a directory named by its uuid, so a fixture /// that wrote a different one would silently count nothing. const FIXTURE_UUID: &str = "11111111-0000-4000-8000-000000000000"; /// Comments where `comment` puts them: under the board, in a directory named by the /// ticket's uuid, one `.md` per entry. The fixture uuid, since that is what /// `write_card` writes into the ID field the counter reads. fn write_comments(dir: &Path, count: usize) { let history = crate::history::history_dir(dir, FIXTURE_UUID); std::fs::create_dir_all(&history).unwrap(); for n in 0..count { std::fs::write( history.join(format!("20260823_1200{n:02}_000000_comment.md")), format!("**Comment**\n\n**Author**: alice\n**Time**: 2026-08-23 12:00:{n:02}\n\nSaid {n}.\n"), ) .unwrap(); } } /// 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 = FIXTURE_UUID; 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 = FIXTURE_UUID; 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:?}"); } /// The bottom corner answers two questions now, and in this order: the comment count /// sits left of the criteria count with one space between them. Left, because the /// criteria count is what the corner has always been about and this is what has been /// added beside it. #[test] fn a_card_with_comments_draws_the_count_before_the_criteria_count() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two"); write_comments(&dir, 2); let rows = only_card_at(&dir, 40); assert_eq!( rows[2], format!("alice{}2{COMMENT_MARK} [1/2]", " ".repeat(27)), "{rows:?}" ); } /// A ticket nobody has commented on draws the row it always did, down to the spacing: /// no count, no mark, and no cell held open for one. `[0/0]` says less than saying /// nothing, and so does `0` with a mark after it. #[test] fn a_card_with_no_comments_spends_nothing_on_the_corner() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two"); let rows = only_card_at(&dir, 40); assert_eq!(rows[2], format!("alice{}[1/2]", " ".repeat(30)), "{rows:?}"); assert!(!rows[2].contains(COMMENT_MARK), "{rows:?}"); } /// Cyan, and the only coloured thing on a row whose owner and criteria count are both /// grey. The mark is what says which kind of count the number is, and the colour is /// what stops two counts side by side reading as one number in brackets and another /// that lost its brackets. #[test] fn the_comment_count_is_cyan_where_the_criteria_count_is_grey() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two"); write_comments(&dir, 3); assert_eq!( card_colour(&dir, 120, &format!("3{COMMENT_MARK}")), Some(Color::Cyan.into()), "the comment count is not cyan" ); assert_eq!(card_colour(&dir, 120, "[1/2]"), Some(Color::Grey.into())); } /// A column with room for one of the two keeps the criteria count: how far along a /// ticket is outranks whether anybody has said something about it. Dropped whole, the /// rule the right corner already followed, never as a bare number without its mark. #[test] fn a_column_too_narrow_for_both_counts_keeps_the_criteria_count() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two"); write_comments(&dir, 2); // 14 is exactly `alice`, a space, and both counts single-spaced. 13 is not. assert_eq!(only_card_at(&dir, 14)[2], format!("alice 2{COMMENT_MARK} [1/2]")); let narrow = only_card_at(&dir, 13); assert_eq!(narrow[2], "alice [1/2]", "{narrow:?}"); assert!(!narrow[2].contains(COMMENT_MARK), "{narrow:?}"); } /// The count comes off the pass that collected the items, so a draw asks the /// filesystem nothing. Proved by taking the directory away after the board is built: /// a card that counted per draw would show nothing here. #[test] fn the_count_is_read_when_the_items_are_collected_and_not_per_draw() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two"); write_comments(&dir, 2); let board = one_board(&dir); std::fs::remove_dir_all(crate::history::history_dir(&dir, FIXTURE_UUID)).unwrap(); let card = board.selected().expect("no card"); let rows: Vec = card_lines(card, false, 40) .iter() .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect()) .collect(); assert!(rows[2].contains(&format!("2{COMMENT_MARK}")), "{rows:?}"); } /// The pair for the test above, and the reason that one is not enough on its own: a /// count that never asks the filesystem again would also never change. The digest /// already moves when a comment lands, so the reload is what recounts. #[test] fn a_comment_added_after_the_board_was_built_reaches_the_card_on_reload() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two"); let mut board = one_board(&dir); assert!(!card_rows(&board, "Short", 40)[2].contains(COMMENT_MARK)); write_comments(&dir, 1); board.reload().unwrap(); assert!( card_rows(&board, "Short", 40)[2].contains(&format!("1{COMMENT_MARK}")), "{:?}", card_rows(&board, "Short", 40) ); } /// 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(), Status::ALL.len()); board.rotate_visibility(SCREEN); board.rotate_visibility(SCREEN); let row = headings(&board, 140, 20); for status in Status::ALL { assert!(row.contains(&format!("{} (0)", status.as_str())), "{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(), Status::ALL.len()); board.rotate_visibility(SCREEN); board.rotate_visibility(SCREEN); let row = headings(&board, 140, 20); assert!(row.contains("done (0)"), "{row}"); assert!(row.contains("discarded (0)"), "{row}"); } #[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 history = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&history).unwrap(); std::fs::write( history.join("20260821_120000_000000_comment.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 = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000_comment.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 detail view shows the sequence `show` does, mechanical entries included, so a /// reader on the board sees how a ticket got where it is and not only what was said /// about it. #[test] fn the_detail_view_shows_a_field_change_beside_a_comment() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let history = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&history).unwrap(); std::fs::write( history.join("20260821_120000_000000_status.md"), "**Status**\nbacklog → committed\n\n**Author**: claude\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); std::fs::write( history.join("20260821_120001_000000_comment.md"), "**Comment**\nAnd why.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:01\n", ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); let plain = board.detail.as_ref().expect("no detail").plain(); assert!(plain.contains("HISTORY"), "{plain}"); assert!(plain.contains("status backlog → committed claude ("), "{plain}"); let moved = plain.find("backlog → committed").expect("the move is missing"); let said = plain.find("And why.").expect("the comment is missing"); assert!(moved < said, "the board reordered the log:\n{plain}"); assert!(!plain.contains('\x1b'), "escapes reached the detail view: {plain:?}"); } /// The history block was the last flat part of the overlay, f3e099e: the board /// appended it as a pre-rendered string after the body, so it drew plain under a /// body e4d0bb7 had fully styled. It arrives as cells now, in the colours `show` /// paints. /// /// Paired the way the guideline demands: a renderer that dropped every colour would /// pass the no-escape half, so the presence is asserted beside it. /// /// The spans it looks for are 2733b10's: the label went grey as chrome, the values /// took the meanings they carry in the metadata table, and the actor came away from /// the timestamp so a name is one colour and cyan is the stamp's alone. Asserted on /// the board as well as in `show`, because these are the cells both render. #[test] fn the_history_block_is_styled_in_the_overlay_and_no_escape_reached_it() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let history = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&history).unwrap(); std::fs::write( history.join("20260821_120000_000000_status.md"), "**Status**\nbacklog → committed\n\n**Author**: claude\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); std::fs::write( history.join("20260821_120001_000000_comment.md"), "**Comment**\nAnd why.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:01\n", ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); let detail = board.detail.as_ref().expect("no detail"); let heading = body_line(detail, "HISTORY"); assert_eq!(span_color(&heading, "HISTORY"), Some(Color::Orange.into())); let from = body_line(detail, "From bob"); assert_eq!(span_color(&from, "From"), Some(Color::Grey.into())); assert_eq!(span_color(&from, "bob"), Some(tag_color("bob").into())); assert_eq!(span_color(&from, "2026-08-21 12:00:01"), Some(Color::Cyan.into())); let change = body_line(detail, "backlog → committed"); assert_eq!(span_color(&change, "status"), Some(Color::Grey.into())); assert_eq!(span_color(&change, "backlog"), Some(Color::Orange.into())); assert_eq!(span_color(&change, "committed"), Some(Color::Orange.into())); assert_eq!(span_color(&change, "claude"), Some(tag_color("claude").into())); assert_eq!(span_color(&change, "2026-08-21 12:00:00"), Some(Color::Cyan.into())); // The quote's rows carry no bar span any more — the bar is the gutter the draw // lays beside them — so what says so on screen is a grey bar cell inside the // overlay, distinct from the border's own verticals by its colour. let said = body_line(detail, "And why."); assert!(!said.spans.iter().any(|span| span.content.contains(QUOTE_BAR))); // Held as text rather than through the borrow: the board is scrolled below. let plain = detail.plain(); // The log ends the overlay, so the gutter is on the last page. for _ in 0..20 { board.scroll_detail(1, SCREEN); } let mut terminal = Terminal::new(TestBackend::new(SCREEN.width, SCREEN.height)).unwrap(); terminal.draw(|frame| draw(frame, &board)).unwrap(); let buffer = terminal.backend().buffer().clone(); let overlay = detail_overlay(Rect::new(0, 0, SCREEN.width, SCREEN.height)); let grey: ratatui::style::Color = Color::Grey.into(); let bars = (overlay.y..overlay.bottom()) .flat_map(|y| (overlay.x..overlay.right()).map(move |x| (x, y))) .filter(|&(x, y)| { let cell = &buffer[(x, y)]; cell.symbol() == QUOTE_BAR && cell.fg == grey }) .count(); assert!(bars > 0, "no grey gutter bar reached the screen"); // The other half: the colour arrived as styles, not as bytes. assert!(!plain.contains('\x1b'), "escapes reached the detail view: {plain:?}"); } /// The bar is geometry over the rows a comment occupies, not text riding on each /// stored line's first characters: the reported bug was that ratatui's word wrap /// folds a long line onto continuation rows the prefix never reaches, so the quote /// read as ending halfway through. Every drawn row of the run is asserted here, /// wrapped continuations and the paragraph break included, and no row after it may /// carry a bar either — a stray one would be a quote wider than its body. #[test] fn the_detail_view_draws_every_line_of_a_comment_behind_the_bar() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let history = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&history).unwrap(); // One stored line long enough to wrap onto several drawn rows, then a second // paragraph behind its own break: the two ways the old shape lost the bar. let long_line = "alpha bravo charlie delta echo foxtrot golf hotel india juliet \ kilo lima mike november oscar papa quebec romeo sierra tango uniform victor \ whiskey xray yankee zulu"; std::fs::write( history.join("20260821_120000_000000_comment.md"), format!( "**Comment**\n{long_line}\n\nSecond paragraph.\n\n**Author**: bob\n**Time**: \ 2026-08-21 12:00:00\n" ), ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); // The log ends the overlay, so the last page is the one that holds the run. for _ in 0..20 { board.scroll_detail(1, SCREEN); } let screen = render(&board, SCREEN.width, SCREEN.height); let rows = overlay_text_rows(&screen, SCREEN.width, SCREEN.height); let header = rows .iter() .position(|row| row.starts_with("From bob")) .expect("the comment's header is not on screen"); // The run: every row after the header up to the first one without a bar. let mut at = header + 1; while rows.get(at).is_some_and(|row| row.starts_with(QUOTE_BAR)) { at += 1; } let run = header + 1..at; assert!( run.len() >= 4, "the fixture should wrap onto several rows, drew {run:?}:\n{rows:#?}" ); // Nothing outside the run is quoted: no stray bar above or below the block. assert!( rows[at..].iter().all(|row| !row.contains(QUOTE_BAR)), "a row past the comment carries a bar:\n{rows:#?}" ); // The break sits inside the run as the bare glyph, and the second paragraph // follows it behind the same bar. assert!( rows[run.clone()].iter().any(|row| row == QUOTE_BAR), "no bare bar on the paragraph break:\n{rows:#?}" ); assert!( rows[run].iter().any(|row| row.starts_with("│ Second")), "the second paragraph lost the bar:\n{rows:#?}" ); } /// The board and `show` share one layout, so the reason a move carries renders /// indented under the row it explains in the overlay too — attached to its /// transition rather than sitting apart like a comment. #[test] fn the_detail_view_renders_a_reason_under_its_row() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let history = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&history).unwrap(); std::fs::write( history.join("20260821_120000_000000_status.md"), "**Status**\nreviewing → backlog\n\n**Author**: claude\n**Time**: 2026-08-21 \ 12:00:00\n**Reason**: sent back, wrong approach\n", ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); let plain = board.detail.as_ref().expect("no detail").plain(); // The reason is its own quoted stretch under the row it explains; its rows carry // no bar in the text, since on screen the bar is the gutter beside them. let expected = "status reviewing → backlog claude (2026-08-21 12:00:00)\nsent back, wrong \ approach"; assert!(plain.contains(expected), "{plain}"); assert!(!plain.contains(QUOTE_BAR), "the bar reached the text: {plain:?}"); // And on screen the bar stands beside it, once the log is scrolled into view. for _ in 0..20 { board.scroll_detail(1, SCREEN); } let screen = render(&board, SCREEN.width, SCREEN.height); let rows = overlay_text_rows(&screen, SCREEN.width, SCREEN.height); let status = rows .iter() .position(|row| row.starts_with("status ")) .expect("the mechanical row is not on screen"); assert!( rows[status + 1].starts_with(&format!("{QUOTE_BAR} sent back")), "the reason did not draw behind the bar:\n{rows:#?}" ); } /// 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 = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000_comment.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 = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000_comment.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 = crate::history::history_dir(&dir, uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000_comment.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("↵ detail"), "{closed}"); assert!(!closed.contains("scroll"), "a scroll offered with nothing open:\n{closed}"); // The merged form: the word alone, with `q` the only cell of it drawn as a key. assert_eq!( keys_on(&board, SCREEN.width, SCREEN.height, "quit"), Some(1), "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("↵/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("↵/q close"), "q is not named as the close key:\n{row}"); // Nothing on the row is drawn as `q` quitting. Asked of the flattened row this is // unanswerable now: `ctrl-c quit` holds the word the merged form is. assert_eq!( keys_on(&board, 120, 20, "quit"), Some(0), "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, split because `ctrl-c` is no word's letter. assert_eq!( keys_on(&board, 120, 20, "ctrl-c quit"), Some(6), "nothing says what quits from here:\n{row}" ); } /// The division the row is drawn on: the key carries the accent colour and the words /// beside it carry none. Everything else about which key is named where is text, and /// this is the one thing that is not. #[test] fn a_key_is_the_accent_colour_and_its_description_is_the_default_foreground() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let board = one_board(&dir); let key: ratatui::style::Color = Color::Cyan.into(); // Merged: the `q` of `quit` is the key and the rest of the word is not. let (colour, modifier) = footer_style(&board, 120, 20, "quit"); assert_eq!(colour, key, "the key did not reach the screen as one"); assert!(modifier.contains(Modifier::BOLD), "the key is not bold: {modifier:?}"); let (colour, modifier) = footer_style(&board, 120, 20, "uit"); assert_eq!( colour, ratatui::style::Color::Reset, "the description took the key's colour" ); assert!(!modifier.contains(Modifier::BOLD), "the description is bold: {modifier:?}"); // Split: the same division across two words instead of inside one. assert_eq!(footer_style(&board, 120, 20, "y copy id").0, key); assert_eq!(footer_style(&board, 120, 20, "copy id").0, ratatui::style::Color::Reset); } /// The prompt and the picker take the row from the footer, and draw the keys they leave /// on it the way the footer does: a reader who has learnt where the coloured letter is /// does not learn it again per row. #[test] fn the_prompt_and_the_picker_draw_their_keys_as_the_footer_does() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); let key: ratatui::style::Color = Color::Cyan.into(); board.open_search(); assert_eq!(footer_style(&board, 120, 20, "↵ jump").0, key, "the prompt's key"); assert_eq!( footer_style(&board, 120, 20, "jump").0, ratatui::style::Color::Reset, "the prompt's description" ); board.search_key(typed(KeyCode::Esc), SCREEN); board.open_picker(PickerKind::Campaign, SCREEN); assert_eq!(footer_style(&board, 120, 20, "↵ view").0, key, "the picker's key"); assert_eq!( footer_style(&board, 120, 20, "view").0, ratatui::style::Color::Reset, "the picker's description" ); } // ------------------------------------------------------------------- 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() -> Fixture { 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("↵ jump"), "{row}"); assert!(row.contains("esc cancel"), "{row}"); assert!(!row.contains("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.should_quit, "typing 'q' quit the board"); assert_eq!(board.visibility, Visibility::Neither, "typing 'd' rotated the columns"); 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.rotate_visibility(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 command prompt -- /// A keypress with control held, which is how `ctrl-w` and `ctrl-c` arrive. fn ctrl(c: char) -> KeyEvent { KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL) } /// Type a whole line into an open command prompt, one key at a time, the way it arrives. fn type_line(board: &mut Board, line: &str) { for c in line.chars() { assert!(board.prompt_key(letter(c), SCREEN), "'{c}' was not taken"); } } fn prompt_line(board: &Board) -> Option<&str> { board.prompt.as_ref().map(|prompt| prompt.line.as_str()) } /// What the last enter had to say, or nothing. fn refused(board: &Board) -> Option<&str> { board .prompt .as_ref() .and_then(|prompt| prompt.refused.as_deref()) } /// Press enter on the open prompt, which is the whole of what this ticket does. fn submit(board: &mut Board) { assert!(board.prompt_key(typed(KeyCode::Enter), SCREEN), "enter was not taken"); } /// The prompt takes the row, names its own two keys, and the board is still behind it. #[test] fn the_command_prompt_replaces_the_footer_and_draws_the_line_and_its_cursor() { let dir = searchable(); let mut board = one_board(&dir); board.open_prompt(); let screen = render(&board, SCREEN.width, SCREEN.height); let row = screen.last().expect("no rows rendered"); assert!(row.contains("↵ run"), "{row}"); assert!(row.contains("esc cancel"), "{row}"); assert!(!row.contains("quit"), "the key list survived the prompt:\n{row}"); assert!( screen.join("\n").contains("Alpha first"), "the board went away behind the prompt" ); type_line(&mut board, "mv 1111111"); let row = footer(&board, SCREEN.width, SCREEN.height); assert!(row.contains(" :mv 1111111"), "the line is not drawn: {row}"); 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 ten characters typed. assert_eq!(at.x, 12, "the cursor is not after the line"); assert_eq!(at.y, SCREEN.height - 1, "the cursor left the prompt row"); } /// The line is edited where the cursor is, not at its end, which is the difference /// between a command line and the search prompt's append-only query. #[test] fn the_line_is_edited_at_a_cursor_the_way_a_shell_edits_one() { let dir = searchable(); let mut board = one_board(&dir); board.open_prompt(); type_line(&mut board, "mv 1111111"); board.prompt_key(typed(KeyCode::Home), SCREEN); type_line(&mut board, "x"); assert_eq!(prompt_line(&board), Some("xmv 1111111"), "home did not reach the front"); // Backspace takes the character before the cursor, not the last one on the line. board.prompt_key(typed(KeyCode::Backspace), SCREEN); assert_eq!(prompt_line(&board), Some("mv 1111111")); board.prompt_key(typed(KeyCode::Right), SCREEN); board.prompt_key(typed(KeyCode::Right), SCREEN); type_line(&mut board, "!"); assert_eq!(prompt_line(&board), Some("mv! 1111111")); board.prompt_key(typed(KeyCode::Left), SCREEN); board.prompt_key(typed(KeyCode::Backspace), SCREEN); assert_eq!(prompt_line(&board), Some("m! 1111111")); // `ctrl-w` takes the word before the cursor, and the separators behind the cursor // with it, so a second press takes the word before those rather than the space. board.prompt_key(typed(KeyCode::End), SCREEN); board.prompt_key(ctrl('w'), SCREEN); assert_eq!(prompt_line(&board), Some("m! ")); board.prompt_key(ctrl('w'), SCREEN); assert_eq!(prompt_line(&board), Some("")); // Nothing to take is nothing done, at either end. board.prompt_key(typed(KeyCode::Backspace), SCREEN); board.prompt_key(ctrl('w'), SCREEN); board.prompt_key(typed(KeyCode::Left), SCREEN); assert_eq!(prompt_line(&board), Some("")); // A cursor counted in bytes still moves by whole characters, so a backspace over a // multi-byte one takes the character rather than splitting it. type_line(&mut board, "comment é"); board.prompt_key(typed(KeyCode::Backspace), SCREEN); assert_eq!(prompt_line(&board), Some("comment ")); } /// 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 command is being typed. #[test] fn the_command_prompt_swallows_the_keys_that_are_bound_to_actions() { let first = searchable(); let second = board_dir(); let mut board = boards(&[("alpha", &first), ("beta", &second)]); let before = selected_title(&board); board.open_prompt(); 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::BackTab), typed(KeyCode::PageDown), ] { assert!(board.prompt_key(key, SCREEN), "{key:?} was not taken"); } assert!(!board.should_quit, "typing 'q' quit the board"); assert_eq!(board.visibility, Visibility::Neither, "typing 'd' rotated the columns"); assert_eq!(selected_title(&board), before, "an arrow moved the selection"); assert_eq!(board.tab, 0, "tab changed project from under the prompt"); // The letters landed in the line; the keys that are not characters did not. assert_eq!(prompt_line(&board), Some("dqjh")); } /// `ctrl-c` is the exception, since a terminal application always honours it. Every /// other control combination is swallowed and does nothing but the one that is bound. #[test] fn the_command_prompt_declines_ctrl_c_and_eats_every_other_control_key() { let dir = searchable(); let mut board = one_board(&dir); board.open_prompt(); assert!( !board.prompt_key(ctrl('c'), SCREEN), "the prompt ate ctrl-c and left no way off the board" ); assert!(board.prompt_key(ctrl('d'), SCREEN), "ctrl-d fell through to the 'd' arm"); assert_eq!(prompt_line(&board), Some(""), "a control key typed its letter"); } /// Both ways of leaving with nothing done, and neither touches anything behind the row. #[test] fn esc_and_enter_on_an_empty_line_leave_the_board_as_it_was() { let dir = searchable(); let mut board = one_board(&dir); board.toggle_detail(); let before = selected_title(&board); board.open_prompt(); type_line(&mut board, "mv 1111111"); assert!(board.prompt_key(typed(KeyCode::Esc), SCREEN), "esc was not taken"); assert!(board.prompt.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"); assert!(board.notice.is_none(), "a cancel said something in the footer"); // And the next esc is the overlay's again. assert!(!board.prompt_key(typed(KeyCode::Esc), SCREEN)); board.open_prompt(); submit(&mut board); assert!(board.prompt.is_none(), "enter on an empty line left the prompt open"); assert!(board.notice.is_none(), "an empty line named a command"); // A line of nothing but separators names no command either. board.open_prompt(); type_line(&mut board, " "); submit(&mut board); assert!(board.prompt.is_none(), "a line of spaces left the prompt open"); assert!(board.notice.is_none(), "a line of spaces named a command"); } /// A board a command can actually be run against. /// /// `board_dir` stands in for a `.worklane` without being one, which is enough to read /// a tree and not enough to write to it: a handler resolves its board by walking up /// from the path it is given, the way every shell invocation does, so what the prompt /// hands it has to be a directory with a real `.worklane` under it. /// /// The fixture is returned beside the board because dropping it takes the tree with /// it, and a board reading a deleted tree draws nothing. fn runnable() -> (Fixture, Board) { let root = Fixture::new("worklane-run").child("alpha"); let dir = root.join(".worklane"); for status in status_dirs() { std::fs::create_dir_all(dir.join(status)).unwrap(); } 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", "", ); let board = Board::new(projects(&[], &root).unwrap()).unwrap(); (root, board) } /// Type a line into a fresh prompt and press enter on it. fn run_line(board: &mut Board, line: &str) { board.open_prompt(); type_line(board, line); submit(board); } /// Which column a title is in, by the status it is drawn under, or nothing when the /// tab is not holding that ticket at all. fn column_of(board: &Board, title: &str) -> Option<&'static str> { board.current().columns.iter().find_map(|column| { let held = column.cards.iter().any(|card| card.ticket.title == title); held.then_some(column.status) }) } /// What the whole frame says, rows joined, for an assertion about a box that is not on /// the footer row. fn screen_text(board: &Board) -> String { render(board, SCREEN.width, SCREEN.height).join("\n") } /// The point of the ticket: the line clap took is handed to the same handler `main` /// hands it to, against the selected tab's own board, and the file on disk changes. /// /// And the board shows it at once. `tick` reloads on a digest, which is right for a /// change made in another pane and needless latency for one the board just made, so the /// run reloads unconditionally — which is what the tick reporting nothing to do /// afterwards says. #[test] fn enter_runs_the_command_against_the_selected_tab_and_redraws_at_once() { let (root, mut board) = runnable(); let dir = root.join(".worklane"); assert_eq!(column_of(&board, "Alpha first"), Some("backlog")); run_line(&mut board, "mv 1111111 --status committed"); assert!(board.prompt.is_none(), "the prompt stayed open: {:?}", refused(&board)); assert!( std::fs::read_dir(dir.join("committed")) .unwrap() .filter_map(|entry| entry.ok()) .any(|entry| entry.file_name().to_string_lossy().starts_with("11111111")), "the file did not move" ); // Drawn from the reload the command did, not from a tick nobody has run yet. assert_eq!(column_of(&board, "Alpha first"), Some("committed")); assert!( !board.tick().unwrap(), "the reload was left to the next tick, so the reader waits a poll interval for \ their own write" ); // And the quoted body, which is the reason the line is tokenised at all: split on // whitespace `comment` would be handed five arguments and clap would refuse it. run_line(&mut board, "comment 1111111 \"the offset was never passed\""); assert!(board.prompt.is_none(), "a quoted body was refused: {:?}", refused(&board)); let log = read_history(&dir, "11111111-0000-4000-8000-000000000000").unwrap(); assert!( log.iter() .any(|entry| entry.body == "the offset was never passed"), "the quoted body did not arrive whole: {log:?}" ); } /// What the handler said is what the board reports, word for word: those messages are /// already written for a person, and a second set kept on the board would go stale the /// first time one of them changed. /// /// Compared against the same command run straight through `dispatch`, which is also /// what says the words were *collected* rather than printed: a handler that reached /// stdout would leave the notice empty and the frame corrupt. #[test] fn the_footer_reports_the_handlers_own_words() { let (root, mut board) = runnable(); let mut buffer: Vec = Vec::new(); let command = ::try_parse_from(["worklane", "chown", "alice", "2222222"]) .unwrap() .command .unwrap(); { let mut sink = Sink::buffer(&mut buffer); crate::dispatch(&command, &root, &mut sink).unwrap(); sink.flush().unwrap(); } let said = String::from_utf8(buffer).unwrap().trim_end().to_string(); assert!(!said.is_empty(), "the handler said nothing to compare against"); // The same command again, this time through the prompt. `chown` is idempotent in // its wording, so the two answers are the same sentence. run_line(&mut board, "chown alice 2222222"); let notice = board.notice.as_ref().expect("the command said nothing"); assert_eq!(notice.text, said, "the board rewrote what the handler said"); assert!(!notice.failed, "a command that worked was reported as a failure"); } /// An answer of several lines is drawn as the lines it has. The footer is one row, so /// it cannot be the place: a box takes the foot of the columns instead, and the row /// keeps the one-line notice a copy has always put there. #[test] fn an_answer_of_several_lines_is_drawn_as_the_lines_it_has() { let (_root, mut board) = runnable(); run_line(&mut board, "relate 1111111 --blocked-by 2222222"); assert!(board.prompt.is_none(), "relate was refused: {:?}", refused(&board)); // `mv` names every open blocker on a line of its own and then says what `-f` does, // which is three lines and the reason none of them may be dropped. run_line(&mut board, "mv 1111111 --status committed"); let notice = board.notice.as_ref().expect("the refusal said nothing"); assert!(notice.failed, "a refused move was reported as a success"); assert!(notice.lines().len() >= 3, "the answer was cut: {:?}", notice.text); assert!(!board.notice_on_row(), "three lines were put on a one-row footer"); let screen = screen_text(&board); for line in notice.lines() { assert!(screen.contains(line.trim()), "`{line}` never reached the frame:\n{screen}"); } // The one-line case is unchanged: the row, and no box. board.notice = Some(Notice::done("copied 1111111")); board.prompt = None; assert!(board.notice_on_row(), "a one-line notice was taken off the row"); assert!( footer(&board, SCREEN.width, SCREEN.height).contains("copied 1111111"), "the row lost the notice it has always carried" ); } /// A handler that errors leaves the prompt open with the line exactly as it was: the /// usual cause is an ambiguous id, and the fix is two more characters rather than the /// whole line retyped from `:`. #[test] fn a_handler_that_errors_reports_it_and_leaves_the_prompt_open() { let (root, mut board) = runnable(); run_line(&mut board, "mv 1111111 --status reviewing"); assert_eq!( prompt_line(&board), Some("mv 1111111 --status reviewing"), "the line was not kept for correcting" ); let notice = board.notice.as_ref().expect("the error said nothing"); assert!(notice.failed, "an error was reported as a success"); assert!( notice.text.contains("one stage"), "not the handler's own words: {notice:?}" ); assert!(!board.notice_on_row(), "the error took the row the prompt is holding"); assert!( screen_text(&board).contains("one stage"), "the error never reached the frame" ); // And nothing was written, so the correction is a real one. assert_eq!(column_of(&board, "Alpha first"), Some("backlog")); // An ambiguous id is the case this shape exists for: the fix is two more // characters on a line the reader has already typed correctly. write_ticket( &root.join(".worklane"), "backlog", "11119999-0000-4000-8000-000000000000", "Alpha twin", "", ); board.prompt = None; run_line(&mut board, "mv 1111 --status committed"); assert_eq!( prompt_line(&board), Some("mv 1111 --status committed"), "the line was lost" ); let notice = board.notice.as_ref().expect("an ambiguous id said nothing"); assert!( notice.failed && notice.lines().len() > 1, "the candidates were cut: {notice:?}" ); } /// The selection stays on the ticket, not on the slot. `mv` puts the card in another /// column and `set --title` renames its file, and an index kept across the reload /// points at whatever has taken that place. #[test] fn the_selection_follows_the_ticket_the_command_moved() { let (_root, mut board) = runnable(); assert_eq!(selected_title(&board).as_deref(), Some("Alpha first")); run_line(&mut board, "mv 1111111 --status committed"); assert_eq!( selected_title(&board).as_deref(), Some("Alpha first"), "the selection stayed on the slot rather than the ticket" ); assert_eq!(board.current().column, 1, "the selection did not follow into committed"); // Renaming the file is the other half: the card is addressed by uuid, so a new // title and a new filename change nothing about which card is selected. run_line(&mut board, "set 1111111 --title \"Alpha renamed\""); assert_eq!(selected_title(&board).as_deref(), Some("Alpha renamed")); } /// And when the board cannot follow it, it says where it went. A card vanishing from /// under the highlight with nothing said reads as a bug in the board. #[test] fn the_notice_says_where_a_ticket_went_when_the_board_stops_drawing_it() { let (_root, mut board) = runnable(); // Done is hidden until `d` reveals it, so this is where a finished ticket goes by // default and the selection cannot go with it. run_line(&mut board, "mv 1111111 --status done -f"); let notice = board.notice.as_ref().expect("nothing was said"); assert!( notice.text.contains("(1111111) is in done"), "the ticket went out of view unannounced: {notice:?}" ); assert!(notice.text.contains('d'), "nothing said which key shows it: {notice:?}"); assert_ne!( selected_title(&board).as_deref(), Some("Alpha first"), "the selection followed a card into a column that is not drawn" ); // A filter that no longer holds it is the other way off the tab. Two tickets carry // the tag, so clearing one leaves the tag — and the filter — standing. let (_root, mut board) = runnable(); run_line(&mut board, "set 1111111 --tags urgent"); run_line(&mut board, "set 2222222 --tags urgent"); board.select_filter(Filter::Tag("urgent".to_string()), SCREEN); assert_eq!(column_of(&board, "Alpha first"), Some("backlog")); run_line(&mut board, "set 1111111 --clear tags"); assert_eq!(column_of(&board, "Alpha first"), None, "the filter kept it after all"); let notice = board.notice.as_ref().expect("nothing was said"); assert!( notice.text.contains("(1111111) is no longer on this tab"), "the filter dropped it unannounced: {notice:?}" ); } /// The merge tab is the one tab that is not a board: its cards came from several /// `.worklane` directories and it is none of them. Routing a write by the card it names /// is ebc5755; until then a command typed there is refused rather than landing on /// whichever project happened to come first. #[test] fn a_command_typed_on_the_merge_tab_is_refused_rather_than_guessed_at() { let (_first, one) = runnable(); let (_second, two) = runnable(); let of = |board: &Board| { let project = board .current_project() .expect("a single board has a project tab"); Project { name: project.name.clone(), dir: project.dir.clone(), } }; let mut board = Board::new(vec![of(&one), of(&two)]).unwrap(); assert_eq!(board.tab, 0, "the merge is not the tab the board opens on"); run_line(&mut board, "mv 1111111 --status committed"); let message = refused(&board).expect("the merge tab ran the command somewhere"); assert!(message.contains("project tab"), "{message}"); assert_eq!( prompt_line(&board), Some("mv 1111111 --status committed"), "the line was lost on a refusal" ); // On a project tab the same line runs, against that project's own board. board.select_tab(1, SCREEN); board.prompt = None; run_line(&mut board, "mv 1111111 --status committed"); assert!( board.prompt.is_none(), "a project tab refused it too: {:?}", refused(&board) ); assert_eq!(column_of(&board, "Alpha first"), Some("committed")); } /// Nothing a handler writes reaches the alternate screen, which is the whole reason the /// sink exists: under the board stdout *is* the frame, in raw mode. /// /// Two halves. The words come back as text, which is what having them in the notice at /// all proves. And nothing carrying an escape is drawn, which the sink answers for /// ordinary output and `error_lines` has to answer for an error, since a message built /// with `color_text` asks the process about its stdout rather than the sink. #[test] fn nothing_a_handler_writes_reaches_the_alternate_screen() { let (_root, mut board) = runnable(); run_line(&mut board, "mv 1111111 --status committed"); let notice = board.notice.as_ref().expect("the words went somewhere else"); assert!(!notice.text.contains('\x1b'), "an escape reached the notice: {notice:?}"); // A paragraph prints an escape rather than obeying it, so one on the frame is // literal bytes over the columns. assert!(!screen_text(&board).contains('\x1b'), "an escape reached the drawn frame"); // The error path, which never goes through a sink at all. let painted = anyhow::anyhow!( "Cannot move backward from {} to {}", paint("done", Color::Orange, true), paint("backlog", Color::Orange, true), ); let drawn = error_lines(&painted); assert!( !drawn.contains('\x1b'), "a painted error would be drawn as bytes: {drawn:?}" ); assert!( drawn.contains("from done to backlog"), "the words were stripped too: {drawn}" ); } /// `main` and the prompt run one dispatch table. Two would be two, and the second would /// drift the first time a command was added — silently, since both halves go on /// compiling. /// /// Read as text, the way the pre-dispatch's own contract is: neither is reachable from /// a test. The needles are built rather than written out, or this test's own source /// would be the second copy it is looking for. #[test] fn main_and_the_prompt_run_one_dispatch_table() { let main = include_str!("main.rs"); let here = include_str!("tui.rs"); assert!( main.contains("pub fn dispatch("), "the table is not a function both can call" ); for verb in ["mv", "add", "comment", "check", "assign", "relate", "set"] { let handler = format!("cmd_{verb}("); assert!(main.contains(&handler), "`{handler}` is not in the table"); assert!( !here.contains(&handler), "tui.rs reaches `{handler}` itself, which is a second dispatch table" ); } // What the board calls instead. assert!( here.contains("crate::dispatch(command, &root, &mut sink)"), "the board does not go through the table" ); } /// A line clap will not take keeps the prompt open with the line intact, so a typo is /// corrected in place instead of retyped from `:`. The message is clap's own, cut back /// to the part that fits a row. #[test] fn a_refused_line_keeps_the_prompt_open_and_shows_clap_without_the_usage_block() { let dir = searchable(); let mut board = one_board(&dir); board.open_prompt(); type_line(&mut board, "mv"); submit(&mut board); assert_eq!(prompt_line(&board), Some("mv"), "the line was not kept"); let message = refused(&board).expect("nothing was said about a line clap refused"); assert!(message.contains("required"), "not clap's own message: {message}"); assert!(!message.contains("Usage:"), "the usage block reached the row: {message}"); assert!(!message.contains('\n'), "the message is a paragraph, not a row: {message}"); assert!(!message.contains('\x1b'), "clap coloured the message: {message:?}"); let row = footer(&board, SCREEN.width, SCREEN.height); assert!(row.contains(" :mv"), "the line left the row: {row}"); assert!(row.contains("required"), "the message is not on the row: {row}"); assert!( !row.contains("esc cancel"), "the keys and the message shared the row: {row}" ); // The message is about the line, so moving the cursor keeps it and an edit takes it. board.prompt_key(typed(KeyCode::Left), SCREEN); assert!( refused(&board).is_some(), "moving the cursor cleared a message about a line that had not changed" ); type_line(&mut board, "x"); assert!(refused(&board).is_none(), "the message outlived the line it was about"); } /// `--help` parses as an error of the kind that means *print this*, and what it would /// print is a page: uncaught, clap's help lands on the alternate screen the way an /// unsunk `println!` would. `--version` is one line by construction, so it says itself. #[test] fn help_and_version_put_nothing_over_the_board() { let dir = searchable(); let mut board = one_board(&dir); for line in ["--help", "-h", "mv --help"] { board.open_prompt(); type_line(&mut board, line); submit(&mut board); let message = refused(&board).unwrap_or_else(|| panic!("`{line}` said nothing")); assert!(!message.contains('\n'), "`{line}` put a page on the row: {message}"); assert!(message.contains("help"), "`{line}` said something else: {message}"); let screen = render(&board, SCREEN.width, SCREEN.height); assert!( screen.join("\n").contains("Alpha first"), "`{line}` printed over the board" ); board.prompt_key(typed(KeyCode::Esc), SCREEN); } board.open_prompt(); type_line(&mut board, "--version"); submit(&mut board); let message = refused(&board).expect("`--version` said nothing"); assert!( message.contains(env!("CARGO_PKG_VERSION")), "`--version` did not say the version: {message}" ); assert!(!message.contains('\n'), "the version is not one line: {message}"); } /// The splitter reports a half-typed line as a state rather than an error, and this is /// what the prompt does with it: nothing goes to clap, because a grammar complaint about /// a sentence nobody finished is a complaint about the wrong thing. #[test] fn a_line_that_ends_inside_a_quote_is_never_handed_to_clap() { let (_root, mut board) = runnable(); board.open_prompt(); type_line(&mut board, "comment 1111111 \"the offset"); submit(&mut board); assert_eq!( prompt_line(&board), Some("comment 1111111 \"the offset"), "the line was not kept" ); let message = refused(&board).expect("nothing was said about an open quote"); assert!(message.contains("quote"), "{message}"); // Closing it makes the same line a command. type_line(&mut board, "\""); submit(&mut board); assert!( board.prompt.is_none(), "a closed quote was still refused: {:?}", refused(&board) ); } /// A line longer than the row scrolls under the cursor instead of being cut off at the /// end of the field, and scrolls back as the cursor moves left. #[test] fn a_line_longer_than_the_row_scrolls_with_the_cursor() { // The window itself, which is where the rule lives. assert_eq!(prompt_window("mv", 2, 10), ("mv".to_string(), 2)); assert_eq!(prompt_window("", 0, 10), (String::new(), 0)); assert_eq!(prompt_window("abcdefghij", 10, 5), ("ghij".to_string(), 4)); assert_eq!(prompt_window("abcdefghij", 0, 5), ("abcde".to_string(), 0)); assert_eq!(prompt_window("abcdefghij", 7, 5), ("defgh".to_string(), 4)); // One cell wide is still a cursor to type at rather than a panic. assert_eq!(prompt_window("abc", 3, 1), (String::new(), 0)); let dir = searchable(); let mut board = one_board(&dir); board.open_prompt(); type_line(&mut board, &format!("mv {}", "a".repeat(200))); let row = footer(&board, SCREEN.width, SCREEN.height); assert!(!row.contains(":mv"), "the head of the line held the row: {row}"); assert!(row.contains("esc cancel"), "a long line pushed the keys off: {row}"); let mut terminal = Terminal::new(TestBackend::new(SCREEN.width, SCREEN.height)).unwrap(); terminal.draw(|frame| draw(frame, &board)).unwrap(); assert!( terminal.get_cursor_position().unwrap().x < SCREEN.width, "the cursor left the frame" ); // Home takes the window back to the front of the line. board.prompt_key(typed(KeyCode::Home), SCREEN); let row = footer(&board, SCREEN.width, SCREEN.height); assert!( row.contains(" :mv aaa"), "the window did not follow the cursor back: {row}" ); } /// `:` is the way in, and only from the action arms: typed into either open prompt it is /// an ordinary character, and pressed at an open picker it belongs to the picker. #[test] fn a_colon_typed_into_the_search_or_the_picker_opens_nothing() { let dir = searchable(); // A campaign to pick, since an empty picker says so rather than opening. Its own // uuid, not one of the tickets': nothing here resolves either, and a shared prefix // in a fixture reads as a claim that it matters. write_campaign( &dir, "55555555-0000-4000-8000-000000000000", "First public release", "v1", "For a public tag.", ); let mut board = one_board(&dir); board.open_search(); assert!(board.search_key(letter(':'), SCREEN), "':' was not taken by the search"); assert!(board.prompt.is_none(), "the search prompt opened a command prompt"); assert_eq!(board.search.as_ref().map(|search| search.query.as_str()), Some(":")); board.search_key(typed(KeyCode::Esc), SCREEN); board.open_picker(PickerKind::Campaign, SCREEN); assert!(board.picker_key(letter(':'), SCREEN), "':' was not taken by the picker"); assert!(board.prompt.is_none(), "the picker opened a command prompt"); assert!(board.picker.is_some(), "':' closed the picker"); // And inside the picker's own query it is a character like any other. board.picker_key(letter('/'), SCREEN); board.picker_key(letter(':'), SCREEN); assert_eq!( board .picker .as_ref() .and_then(|picker| picker.query.clone()) .as_deref(), Some(":"), ); assert!(board.prompt.is_none(), "the picker's query opened a command prompt"); } /// The row names the keys that work, and `:` works in every state the board is in. #[test] fn every_footer_names_the_command_key() { let dir = searchable(); let mut board = one_board(&dir); assert!(footer(&board, 120, 20).contains(": command"), "the board's own footer"); board.toggle_detail(); assert!(footer(&board, 120, 20).contains(": command"), "the modal footer"); } /// The prompt has to be offered every key before the action arms, and `:` has to be the /// way in from the board itself. Neither is reachable from a test, so the dispatch is /// read as text, the way the search prompt's own contract is. #[test] fn the_dispatch_opens_the_command_prompt_and_gives_it_the_keyboard_first() { let source = include_str!("main.rs") .split_whitespace() .collect::>() .join(" "); assert!( source.contains("if board.prompt_key(key, screen) { continue; }"), "the prompt has to be offered every key before the action arms, or typing \ 'd' into a command toggles the done column" ); assert!( source.contains("KeyCode::Char(':') => board.open_prompt(),"), "`:` has to open the prompt from the action arms" ); } // ------------------------------------------------------------------- the recall -- /// Press a key on the open prompt and assert it was taken, which every key there is. fn press_prompt(board: &mut Board, code: KeyCode) { assert!(board.prompt_key(typed(code), SCREEN), "{code:?} was not taken"); } /// What a board has kept, oldest first, whatever tab it is on. fn kept(board: &Board) -> &[String] { &board.recalls[board.tab].lines } /// What the file holds, or nothing when there is no file to read. fn recall_file(dir: &Path) -> Option { std::fs::read_to_string(dir.join(RECALL_FILE)).ok() } /// The walk itself: `up` hands back the previous line, repeated presses go further /// back, and `down` comes forward again and returns the line that was being typed. #[test] fn up_walks_back_through_the_lines_and_down_comes_forward_to_the_half_typed_one() { let (_root, mut board) = runnable(); for line in ["ls backlog", "show 1111111"] { run_line(&mut board, line); } board.open_prompt(); type_line(&mut board, "comm"); press_prompt(&mut board, KeyCode::Up); assert_eq!( prompt_line(&board), Some("show 1111111"), "up did not hand back the last line" ); press_prompt(&mut board, KeyCode::Up); assert_eq!(prompt_line(&board), Some("ls backlog"), "up did not walk further back"); // The oldest line is a stop, not a wrap onto the newest again. press_prompt(&mut board, KeyCode::Up); assert_eq!(prompt_line(&board), Some("ls backlog"), "up wrapped past the oldest line"); press_prompt(&mut board, KeyCode::Down); assert_eq!(prompt_line(&board), Some("show 1111111"), "down did not come forward"); press_prompt(&mut board, KeyCode::Down); assert_eq!(prompt_line(&board), Some("comm"), "the half typed line was lost"); // Nothing in front of the reader's own line, so down there does nothing. press_prompt(&mut board, KeyCode::Down); assert_eq!(prompt_line(&board), Some("comm"), "down emptied the row"); } /// The cursor lands at the end of a recalled line, since what a reader does with one is /// append to it or fix its tail. #[test] fn a_recalled_line_arrives_with_the_cursor_at_its_end() { let (_root, mut board) = runnable(); run_line(&mut board, "ls backlog"); board.open_prompt(); press_prompt(&mut board, KeyCode::Up); type_line(&mut board, " --tag bug"); assert_eq!( prompt_line(&board), Some("ls backlog --tag bug"), "the cursor was not at the end of the recalled line" ); } /// An empty recall does nothing at all, and that includes leaving the row alone: `up` on /// a board nobody has typed at must not be a way to lose a half typed command. #[test] fn up_on_a_board_with_no_lines_leaves_the_row_alone() { let (_root, mut board) = runnable(); board.open_prompt(); type_line(&mut board, "mv 111"); press_prompt(&mut board, KeyCode::Up); press_prompt(&mut board, KeyCode::Down); assert_eq!(prompt_line(&board), Some("mv 111"), "an arrow touched the line"); assert!(kept(&board).is_empty(), "a line nobody entered was kept"); } /// The line this is most needed for. A refused line never reached a handler, and the fix /// is usually two characters, so it has to be recallable like any other. #[test] fn a_line_that_was_refused_is_recalled_too() { let (_root, mut board) = runnable(); run_line(&mut board, "mb 1111111 --status committed"); assert!(refused(&board).is_some(), "the typo was not refused"); // The prompt is still open on the refused line, so this is the next opening of it. board.prompt = None; board.open_prompt(); press_prompt(&mut board, KeyCode::Up); assert_eq!( prompt_line(&board), Some("mb 1111111 --status committed"), "the refused line was not kept" ); } /// Holding `up` steps through distinct commands rather than through the same `mv` typed /// four times. #[test] fn consecutive_duplicates_are_kept_once() { let (root, mut board) = runnable(); run_line(&mut board, "ls backlog"); run_line(&mut board, "ls backlog"); run_line(&mut board, "show 1111111"); run_line(&mut board, "ls backlog"); assert_eq!( kept(&board), ["ls backlog", "show 1111111", "ls backlog"], "the repeat was kept twice, or a line away from its repeat was folded into it" ); let dir = root.join(".worklane"); assert_eq!( recall_file(&dir).unwrap_or_default(), "ls backlog\nshow 1111111\nls backlog\n", "the file and the walk disagree" ); } /// The point of the file: the lines outlive the run. A board is opened and closed all /// day, and a recall that empties on quit only helps inside a single sitting. #[test] fn the_lines_go_in_the_board_folder_and_come_back_on_the_next_run() { let (root, mut board) = runnable(); let dir = root.join(".worklane"); run_line(&mut board, "ls backlog"); assert_eq!(recall_file(&dir).as_deref(), Some("ls backlog\n"), "nothing was written"); drop(board); // The next run of the board over the same tree, which is what a quit and a restart // leaves behind. let mut next = Board::new(projects(&[], root.as_ref()).unwrap()).unwrap(); assert_eq!(kept(&next), ["ls backlog"], "the file was not read back"); next.open_prompt(); press_prompt(&mut next, KeyCode::Up); assert_eq!(prompt_line(&next), Some("ls backlog"), "the previous run is not recalled"); // And the duplicate rule spans the two runs, since it is applied to what was loaded. run_line(&mut next, "ls backlog"); assert_eq!(kept(&next), ["ls backlog"], "the file's last line was repeated"); } /// One file per board, and the walk follows the tab. A project's lines are the ones /// naming its ticket ids, and handing another board's `mv` back here would offer an id /// that resolves to nothing. #[test] fn each_tab_walks_the_lines_of_its_own_board() { let (first, one) = runnable(); let (second, two) = runnable(); let mut board = Board::new(vec![ project_at(&one.projects[0].dir), project_at(&two.projects[0].dir), ]) .unwrap(); // A delta and not an index, so the two project tabs are one step apart from the // merge the board opens on. board.select_tab(1, SCREEN); assert_eq!(board.tab, 1, "the first project tab is not where one step lands"); run_line(&mut board, "ls backlog"); board.prompt = None; board.select_tab(1, SCREEN); assert_eq!(board.tab, 2, "the second project tab is not the next step"); run_line(&mut board, "show 1111111"); board.prompt = None; board.open_prompt(); press_prompt(&mut board, KeyCode::Up); assert_eq!( prompt_line(&board), Some("show 1111111"), "the second tab walked the first's" ); board.prompt = None; board.select_tab(-1, SCREEN); assert_eq!(board.tab, 1, "the step back missed the first project tab"); board.open_prompt(); press_prompt(&mut board, KeyCode::Up); assert_eq!(prompt_line(&board), Some("ls backlog"), "the first tab lost its own line"); assert_eq!(kept(&board), ["ls backlog"], "the other tab's line reached this one"); assert_eq!( recall_file(&first.join(".worklane")).as_deref(), Some("ls backlog\n"), "the first board's file" ); assert_eq!( recall_file(&second.join(".worklane")).as_deref(), Some("show 1111111\n"), "the second board's file" ); } /// The merge tab is not a board, so there is nothing to attribute its lines to. They are /// still recalled for the run, since every one of them was refused and a refused line is /// the one worth getting back. #[test] fn a_line_typed_on_the_merge_tab_is_recalled_for_the_run_and_written_nowhere() { let (first, one) = runnable(); let (second, two) = runnable(); let mut board = Board::new(vec![ project_at(&one.projects[0].dir), project_at(&two.projects[0].dir), ]) .unwrap(); assert_eq!(board.tab, 0, "the merge is not the tab the board opens on"); run_line(&mut board, "mv 1111111 --status committed"); assert!(refused(&board).is_some(), "the merge tab ran the command somewhere"); board.prompt = None; board.open_prompt(); press_prompt(&mut board, KeyCode::Up); assert_eq!( prompt_line(&board), Some("mv 1111111 --status committed"), "the merge tab did not recall its own line" ); for dir in [first.join(".worklane"), second.join(".worklane")] { assert_eq!( recall_file(&dir), None, "a merge line landed on a board: {}", dir.display() ); } } /// A board whose folder cannot take the file still recalls within the run. The line is /// what the reader asked for and it is on the row either way, so a failed write is /// silent rather than a notice about the one thing nobody asked for. #[test] fn a_file_that_cannot_be_written_still_recalls_for_the_run() { let (root, _board) = runnable(); let dir = root.join(".worklane"); // A directory where the file goes: the read fails, and so does every append. std::fs::create_dir_all(dir.join(RECALL_FILE)).unwrap(); let mut board = Board::new(projects(&[], root.as_ref()).unwrap()).unwrap(); assert!(kept(&board).is_empty(), "an unreadable file was not an empty recall"); run_line(&mut board, "ls backlog"); assert!(board.prompt.is_none(), "the command was refused: {:?}", refused(&board)); assert_eq!(kept(&board), ["ls backlog"], "the line was lost with the write"); board.open_prompt(); press_prompt(&mut board, KeyCode::Up); assert_eq!(prompt_line(&board), Some("ls backlog"), "the recall stopped working"); } /// The swallow contract, restated with something in the recall: the arrows now do /// something inside the prompt, and it still must not be the thing they do on the board. #[test] fn the_arrows_walk_the_recall_and_never_the_cards() { let (_root, mut board) = runnable(); run_line(&mut board, "ls backlog"); board.prompt = None; let before = selected_title(&board); let column = board.current().column; board.open_prompt(); press_prompt(&mut board, KeyCode::Up); press_prompt(&mut board, KeyCode::Down); press_prompt(&mut board, KeyCode::Up); assert_eq!(selected_title(&board), before, "an arrow moved the selection"); assert_eq!(board.current().column, column, "an arrow changed column"); assert_eq!(prompt_line(&board), Some("ls backlog"), "the walk did not happen"); } // ------------------------------------------------------------------ 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_eq!( keys_on(&board, 120, 20, "quit"), Some(1), "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. /// The fixture points at the project and removes the directory above it, which is what /// `Fixture::child` is for: the path a test hands to `projects` is the project, and the /// generated name that has to be swept up is its parent. fn project_tree(name: &str) -> Fixture { let root = Fixture::new("worklane-project").child(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.to_path_buf(), beta.to_path_buf()], &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 = Fixture::new("worklane-bare"); let error = projects(&[alpha.to_path_buf(), bare.to_path_buf()], &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.to_path_buf(), 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}"); } /// The titles of one column, top to bottom, which is the order the reader acts on. fn column_titles(board: &Board, at: usize) -> Vec { board.current().columns[at] .cards .iter() .map(|card| card.ticket.title.clone()) .collect() } /// Every column past the backlog is ordered by its own entry stamp, not by priority: /// committed is the longest wait first, done is what just landed first. Every ticket /// here is a p2, so the stamp is doing all of the work. #[test] fn a_column_is_ordered_by_the_stamp_the_ticket_entered_it_with() { let dir = board_dir(); let stamp = |field: &str, at: &str| format!("- **{field}**: 2026-08-0{at} 09:00:00\n"); write_ticket( &dir, "committed", "11111111-0000-4000-8000-000000000000", "Waited", &stamp("Committed On", "1"), ); write_ticket( &dir, "committed", "22222222-0000-4000-8000-000000000000", "Fresh", &stamp("Committed On", "3"), ); write_ticket( &dir, "done", "33333333-0000-4000-8000-000000000000", "Older", &stamp("Completed On", "1"), ); write_ticket( &dir, "done", "44444444-0000-4000-8000-000000000000", "Newer", &stamp("Completed On", "3"), ); let board = boards(&[("only", &dir)]); assert_eq!(column_titles(&board, 1), ["Waited", "Fresh"]); assert_eq!(column_titles(&board, 3), ["Newer", "Older"]); } /// The backlog is the column with no entry stamp, so the due date is what orders it. /// Every ticket here is a p2, so the due is doing all of the work, and the undated /// one trails both dated ones rather than sitting among them. #[test] fn the_backlog_column_is_ordered_by_the_due_date() { let dir = board_dir(); let card = |uuid: &str, title: &str, due: &str| { let path = write_ticket(&dir, "backlog", uuid, title, ""); let body = std::fs::read_to_string(&path) .unwrap() .replace("- **Due**: 2026-12-31", &format!("- **Due**: {due}")); std::fs::write(&path, body).unwrap(); }; card("11111111-0000-4000-8000-000000000000", "Later", "2026-09-03"); card("22222222-0000-4000-8000-000000000000", "Undated", "_Not set_"); card("33333333-0000-4000-8000-000000000000", "Sooner", "2026-09-01"); let board = boards(&[("only", &dir)]); assert_eq!(column_titles(&board, 0), ["Sooner", "Later", "Undated"]); } /// The merge spans statuses, so no single stamp governs it and it keeps priority then /// title. Pinned on done, where the column order and the merge order disagree: the /// board would put the newest first and the merge puts the p1 first. #[test] fn the_merge_keeps_priority_then_title_where_a_column_would_use_the_stamp() { let (first, second) = (board_dir(), board_dir()); let card = |dir: &Path, uuid: &str, title: &str, level: u8, day: u8| { let path = write_ticket(dir, "done", uuid, title, ""); let body = std::fs::read_to_string(&path) .unwrap() .replace("- **Priority**: 2", &format!("- **Priority**: {level}")) .replace( "- **Status**: done\n", &format!("- **Completed On**: 2026-08-0{day} 09:00:00\n- **Status**: done\n"), ); std::fs::write(&path, body).unwrap(); }; // Both on one board, so that board's own column can be read for the other // order. The urgent one finished first, so stamp and priority disagree. card(&first, "11111111-0000-4000-8000-000000000000", "Urgent", 1, 1); card(&first, "22222222-0000-4000-8000-000000000000", "Later", 5, 3); // A second board, which is what makes the merge tab exist at all. card(&second, "33333333-0000-4000-8000-000000000000", "Other", 3, 2); let mut board = boards(&[("alpha", &first), ("beta", &second)]); assert_eq!( column_titles(&board, 3), ["Urgent", "Other", "Later"], "the merge sorted by stamp" ); // The board the cards came from orders that column by the stamp, so the two // really are two orders rather than one that happens to agree. board.select_tab(1, SCREEN); assert_eq!(column_titles(&board, 3), ["Later", "Urgent"]); } /// 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")); } /// A discarded blocker holds nothing up, the answer `mv` gives it: there is nothing /// left to wait for. /// /// The board and `mv` share `is_open` for this, which is what keeps them from /// drifting now that the blocker arrives in the map: `columns_of` builds every /// status, so a rule written as `!= DONE` would mark these cards while `mv` kept /// letting them move. The fixture writes the directory directly, the way a board /// that predates a discard would hold one. #[test] fn a_discarded_blocker_marks_nothing() { let dir = board_dir(); std::fs::create_dir_all(dir.join(DISCARDED)).unwrap(); write_ticket(&dir, DISCARDED, BLOCKER, "The blocker", ""); write_ticket(&dir, "backlog", WAITER, "The waiter", &blocked_by(BLOCKER)); assert!(!marked_blocked(&one_board(&dir), "The waiter")); assert!(!is_open(DISCARDED), "the rule the board and mv share"); assert!(is_open("backlog") && is_open("committed") && is_open("reviewing")); } /// 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() -> Fixture { related_board_targeting("reviewing") } /// The same, with the target in a status of the caller's choosing: how the row is /// drawn depends on it, so a test about a discarded target needs one there. fn related_board_targeting(status: &str) -> Fixture { 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, status, 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 strike reaches the board as a ratatui modifier, not as `\x1b[9m` in the /// paragraph, which is what a `Paragraph` would draw as literal bytes. `Cell` carries /// the modifier for the same reason it carries the colour: one layout, two painters. /// /// Paired the way the guideline demands, and both halves are load bearing. A renderer /// that struck nothing would pass the absence, and one that went back to painting /// strings would pass the presence. #[test] fn a_discarded_target_is_struck_in_the_overlay_and_no_escape_reached_it() { let dir = related_board_targeting(DISCARDED); 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"); for span in &row.spans { assert!( span.style.add_modifier.contains(Modifier::CROSSED_OUT), "{:?} is not struck, so the line breaks mid row: {row:?}", span.content ); } // The pair: the strike arrived as a style, and no escape arrived with it. assert!(!row.spans.is_empty(), "the row has no spans, so the loop above is vacuous"); assert!( !detail.plain().contains('\x1b'), "escapes reached the body: {:?}", detail.plain() ); } /// The other side of it, so the assertion above cannot be satisfied by a board that /// strikes every relation row through: a live target is drawn as it always was. #[test] fn a_live_target_is_not_struck_in_the_overlay() { 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"); for span in &row.spans { assert!( !span.style.add_modifier.contains(Modifier::CROSSED_OUT), "{:?} is struck through: {row:?}", span.content ); } } /// One builder behind both views, so the dedupe 03bdc76 added lands on the board /// without the overlay knowing about it. Criterion 2 names the board as well as /// `show`, and this is the half that says so. #[test] fn a_relates_to_stored_at_both_ends_is_drawn_once_in_the_overlay() { let dir = board_dir(); let holder = "11111111-0000-4000-8000-000000000000"; let target = "22222222-0000-4000-8000-000000000000"; // Both lines, which is the state a board recorded before `relate` refused the // mirror. The section goes ahead of the metadata on the holder, where `relate` // writes it and where the overlay has it on screen. std::fs::write( dir.join("backlog").join(format!("{holder}_a-holder.md")), format!( "# A holder\n\n## Description\nA description.\n\n## Relations\n\ - relates to {target}\n\n## Metadata\n\n- **ID**: {holder}\n\ - **Priority**: 2\n- **Status**: backlog\n" ), ) .unwrap(); write_ticket( &dir, "reviewing", target, "The target", &format!("\n## Relations\n- relates to {holder}\n"), ); let mut board = one_board(&dir); board.toggle_detail(); let body = board.detail.as_ref().expect("no detail").plain(); assert_eq!( body.matches("relates to").count(), 1, "the same edge is drawn twice in the overlay:\n{body}" ); } /// 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 = detail_last_offset(&board.detail.as_ref().unwrap().sections, 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 history // 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 history 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 .sections .iter() .flat_map(|section| section.text().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() ); } /// Every painted run in the body reaches the overlay as a style, e4d0bb7. /// /// The block was the only coloured part of the body; the rest was flat because /// `content_parts` painted into a string and the board had to ask for the unpainted /// one. It hands out cells now, so the CLI paints them and the board styles them, /// and there is one layout behind both. /// /// Paired the way the guideline demands, and both halves are load bearing here: a /// renderer that dropped every colour would pass the absence, and one that went back /// to painting strings would pass the presence. #[test] fn the_whole_body_is_styled_in_the_overlay_and_no_escape_reached_it() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{uuid}_a-painted-one.md")), format!( "# A painted one\n\n## Description\n\nA line with **emphasis** in it.\n\n\ ## Acceptance Criteria\n\n- [ ] Something\n\n\ ## Implementation Plan\n\n1. A step\n\n\ ## Metadata\n\n- **ID**: {uuid}\n- **Due**: _Not set_\n\ - **Tags**: bug\n- **Status**: backlog\n" ), ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); let detail = board.detail.as_ref().expect("no detail"); // One run per colour the guideline gives the body, each asked for by name so a // run that goes flat names itself in the failure. let heading = body_line(detail, "Description"); assert_eq!(span_color(&heading, "Description"), Some(Color::Orange.into())); let emphasis = body_line(detail, "emphasis"); assert_eq!(span_color(&emphasis, "emphasis"), Some(Color::Magenta.into())); let criterion = body_line(detail, "Something"); assert_eq!(span_color(&criterion, "1."), Some(Color::Cyan.into())); assert_eq!(span_color(&criterion, "[ ]"), Some(Color::Grey.into())); let step = body_line(detail, "A step"); assert_eq!(span_color(&step, "1."), Some(Color::Cyan.into())); let due = body_line(detail, "_Not set_"); assert_eq!(span_color(&due, "Due"), Some(Color::Red.into())); assert_eq!(span_color(&due, "_Not set_"), Some(Color::Grey.into())); let tags = body_line(detail, "bug"); assert_eq!(span_color(&tags, "bug"), Some(tag_color("bug").into())); // `Color::Magenta.ansi()` is `\x1b[1;35m`, so the CLI draws a bold run bold as // well as magenta. The board has to add the modifier itself, since `From` // carries only the colour. let bold = emphasis .spans .iter() .find(|span| span.content.as_ref() == "emphasis") .expect("no emphasis span"); assert!( bold.style.add_modifier.contains(Modifier::BOLD), "the bold run is magenta but not bold: {bold:?}" ); // The other half: none of that arrived as bytes. 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}"); } /// 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}"); } /// 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 = detail_last_offset(&board.detail.as_ref().unwrap().sections, 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}"); } /// 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!( detail_last_offset(&board.detail.as_ref().unwrap().sections, 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") ); } /// 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"); } /// 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" ); } // ------------------------------------------------------------- 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") } /// Four completed campaigns, oldest first: the campaign, the member that finished it, /// its title and the hour it was filed. /// /// An hour apart so the truncation has an order to keep, and named so no title is a /// substring of another's or of a summary any of these boards draws. const FINISHED: [(&str, &str, &str, &str); 4] = [ ( "aaaaaaaa-0000-4000-8000-000000000000", "a1111111-0000-4000-8000-000000000000", "Disk migration", "2026-01-01 01:00:00", ), ( "bbbbbbbb-0000-4000-8000-000000000000", "b1111111-0000-4000-8000-000000000000", "Log rework", "2026-01-01 02:00:00", ), ( "cccccccc-0000-4000-8000-000000000000", "c1111111-0000-4000-8000-000000000000", "Prompt polish", "2026-01-01 03:00:00", ), ( "dddddddd-0000-4000-8000-000000000000", "d1111111-0000-4000-8000-000000000000", "Tag audit", "2026-01-01 04:00:00", ), ]; /// A board that has run for a while: two open campaigns and [`FINISHED`]'s four /// completed ones, which is more completed than the picker shows. /// /// Beaver holds no members at all, so it is what pins a campaign with none listing as /// open. Every completed one holds a done member, since a campaign with none is open /// however long it has been on the board. fn tail_board(dir: &Path) -> Board { write_campaign(dir, V1, "First public release", "v1", "Everything for a public tag."); write_campaign(dir, BEAVER, "Beaver migration", "beaver", "Move the store off one disk."); write_ticket( dir, "backlog", "11111111-0000-4000-8000-000000000000", "In v1", &campaign_field(V1), ); for (campaign, member, title, created_at) in FINISHED { write_dated_campaign(dir, campaign, title, created_at); write_ticket(dir, "done", member, title, &campaign_field(campaign)); } one_board(dir) } /// A campaign with the filing time a test can set, and nothing else on it. /// /// A separate fixture rather than a sixth parameter on `write_campaign`, the split /// `write_member_card` already makes: only the tests about the completed section's /// order care when a campaign was filed, and five string arguments in a row is what /// the Rust Style rule in AGENTS.md warns about. fn write_dated_campaign(dir: &Path, uuid: &str, title: &str, created_at: &str) { let campaigns = dir.join(CAMPAIGNS_DIR); std::fs::create_dir_all(&campaigns).unwrap(); std::fs::write( campaigns.join(format!("{}_{}.md", uuid, slug(title))), format!( "# {title}\n\n## Description\nWhat it was for.\n\n## Metadata\n\n\ - **ID**: {uuid}\n- **Codename**: {NOT_SET}\n- **Owner**: alice\n\ - **Created At**: {created_at}\n" ), ) .unwrap(); } /// Open the picker's query and type into it, `/` and all. /// /// Through `picker_key` rather than by writing the field, so what a test drives is what /// a reader's keyboard drives: the `/` has to be taken by the picker for any of the /// characters after it to land in a query at all. fn type_picker_query(board: &mut Board, query: &str) { press(board, KeyCode::Char('/')); for c in query.chars() { assert!(board.picker_key(letter(c), SCREEN), "'{c}' was not taken"); } } /// Press one key at the open picker. fn press(board: &mut Board, code: KeyCode) { assert!(board.picker_key(typed(code), SCREEN), "{code:?} was not taken"); } /// The query the picker is holding, or nothing when it is reading keys as movement. fn query_of(board: &Board) -> Option { board .picker .as_ref() .expect("the picker is not open") .query .clone() } /// The uuid the highlight is on, so a test can name it without reaching for a row /// number the sections have already moved. fn highlighted(board: &Board) -> Option { board.picked().map(|key| key.name().to_string()) } /// Which drawn row is exactly this heading, since a heading is the whole of its row. fn row_at(rows: &[String], heading: &str) -> usize { rows.iter() .position(|row| row.trim() == heading) .unwrap_or_else(|| panic!("no {heading:?} row: {rows:?}")) } /// Which drawn row carries this text, for the rows that carry more than one thing. fn row_with(rows: &[String], needle: &str) -> usize { rows.iter() .position(|row| row.contains(needle)) .unwrap_or_else(|| panic!("no row with {needle:?}: {rows:?}")) } /// The campaigns the picker is drawing, in the order it draws them. /// /// Off `picker_list` rather than off the frame, because what a filter is asked about is /// which campaigns are in the list and not how their rows came out: a query narrow /// enough to leave one row leaves nothing on screen to count against. fn picked_ids(board: &Board) -> Vec { let picker = board.picker.as_ref().expect("the picker is not open"); picker_list(board.current(), picker) .iter() .filter_map(|row| match row { PickerRow::Campaign(campaign) => Some(campaign.uuid.clone()), _ => None, }) .collect() } /// The colour the picker drew the first character of one of its rows in. /// /// The first character, because that is where every row this is asked about starts /// saying what it is: the ellipsis on the truncation line and the first letter of a /// heading. Counted from the top of the list, which is where an unscrolled box is. fn picker_row_color( board: &Board, at: usize, width: u16, height: u16, ) -> ratatui::style::Color { let picker = board.picker.as_ref().expect("the picker is not open"); let rows = picker_list(board.current(), picker).len(); let inner = picker_overlay(Rect::new(0, 0, width, height), rows).inner(Margin::new(1, 1)); let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); buffer[(inner.x, inner.y + at as u16)].fg } /// The picker's rows, cut out of the frame by its own geometry. /// /// The whole screen will not do: a card carries the same campaign label, so a search /// for one over every row finds the board rather than the list, which is the shape /// `overlay_title_row` exists for on the other overlay. /// /// Counted in *drawn* rows, which is what the box is sized against: the sections and the /// truncation line are rows of it, so a count of the campaigns alone would cut the last /// one or two off whatever the test is looking for. fn picker_rows(board: &Board, width: u16, height: u16) -> Vec { let picker = board.picker.as_ref().expect("the picker is not open"); let rows = picker_list(board.current(), picker).len(); let overlay = picker_overlay(Rect::new(0, 0, width, height), rows); let inner = overlay.inner(Margin::new(1, 1)); let lines = render(board, width, height); (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 tag picker -- /// A ticket carrying `tags`, in `status`, so a test can build a board with a vocabulary /// spread across the columns. fn write_tag_ticket(dir: &Path, status: &str, uuid: &str, title: &str, tags: &str) { std::fs::write( dir.join(status).join(format!("{}_{}.md", uuid, slug(title))), format!( "# {title}\n\n## Description\nA description.\n\n## Metadata\n\n\ - **ID**: {uuid}\n- **Priority**: 2\n- **Tags**: {tags}\n\ - **Due**: _Not set_\n- **Owner**: alice\n\ - **Created At**: 2026-08-21 02:00:00\n- **Status**: {status}\n" ), ) .unwrap(); } /// The vocabulary file, written the way `tags add` writes it. fn write_vocabulary(dir: &Path, declared: &[(&str, &str)]) { let mut index = TagIndex::default(); for (tag, annotation) in declared { index.declare(tag, annotation); } std::fs::write(dir.join(TAGS_FILE), index.render()).unwrap(); } /// Three tags across three columns, two of them declared: `bug` and `cli` are in the /// vocabulary, `sync` is a word somebody typed onto a ticket, and `chore` is declared /// and carried by nothing. fn tag_board(dir: &Path) -> Board { write_tag_ticket(dir, "backlog", "11111111-0000-4000-8000-000000000000", "One", "bug,cli"); write_tag_ticket(dir, "committed", "22222222-0000-4000-8000-000000000000", "Two", "bug"); write_tag_ticket(dir, "done", "33333333-0000-4000-8000-000000000000", "Three", "sync"); write_vocabulary( dir, &[ ("bug", "Behaviour that contradicts what the tool says."), ("chore", "Work with nothing to see."), ("cli", "The command line surface."), ], ); one_board(dir) } /// The tag rows of an open picker, without the chrome around them. fn open_tag_picker(board: &mut Board) -> Vec { board.open_picker(PickerKind::Tag, SCREEN); picker_rows(board, SCREEN.width, SCREEN.height) .into_iter() .map(|row| row.trim_end().to_string()) .filter(|row| !row.is_empty()) .collect() } /// The board could be cut by campaign and not by the other axis it has always had. #[test] fn the_tag_picker_lists_every_tag_the_board_declares_or_carries() { let dir = board_dir(); let mut board = tag_board(&dir); let rows = open_tag_picker(&mut board); assert_eq!( rows, vec![ "declared", "bug 2 Behaviour that contradicts what the tool says.", "chore 0 Work with nothing to see.", "cli 1 The command line surface.", "undeclared", "sync 1", ], "the picker does not list the vocabulary" ); } /// The split is the point of the list: a word nobody agreed on sits under the ones that /// were, which is where `campaign` against `campaigns` would have been caught. #[test] fn an_undeclared_tag_sits_in_its_own_section() { let dir = board_dir(); let mut board = tag_board(&dir); let rows = open_tag_picker(&mut board); let declared = rows .iter() .position(|row| row == "declared") .expect("no declared heading"); let undeclared = rows .iter() .position(|row| row == "undeclared") .expect("no undeclared heading"); assert!(declared < undeclared, "the sections are the wrong way round: {rows:?}"); assert!( rows.iter().skip(undeclared).any(|row| row.starts_with("sync")), "the carried tag is not under the undeclared heading: {rows:?}" ); } /// Every column, so a tag answers the same question the listing does. #[test] fn picking_a_tag_filters_every_column_to_the_cards_carrying_it() { let dir = board_dir(); let mut board = tag_board(&dir); board.visibility = Visibility::Both; board.select_filter(Filter::Tag("bug".to_string()), SCREEN); let headings = headings(&board, 120, 20); assert!(headings.contains("backlog (1)"), "{headings}"); assert!(headings.contains("committed (1)"), "{headings}"); assert!(headings.contains("done (0)"), "{headings}"); } /// Case sensitively, exactly as `--tag` matches, or the same question asked on the board /// and at the command line gives two answers. #[test] fn a_tag_filter_keeps_case_apart_the_way_the_listing_does() { let dir = board_dir(); write_tag_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "One", "bug"); write_tag_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Two", "Bug"); let mut board = one_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); assert!(headings(&board, 120, 20).contains("backlog (1)"), "case was folded"); } /// A word the board agreed on and has not used is worth picking, and an empty board is /// the honest answer to it: the count on the row said so before it was pressed. #[test] fn a_declared_tag_nothing_carries_can_be_picked_and_empties_the_board() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("chore".to_string()), SCREEN); assert!(headings(&board, 120, 20).contains("backlog (0)"), "the filter was refused"); assert_eq!( board.current().filter.tag(), Some("chore"), "the filter came off with nothing to show" ); } /// A board that predates the vocabulary still has tags, and every one of them is a word /// nobody declared. #[test] fn a_board_with_no_vocabulary_lists_every_tag_as_undeclared() { let dir = board_dir(); write_tag_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "One", "bug,cli"); let mut board = one_board(&dir); let rows = open_tag_picker(&mut board); assert_eq!(rows, vec!["undeclared", "bug 1", "cli 1"], "{rows:?}"); } /// The query reads the annotation as well as the tag, which is the rule the campaign /// picker follows: a row is searched by what it draws. A reader who cannot remember the /// word can often remember what it was for. #[test] fn the_tag_query_matches_the_annotation_as_well_as_the_tag() { let dir = board_dir(); let mut board = tag_board(&dir); board.open_picker(PickerKind::Tag, SCREEN); for typed in "contradicts".chars() { board.picker_key(KeyEvent::new(KeyCode::Char(typed), KeyModifiers::NONE), SCREEN); } board.picker_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE), SCREEN); for typed in "contradicts".chars() { board.picker_key(KeyEvent::new(KeyCode::Char(typed), KeyModifiers::NONE), SCREEN); } let rows: Vec = picker_rows(&board, SCREEN.width, SCREEN.height) .into_iter() .map(|row| row.trim_end().to_string()) .filter(|row| !row.is_empty()) .collect(); assert_eq!( rows, vec![ "declared", "bug 2 Behaviour that contradicts what the tool says." ] ); } /// `esc` takes the query off before it takes the picker off, one layer at a time, the /// order `dismiss` closes the board's own layers in. Shared machinery, tested here too /// because it is a criterion of the tag picker and not only of the campaign one. #[test] fn esc_clears_the_tag_query_before_it_closes_the_picker() { let dir = board_dir(); let mut board = tag_board(&dir); board.open_picker(PickerKind::Tag, SCREEN); board.picker_key(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE), SCREEN); board.picker_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::NONE), SCREEN); let rows: Vec = picker_rows(&board, SCREEN.width, SCREEN.height) .into_iter() .map(|row| row.trim_end().to_string()) .filter(|row| !row.is_empty()) .collect(); assert_eq!(rows.len(), 2, "the query did not filter the rows: {rows:?}"); board.picker_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), SCREEN); assert!(board.picker.is_some(), "esc closed the picker with a query open"); assert!( board .picker .as_ref() .is_some_and(|picker| picker.query.is_none()), "the query survived esc" ); board.picker_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), SCREEN); assert!(board.picker.is_none(), "the second esc left the picker open"); assert!(board.current().filter.is_whole(), "esc filtered the board"); } /// One filter at a time, which is what `Filter` makes true rather than what two setters /// remember: the frame above the columns names what they are, and it has one thing to /// say. #[test] fn picking_a_tag_clears_a_campaign_and_picking_a_campaign_clears_a_tag() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); write_member_card(&dir, "Short", "cli", V1); let mut board = one_board(&dir); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); board.select_filter(Filter::Tag("cli".to_string()), SCREEN); assert_eq!(board.current().filter.campaign(), None, "the campaign survived a tag"); assert_eq!(board.current().filter.tag(), Some("cli")); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); assert_eq!(board.current().filter.tag(), None, "the tag survived a campaign"); assert_eq!(board.current().filter.campaign(), Some(V1)); } /// A tag that leaves the board altogether takes its filter with it, the answer a /// campaign that leaves already gets: a filter on a word nothing declares and nothing /// carries would empty every column and say nothing about why. Being carried by nothing /// is not the same thing, which is the case above. #[test] fn a_tag_that_leaves_the_vocabulary_gives_the_whole_board_back() { let dir = board_dir(); let path = dir .join("backlog") .join(format!("{}_{}.md", "11111111-0000-4000-8000-000000000000", "one")); write_tag_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "One", "bug"); let mut board = one_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); // The only ticket carrying it, and no vocabulary declaring it: the word is gone. std::fs::remove_file(&path).unwrap(); board.tick().unwrap(); assert!(board.current().filter.is_whole(), "the filter outlived its tag"); } /// `q` takes off whatever view is on, and a tag filter is one, the way a campaign is. #[test] fn q_gives_the_whole_board_back_from_a_tag() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); board.dismiss(SCREEN); assert!(board.current().filter.is_whole(), "the filter survived q"); assert!(!board.should_quit, "q quit out from under the filter"); } /// The frame slot is one slot, so a tag holds the selection above the columns the way a /// campaign does: `up` from the top card reaches it, and `down` comes back. #[test] fn a_tag_frame_holds_the_selection_the_way_a_campaign_frame_does() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); assert_eq!(board.chrome().frame, Some(FrameSize::Collapsed), "a tag drew no frame"); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "up from the top card stayed put"); board.select_card(1, SCREEN); assert_eq!(board.current().focus, Focus::Cards, "down did not leave the frame"); } /// The row names both filters where a reader has to find them, and spends nothing on /// either once one is on: the frame above the columns names what the board is filtered /// to and says `q board` on its own border, so the row saying it again would be eight /// cells spent repeating what is already on screen. #[test] fn the_footer_names_the_tag_key_and_leaves_the_way_back_to_the_frame() { let dir = board_dir(); let mut board = tag_board(&dir); // Both merged, being their own words' first letters. let plain = footer(&board, 120, 20); assert_eq!( keys_on(&board, 120, 20, "tag"), Some(1), "the tag key is not named: {plain}" ); assert_eq!(keys_on(&board, 120, 20, "campaign"), Some(1), "{plain}"); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); let filtered = footer(&board, 120, 20); assert!(!filtered.contains("q board"), "the row repeated the frame: {filtered}"); assert_eq!( keys_on(&board, 120, 20, "tag"), None, "a key that filters again: {filtered}" ); assert!(filtered.contains("ctrl-c quit"), "{filtered}"); } /// `y` on the frame copies what the frame names, and a tag is its own id: `--tag` /// matches the word whole, and the hash the border draws is not part of it. #[test] fn y_on_a_tag_frame_copies_the_tag_and_not_the_hash() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); board.select_card(-1, SCREEN); assert_eq!(board.copy_text().as_deref(), Some("bug")); assert!( footer(&board, 120, 20).contains("y copy tag"), "the row called a tag an id" ); } // ------------------------------------------------------- the tag frame -- /// `tag_board` filtered to `bug`, with an annotation that has somewhere to scroll. /// /// The same three tickets every other tag test reasons about, and `write_vocabulary` /// again over the same three tags, which is the same file: the columns are the fixture's /// and only the prose above them is this one's. fn tag_frame_board(dir: &Path, lines: usize) -> Board { tag_board(dir); let annotation = long_description(lines); write_vocabulary( dir, &[ ("bug", annotation.as_str()), ("chore", "Work with nothing to see."), ("cli", "The command line surface."), ], ); let mut board = one_board(dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); board } /// The colour the hash on the frame's top border actually reached the screen in. /// /// Located on that row rather than by searching the buffer for the glyph: a card draws /// `#bug` on its own label row, and `drawn_color` would answer about whichever card /// holds the first one. fn frame_title_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 area = screen_rows(Rect::new(0, 0, width, height), board.chrome())[FRAME_ROW]; (area.x..area.x + area.width) .find(|x| buffer[(*x, area.y)].symbol() == "#") .map(|x| buffer[(x, area.y)].fg) } /// The colour the frame's first row of prose reached the screen in, which is what says /// a placeholder is a placeholder. fn frame_prose_color(board: &Board, width: u16, height: u16) -> ratatui::style::Color { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); let text = screen_rows(Rect::new(0, 0, width, height), board.chrome())[FRAME_ROW] .inner(Margin::new(1, 1)); buffer[(text.x, text.y)].fg } /// The payoff for declaring a tag at all: whoever is browsing one is deciding whether /// the next ticket belongs in it, and the sentence saying when it is appropriate is on /// the screen at that moment rather than in a file they would have to know to open. #[test] fn the_tag_frame_names_the_tag_and_what_it_means() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); let rows = frame_lines(&board, 100, 24); assert_eq!(rows.len(), Chrome::FRAME_ROWS as usize, "the frame is a different height"); assert!(rows[0].contains("#bug"), "no tag on the frame: {:?}", rows[0]); assert!( rows[1].contains("Behaviour that contradicts what the tool says."), "no annotation: {:?}", rows[1] ); // The way out, on the border of the thing it undoes, where the campaign frame puts // it: with a filter on, the footer's last slot names `ctrl-c quit`. let bottom = rows.len() - 1; assert!(rows[bottom].contains("q board"), "no way out named: {:?}", rows[bottom]); } /// The bottom right is what the frame is *about*: how much of the board this is. The /// noun is spelled out and pluralised, because a bare number on a border says nothing /// about what was counted. #[test] fn the_count_of_tickets_carrying_the_tag_is_on_the_bottom_border() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); let held: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(held, 2, "the fixture changed"); let rows = frame_lines(&board, 100, 24); let bottom = &rows[rows.len() - 1]; assert!(bottom.contains("2 tickets"), "no count on the frame: {bottom:?}"); // And the singular, on the one tag the fixture gives a single ticket. board.select_filter(Filter::Tag("cli".to_string()), SCREEN); let rows = frame_lines(&board, 100, 24); let bottom = &rows[rows.len() - 1]; assert!( bottom.contains("1 ticket "), "the count did not agree with itself: {bottom:?}" ); } /// The count is every column's, drawn or not, the rule the campaign standing holds: /// hiding done is a change to what is drawn and never to what is counted. `sync` is /// carried by the done ticket alone, so the two answers differ here or nowhere. #[test] fn the_count_holds_while_the_only_column_carrying_the_tag_is_hidden() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("sync".to_string()), SCREEN); assert_eq!(board.visibility, Visibility::Neither, "a terminal column is drawn"); let rows = frame_lines(&board, 100, 24); let bottom = &rows[rows.len() - 1]; assert!( bottom.contains("1 ticket "), "the hidden column was not counted: {bottom:?}" ); } /// A tag nobody declared has no annotation, and the frame says so rather than drawing a /// blank row: that is the frame telling you the word was never agreed on, which is the /// other half of what the vocabulary file is for. #[test] fn an_undeclared_tag_draws_the_placeholder_rather_than_a_blank_row() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("sync".to_string()), SCREEN); let rows = frame_lines(&board, 100, 24); assert!(rows[1].contains(NO_ANNOTATION), "no placeholder: {:?}", rows[1]); assert_eq!( frame_prose_color(&board, 100, 24), Color::Grey.into(), "the placeholder was drawn as prose" ); } /// The colour guideline applied: `tag_color` is a pure function of the word, so the /// frame, the picker row and every card agree without anything being stored. #[test] fn the_tag_on_the_frame_is_drawn_in_the_colour_a_card_draws_it_in() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("bug".to_string()), SCREEN); assert_eq!( frame_title_color(&board, 100, 24), Some(tag_color("bug").into()), "the tag was not drawn in its own colour" ); } /// The frame slot is shared, not doubled: one filter is on at a time, so the rows the /// columns give up cannot depend on which of the two took them. #[test] fn the_tag_frame_takes_the_rows_the_campaign_frame_takes() { let dir = board_dir(); let mut board = tag_board(&dir); let screen = Size { width: 100, height: 24 }; let plain = board_area(screen, board.chrome()); board.select_filter(Filter::Tag("bug".to_string()), screen); let framed = board_area(screen, board.chrome()); assert_eq!(framed.y, plain.y + Chrome::FRAME_ROWS, "the columns did not move down"); assert_eq!( framed.height, plain.height - Chrome::FRAME_ROWS, "the frame took its rows from somewhere else" ); } /// The frame spends its prose rows on prose, whichever filter filled it. #[test] fn the_tag_frame_draws_a_row_of_the_annotation_for_every_row_it_takes() { let dir = board_dir(); let board = tag_frame_board(&dir, 40); let rows = frame_lines(&board, 120, 20); let prose = &rows[1..rows.len() - 1]; assert_eq!(prose.len(), Chrome::FRAME_PROSE_ROWS as usize, "not all of them are prose"); for (at, drawn) in prose.iter().enumerate() { let wanted = format!("Line {:03}", at + 1); assert!(drawn.contains(&wanted), "no {wanted} on the frame: {drawn:?}"); } } /// An annotation with paragraphs in it is longer than three rows, so the two keys that /// read a campaign's description read this one, clamped at both ends off the same /// wrapped measurement the draw uses. One set of rules, per ebad2fa: the same keys must /// not move different distances in the two things the frame can hold. #[test] fn the_scroll_keys_page_through_the_tag_frame() { let dir = board_dir(); let mut board = tag_frame_board(&dir, 40); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "up did not reach the frame"); board.scroll_page(1, SCREEN); let one = board.current().frame_offset; assert!(one > 0, "the frame did not move"); board.scroll_page(1, SCREEN); assert!(board.current().frame_offset > one, "the second page did not move"); board.scroll_page(40, SCREEN); let text = frame_text_area(SCREEN, board.chrome()); let last = last_offset(&tag_prose(board.current().selected_tag().expect("no tag")), text); assert_eq!(board.current().frame_offset, last, "the scroll ran past the annotation"); board.scroll_page(-40, SCREEN); assert_eq!(board.current().frame_offset, 0, "the scroll ran off the top"); } /// The page indicator earns its place here for the reason it does on the campaign frame: /// three rows of a long annotation look exactly like the whole of a short one. #[test] fn a_scrollable_annotation_puts_a_page_indicator_on_the_frame() { let dir = board_dir(); let long = tag_frame_board(&dir, 40); let rows = frame_lines(&long, 120, 20); let bottom = &rows[rows.len() - 1]; assert!(bottom.contains("pg 1/"), "no indicator on a long annotation: {bottom:?}"); let dir = board_dir(); let mut short = tag_board(&dir); short.select_filter(Filter::Tag("bug".to_string()), SCREEN); let rows = frame_lines(&short, 120, 20); let bottom = &rows[rows.len() - 1]; assert!(!bottom.contains("pg "), "an indicator where nothing scrolls: {bottom:?}"); } /// `q` takes the filter off from the frame as well as from the cards. The frame is the /// view the reader put on, not a layer over it, so there is no extra press between them /// and the board. #[test] fn q_gives_the_whole_board_back_from_the_tag_frame() { let dir = board_dir(); let mut board = tag_frame_board(&dir, 40); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "up did not reach the frame"); board.dismiss(SCREEN); assert!(board.current().filter.is_whole(), "the filter survived q"); assert_eq!(board.current().focus, Focus::Cards, "the focus outlived the frame"); assert!(!board.should_quit, "q quit out from under the filter"); } /// `enter` gives a tag frame half the board and takes the rows back, the key the /// campaign frame already has: the height is a view of the prose above the columns, and /// an annotation with paragraphs in it is as worth half the board as a description is. #[test] fn enter_expands_a_tag_frame_and_gives_the_rows_back() { let dir = board_dir(); let mut board = tag_frame_board(&dir, 40); board.select_card(-1, SCREEN); let collapsed = board.chrome().frame_rows(SCREEN.height); assert_eq!(collapsed, Chrome::FRAME_ROWS, "the frame did not open collapsed"); board.toggle_focused(SCREEN); let expanded = board.chrome().frame_rows(SCREEN.height); assert!(expanded > collapsed, "enter did not give the frame more rows"); // The draw and the measurement, which is what `Chrome` exists to keep as one answer. assert_eq!( frame_lines(&board, SCREEN.width, SCREEN.height).len(), expanded as usize, "the draw and the measurement disagree" ); board.toggle_focused(SCREEN); assert_eq!( board.chrome().frame_rows(SCREEN.height), collapsed, "enter did not give the rows back" ); } /// A tag the board stops holding takes its frame with it, the answer `reload` gives a /// campaign that has left: a frame that is no longer drawn must not go on holding the /// selection. #[test] fn a_tag_that_leaves_the_board_takes_its_frame_and_the_selection_with_it() { let dir = board_dir(); let mut board = tag_board(&dir); board.select_filter(Filter::Tag("sync".to_string()), SCREEN); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "up did not reach the frame"); std::fs::remove_file( dir.join("done") .join("33333333-0000-4000-8000-000000000000_three.md"), ) .unwrap(); board.tick().unwrap(); assert!(board.current().filter.is_whole(), "the filter outlived its tag"); assert_eq!(board.current().focus, Focus::Cards, "the focus outlived the frame"); assert_eq!(board.chrome().frame, None, "the frame outlived the tag"); } /// A tag is a string and the same string on every board, so the merge tab carries one /// row per word and filtering to it cuts every project at once. A campaign cannot do /// this: its uuid resolves inside one `.worklane`. #[test] fn a_tag_on_the_merge_tab_reaches_every_board() { let first = board_dir(); let second = board_dir(); write_tag_ticket(&first, "backlog", "11111111-0000-4000-8000-000000000000", "One", "bug"); write_tag_ticket(&second, "backlog", "22222222-0000-4000-8000-000000000000", "Two", "bug"); write_vocabulary(&first, &[("bug", "Something wrong.")]); let mut board = boards(&[("first", &first), ("second", &second)]); let rows = open_tag_picker(&mut board); assert_eq!( rows, vec!["declared", "bug 2 Something wrong."], "the tags did not merge" ); board.picker = None; board.select_filter(Filter::Tag("bug".to_string()), SCREEN); assert!(headings(&board, 120, 20).contains("backlog (2)"), "one board was left out"); } /// The vocabulary is read on the tick like everything else the board draws, so a tag /// declared elsewhere reaches an open picker rather than a copy of the list taken when /// it opened. #[test] fn declaring_a_tag_elsewhere_changes_the_digest() { let dir = board_dir(); write_tag_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "One", "bug"); let before = digest(&dir); write_vocabulary(&dir, &[("bug", "Something wrong.")]); assert_ne!(before, digest(&dir), "the vocabulary is outside the digest"); } /// A board with no tags at all says so in words rather than opening an empty box, the /// answer the campaign picker already gives. #[test] fn a_board_with_no_tags_says_so_rather_than_opening_an_empty_picker() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Untagged", ""); let mut board = one_board(&dir); board.open_picker(PickerKind::Tag, SCREEN); assert!(board.picker.is_none(), "an empty picker opened"); let notice = board.notice.as_ref().expect("nothing was said"); assert!(notice.text.contains("no tags"), "{}", notice.text); assert!(notice.failed, "the notice did not read as a key that did nothing"); } /// `t` has to reach the tag picker from the dispatch, which is not reachable from a /// test: the arm is the only place the binding exists. #[test] fn the_dispatch_binds_t_to_the_tag_picker() { let source = include_str!("main.rs") .split_whitespace() .collect::>() .join(" "); assert!( source .contains("KeyCode::Char('t') => board.open_picker(tui::PickerKind::Tag, screen),"), "`t` has to reach the tag picker, and it is the only way in to it" ); } /// 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:?}"); } /// 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:?}"); } /// 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:?}"); } /// 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:?}"); } /// 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:?}"); } /// 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:?}"); } /// 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 ); } /// 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"); } /// Selecting a campaign turns the 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_filter(Filter::Campaign(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::ALL.len()); } /// 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_filter(Filter::Campaign(V1.to_string()), SCREEN); let rows = frame_lines(&board, 100, 24); assert_eq!(rows.len(), Chrome::FRAME_ROWS as usize, "the frame is a different height"); let bottom = rows.len() - 1; 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 description: {:?}", rows[1] ); assert!(rows[bottom].contains("0/2 done"), "no standing: {:?}", rows[bottom]); assert!(rows[bottom].contains("[open]"), "no derived state: {:?}", rows[bottom]); // The way out, on the border of the thing it undoes. assert!(rows[bottom].contains("q board"), "no way out named: {:?}", rows[bottom]); } /// 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_filter(Filter::Campaign(V1.to_string()), SCREEN); assert_eq!(board.visibility, Visibility::Neither, "a column is drawn at startup"); let standing = board .current() .selected_campaign() .expect("no campaign selected") .standing; assert_eq!((standing.done, standing.total), (1, 2)); } /// A member decided out of the campaign counts as finished, the rule `campaign ls` /// holds: counting it outstanding would hold the campaign open over a ticket nobody /// will ever do. #[test] fn the_standing_counts_a_discarded_member_as_finished() { 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, DISCARDED, "55555555-0000-4000-8000-000000000000", "Dropped one", &campaign_field(V1), ); let mut board = one_board(&dir); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); let standing = board .current() .selected_campaign() .expect("no campaign selected") .standing; assert_eq!((standing.done, standing.total), (1, 2), "the discard was not counted"); } /// 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_filter(Filter::Campaign(V1.to_string()), screen); let framed = board_area(screen, board.chrome()); assert_eq!(framed.y, plain.y + Chrome::FRAME_ROWS, "the columns did not move down"); assert_eq!( framed.height, plain.height - Chrome::FRAME_ROWS, "the frame took its rows from somewhere else" ); } // ------------------------------------------------------- the frame's own prose -- /// A description of numbered lines, so a test can say which of them is on screen. /// /// `long_section` for a campaign, and longer than the frame at any width these tests /// draw, which is true of every campaign description filed in this repo. fn long_description(lines: usize) -> String { (1..=lines).map(|n| format!("Line {n:03}\n")).collect() } /// `campaign_board` filtered to v1, with a description that has somewhere to scroll. /// /// The same tickets as every other campaign test reasons about, and `write_campaign` /// again over the same uuid and title, which is the same file: the columns are the /// fixture's and only the prose above them is this one's. fn frame_board(dir: &Path, lines: usize) -> Board { campaign_board(dir); write_campaign(dir, V1, "First public release", "v1", &long_description(lines)); let mut board = one_board(dir); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); board } /// Whether any card is drawn picked out, which is what the reversed modifier does. /// /// Read off the buffer rather than off `card_lines`, because the question is what the /// reader can see: the highlight is the only thing that says which ticket `y` and /// `enter` are about, and while the frame holds the selection they are about none. fn a_card_is_highlighted(board: &Board, width: u16, height: u16) -> bool { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); let area = board_area(Size { width, height }, board.chrome()); (area.y..area.y + area.height) .flat_map(|y| (area.x..area.x + area.width).map(move |x| (x, y))) .any(|(x, y)| buffer[(x, y)].modifier.contains(Modifier::REVERSED)) } /// The frame spends its prose rows on prose, which is the whole point of taking them: /// a line and a half of a description was the wrong amount for the place the question /// it answers gets asked. #[test] fn the_frame_draws_a_row_of_the_description_for_every_row_it_takes() { let dir = board_dir(); let board = frame_board(&dir, 40); let rows = frame_lines(&board, 120, 20); assert_eq!(rows.len(), Chrome::FRAME_ROWS as usize, "the frame is a different height"); // The prose rows are the frame's rows less the border either side of them. let prose = &rows[1..rows.len() - 1]; assert_eq!(prose.len(), Chrome::FRAME_PROSE_ROWS as usize, "not all of them are prose"); for (at, drawn) in prose.iter().enumerate() { let wanted = format!("Line {:03}", at + 1); assert!(drawn.contains(&wanted), "no {wanted} on the frame: {drawn:?}"); } } /// Up past the top card reaches the frame, and down comes back to the column it was /// left in rather than to the first one: the column index is never what changed. #[test] fn up_from_the_top_card_reaches_the_frame_and_down_returns_to_the_column() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_column(1, SCREEN); assert_eq!( selected_title(&board).as_deref(), Some("Also in v1"), "the fixture changed" ); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "up from the top card stayed put"); // And no further up: the frame is the top of the board, the answer the top card of // a column already gives. board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "up from the frame went somewhere"); board.select_card(1, SCREEN); assert_eq!(board.current().focus, Focus::Cards, "down did not leave the frame"); assert_eq!(board.current().column, 1, "down landed in a different column"); assert_eq!(selected_title(&board).as_deref(), Some("Also in v1")); } /// An empty column reaches it too. A column with no card to stand on must not be a /// column the reader is stuck in, which is what the old clamp made of it. #[test] fn an_empty_column_still_reaches_the_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_column(2, SCREEN); assert!(board.selected().is_none(), "the fixture's third column is not empty"); board.select_card(-1, SCREEN); assert_eq!( board.current().focus, Focus::Frame, "an empty column trapped the selection" ); board.select_card(1, SCREEN); assert_eq!(board.current().column, 2, "down landed somewhere else"); } /// The two keys the overlay reads a ticket with read the frame's description, clamped /// at both ends off the same wrapped measurement the draw uses. #[test] fn the_scroll_keys_page_through_the_frame_while_it_holds_the_selection() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); board.scroll_page(1, SCREEN); let one = board.current().frame_offset; assert!(one > 0, "the frame did not move"); board.scroll_page(1, SCREEN); assert!(board.current().frame_offset > one, "the second page did not move"); // Both ends, the clamp the overlay applies: the last page ends with the prose // rather than running on into blank rows, and the top is zero. board.scroll_page(40, SCREEN); let text = frame_text_area(SCREEN, board.chrome()); let last = last_offset( &campaign_prose(board.current().selected_campaign().expect("no campaign")), text, ); assert_eq!(board.current().frame_offset, last, "the scroll ran past the description"); board.scroll_page(-40, SCREEN); assert_eq!(board.current().frame_offset, 0, "the scroll ran off the top"); } /// And only while it holds the selection. On the cards the keys are what they were /// before the frame could scroll, which is nothing. #[test] fn the_scroll_keys_leave_the_frame_alone_from_the_cards() { let dir = board_dir(); let mut board = frame_board(&dir, 40); assert_eq!(board.current().focus, Focus::Cards, "the board opened on the frame"); board.scroll_page(1, SCREEN); assert_eq!(board.current().frame_offset, 0, "the frame scrolled from the cards"); } /// An open ticket keeps both keys whatever holds the selection behind it. It is the /// thing the reader put on and the thing they are reading, and it has had them since /// 1b78a24. /// /// The state is built by hand because no keypress produces it: up stops at the top card /// while a ticket is open, which the next test is. The precedence is what has to be /// written down, and it holds whether or not there is a way to reach the state. #[test] fn an_open_ticket_keeps_the_scroll_keys_from_the_frame() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", &long_description(40)); let mut extra = campaign_field(V1); extra.push_str(&long_section(60)); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "A long one", &extra, ); let mut board = one_board(&dir); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); board.toggle_detail(); assert!(board.detail.is_some(), "nothing opened"); let tab = board.tab; board.tabs[tab].focus = Focus::Frame; board.scroll_page(1, SCREEN); assert!(board.offset > 0, "the open ticket lost the scroll keys"); assert_eq!(board.current().frame_offset, 0, "the frame took them from under it"); } /// And the frame is out of reach from under an open ticket. Up and down step through /// the tickets there and the overlay follows, so a selection that reached the frame /// would have to either close the overlay on an arrow key or leave it showing a ticket /// nothing is selecting. #[test] fn the_frame_is_out_of_reach_from_under_an_open_ticket() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.toggle_detail(); assert!(board.detail.is_some(), "nothing opened"); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Cards, "the frame took the selection"); assert!(board.detail.is_some(), "the overlay closed on an arrow key"); } /// The frame says there is more of it than fits, in the words the overlay says it in: /// a reader who has learned what `pg 2/3` means on a ticket reads it the same way here. #[test] fn the_frame_says_there_is_more_of_it_than_fits() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); let bottom = |board: &Board| { let rows = frame_lines(board, 120, 20); rows[rows.len() - 1].clone() }; let first = bottom(&board); assert!(first.contains("pg 1/"), "no indicator on a scrollable frame: {first:?}"); // Beside the way out and clear of the standing, which is the frame's own corner. assert!(first.contains("q board"), "the indicator took the way out: {first:?}"); assert!(first.contains("0/2 done"), "the indicator took the standing: {first:?}"); board.scroll_page(1, SCREEN); let second = bottom(&board); assert!( second.contains("pg 2/"), "the indicator did not follow the scroll: {second:?}" ); } /// A description that fits leaves the frame selectable and the keys inert. Making the /// frame unreachable instead would be a key that works on one campaign and not the /// next, which is worse than a key that sometimes has nothing to scroll. #[test] fn a_description_that_fits_leaves_the_frame_selectable_and_the_keys_inert() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "the short frame was unreachable"); board.scroll_page(1, SCREEN); assert_eq!(board.current().frame_offset, 0, "a description that fits scrolled"); let rows = frame_lines(&board, 120, 20); let bottom = &rows[rows.len() - 1]; assert!( !bottom.contains("pg "), "an indicator over a description that fits: {bottom:?}" ); } /// A campaign with no description is reachable and spends its rows on the placeholder. /// The rows are taken either way, and an empty frame reads as one that failed to draw. #[test] fn a_campaign_with_no_description_is_reachable_and_shows_its_placeholder() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", ""); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "In v1", &campaign_field(V1), ); let mut board = one_board(&dir); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); let rows = frame_lines(&board, 120, 20); assert!( rows[1].contains(DESCRIPTION.placeholder), "no placeholder on an empty frame: {:?}", rows[1] ); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "an empty frame was unreachable"); } /// The footer describes the keys that work where the selection is, which on the frame /// is a different list. What it must never do is name a key by what it used to do. #[test] fn the_footer_names_the_keys_that_work_on_the_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); let row = footer(&board, 120, 20); assert!(row.contains("↓ board"), "no way back to the cards named:\n{row}"); assert!(row.contains("pgup/pgdn scroll"), "the scroll keys are not named:\n{row}"); assert!(row.contains("y copy id"), "the copy key is not named:\n{row}"); // Both do nothing here, so neither is offered. assert!(!row.contains("↵ detail"), "↵ is named and does nothing:\n{row}"); assert!( !row.contains("←→ column"), "the column keys are named and do nothing:\n{row}" ); // And the last slot still answers how to get out, which from here is `ctrl-c`. assert!(row.contains("ctrl-c quit"), "nothing says what quits from here:\n{row}"); } /// No card is selected while the frame holds the selection, and none is drawn as if it /// were: that highlight is what says which ticket `enter` is about. #[test] fn no_card_is_selected_while_the_frame_holds_the_selection() { let dir = board_dir(); let mut board = frame_board(&dir, 40); assert!( a_card_is_highlighted(&board, 120, 20), "nothing was picked out to begin with" ); board.select_card(-1, SCREEN); assert!(board.selected().is_none(), "a card was handed back from the frame"); assert!(!a_card_is_highlighted(&board, 120, 20), "a card is still drawn picked out"); // `enter` reaches the frame's own height now rather than the overlay, but the // overlay is still what it does not open: there is no ticket here to open. board.toggle_focused(SCREEN); assert!(board.detail.is_none(), "enter opened a ticket nothing was selecting"); board.toggle_focused(SCREEN); board.select_card(1, SCREEN); assert!(a_card_is_highlighted(&board, 120, 20), "the highlight did not come back"); } /// `y` copies the id of what is selected in every state the selection can be in, and on /// the frame that is the campaign whose id the top border prints. #[test] fn the_copy_key_takes_the_campaigns_id_from_the_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); assert_eq!(board.copy_text().as_deref(), Some(short_id(V1)), "not the campaign's id"); board.select_card(1, SCREEN); assert_eq!( board.copy_text().as_deref(), Some(short_id("11111111-0000-4000-8000-000000000000")), "back on the cards it is not the ticket's id" ); } /// Left and right do nothing on the frame. It spans the width of the board, so there is /// nothing beside it, and moving the column underneath would change nothing on screen /// until the selection came back down. #[test] fn the_column_keys_are_inert_while_the_frame_holds_the_selection() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_column(1, SCREEN); board.select_card(-1, SCREEN); board.select_column(1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "a column key left the frame"); assert_eq!(board.current().column, 1, "a column key moved where down comes back to"); } /// `q` gives the whole board back from the frame, as it does from the columns: the /// frame is the campaign filter drawn, so taking it off is taking the filter off. #[test] fn q_gives_the_whole_board_back_from_the_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); board.dismiss(SCREEN); assert_eq!(board.current().filter.campaign(), None, "the campaign is still selected"); assert_eq!( board.current().focus, Focus::Cards, "the selection is on a frame nothing draws" ); assert!(!board.should_quit, "the board quit out from under the frame"); let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4, "the whole board did not come back"); } /// A jump lands on a card, so it takes the selection off the frame: `/` reaching a /// ticket the frame still held would leave the highlight where none of the keys that /// act on a ticket do anything. #[test] fn a_jump_takes_the_selection_off_the_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); board.open_search(); for c in "Also".chars() { board.search_key(letter(c), SCREEN); } board.search_key(typed(KeyCode::Enter), SCREEN); assert_eq!( board.current().focus, Focus::Cards, "the jump left the selection on the frame" ); assert_eq!(selected_title(&board).as_deref(), Some("Also in v1")); } /// The offset is the tab's, beside the filter, since the filter is per tab: how far into /// a description a reader has got is a fact about the tab drawing it. #[test] fn the_frame_offset_is_the_tabs_own() { let one = board_dir(); let two = board_dir(); write_campaign(&one, V1, "First public release", "v1", &long_description(40)); write_ticket( &one, "backlog", "11111111-0000-4000-8000-000000000000", "In v1", &campaign_field(V1), ); write_ticket(&two, "backlog", "77777777-0000-4000-8000-000000000000", "Elsewhere", ""); let mut board = boards(&[("one", &one), ("two", &two)]); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); board.select_card(-1, SCREEN); board.scroll_page(1, SCREEN); let at = board.current().frame_offset; assert!(at > 0, "the merge tab's frame did not scroll"); board.select_tab(2, SCREEN); assert_eq!(board.current().frame_offset, 0, "the offset came across to another tab"); assert_eq!(board.current().focus, Focus::Cards, "so did the focus"); board.select_tab(-2, SCREEN); assert_eq!(board.current().frame_offset, at, "the tab did not keep its place"); assert_eq!(board.current().focus, Focus::Frame, "the tab did not keep its focus"); } /// Changing the filter puts the frame back at the top, the answer `refresh_detail` /// gives the overlay when the ticket under it changes: it is a different campaign's /// description, and a reader opening on line 20 of it is reading nothing. #[test] fn changing_the_filter_puts_the_frame_back_at_the_top() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); board.scroll_page(1, SCREEN); assert!(board.current().frame_offset > 0, "nothing scrolled"); board.select_filter(Filter::Campaign(BEAVER.to_string()), SCREEN); assert_eq!(board.current().frame_offset, 0, "the new campaign opened partway down"); assert_eq!(board.current().focus, Focus::Cards, "the selection stayed on the frame"); } // ---------------------------------------------------- the frame's two heights -- /// The frame's page indicator, or nothing when it is not drawn. /// /// Cut out of the bottom border, where it sits between `q board` and the standing, so a /// test can say the frame repaged without knowing what the numbers should be. fn frame_indicator(board: &Board, width: u16, height: u16) -> Option { let rows = frame_lines(board, width, height); let bottom = rows.last().expect("no frame drawn").clone(); let at = bottom.find("pg ")?; Some(bottom[at..].split('─').next()?.trim().to_string()) } /// The rows the frame takes, as the layout gives them out. fn frame_height(board: &Board, screen: Size) -> u16 { screen_rows(Rect::new(0, 0, screen.width, screen.height), board.chrome())[FRAME_ROW].height } /// `enter` on the frame gives its prose half the board, and `enter` again gives the rows /// back. A toggle, so the key that expands is the key that collapses. #[test] fn enter_expands_the_frame_and_enter_again_gives_the_rows_back() { let dir = board_dir(); let mut board = frame_board(&dir, 60); let collapsed = frame_height(&board, SCREEN); assert_eq!(collapsed, Chrome::FRAME_ROWS, "the board did not open collapsed"); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); let expanded = frame_height(&board, SCREEN); assert!(board.current().expanded, "the tab does not think it expanded"); assert!(expanded > collapsed, "the frame did not grow: {expanded} rows"); board.toggle_focused(SCREEN); assert!(!board.current().expanded, "the tab did not collapse"); assert_eq!(frame_height(&board, SCREEN), collapsed, "the rows did not come back"); } /// And only from the frame. `enter` on a card is the overlay's, which is what the routing /// in `toggle_focused` is for. #[test] fn enter_on_a_card_opens_the_ticket_rather_than_the_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.toggle_focused(SCREEN); assert!(board.detail.is_some(), "enter did not open the ticket"); assert!(!board.current().expanded, "enter on a card expanded the frame"); board.toggle_focused(SCREEN); assert!(board.detail.is_none(), "enter did not close the ticket"); } /// Half of what the frame and the columns divide, which is the screen less the tab row /// and the footer. Half rather than most of it: the columns below are the campaign's /// members, and a reader inspecting the campaign has to go on seeing what it is made of. #[test] fn the_expanded_frame_takes_half_of_what_it_shares_with_the_columns() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); let shared = SCREEN.height - FOOTER_ROWS; assert_eq!(frame_height(&board, SCREEN), shared / 2, "not half of the shared rows"); // The odd row goes to the cards, and the two of them plus the footer are the screen. let columns = board_area(SCREEN, board.chrome()).height; assert!(columns >= shared / 2, "the cards did not keep the odd row"); assert_eq!(frame_height(&board, SCREEN) + columns + FOOTER_ROWS, SCREEN.height); } /// The share is bounded at both ends, and a sweep is what says so rather than one screen /// that happens to work. Expanding must never shrink the frame, and must never take rows /// the columns are reserved: `Constraint::Min` would take them back silently, and the /// measurement here would then disagree with what is drawn. #[test] fn the_expanded_share_is_bounded_at_both_ends() { for height in 4..=60u16 { for tabbed in [false, true] { let chrome = Chrome { tabbed, frame: Some(FrameSize::Expanded), }; let rows = chrome.frame_rows(height); let shared = height.saturating_sub(u16::from(tabbed) + FOOTER_ROWS); assert!( rows >= Chrome::FRAME_ROWS, "expanding shrank the frame to {rows} rows at height {height}" ); // Only where the board can hold both. Below that the frame is pinned to its // collapsed height and the layout is what apportions what is left. if shared >= Chrome::FRAME_ROWS + COLUMN_MIN_ROWS { assert!( shared - rows >= COLUMN_MIN_ROWS, "the columns kept {} rows at height {height}", shared - rows ); } } } } /// A board too short to divide gives the collapsed frame back rather than a height /// nothing measured. #[test] fn a_board_too_short_to_divide_stays_at_the_collapsed_height() { let short = Size { width: 80, height: 10 }; let chrome = Chrome { tabbed: false, frame: Some(FrameSize::Expanded), }; assert_eq!(chrome.frame_rows(short.height), Chrome::FRAME_ROWS); } /// Every measurement of the board agrees about the expanded height. That is what `Chrome` /// is for: a keypress that scrolled against the taller board would put the selection /// where the next frame does not draw it. #[test] fn every_measurement_agrees_about_the_expanded_height() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); let rows = screen_rows(Rect::new(0, 0, SCREEN.width, SCREEN.height), board.chrome()); let total: u16 = rows.iter().map(|row| row.height).sum(); assert_eq!(total, SCREEN.height, "the rows do not add up to the screen"); // The keypress measures the prose off the screen and the draw off the area it is // given. Two answers here is how a scroll comes to clamp against a frame nobody drew. assert_eq!( frame_text_area(SCREEN, board.chrome()), rows[FRAME_ROW].inner(Margin::new(1, 1)), "the keypress and the draw measure different prose" ); assert_eq!(board_area(SCREEN, board.chrome()), rows[BOARD_ROW]); assert_eq!( column_text_height(SCREEN, board.chrome()), rows[BOARD_ROW].height - 2, "the cards are laid out against a column of another height" ); } /// The scroll keys go on doing what they do, and the indicator repages: the step and the /// clamp are both measured off the viewport, so both move when the frame does. #[test] fn the_scroll_keys_page_through_the_expanded_frame_and_the_indicator_repages() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); let collapsed = frame_indicator(&board, 120, 20).expect("no indicator collapsed"); board.toggle_focused(SCREEN); let expanded = frame_indicator(&board, 120, 20).expect("no indicator expanded"); assert_ne!(collapsed, expanded, "the indicator did not repage: {expanded}"); assert!(expanded.starts_with("pg 1/"), "not on the first page: {expanded}"); board.scroll_page(1, SCREEN); assert!(board.current().frame_offset > 0, "the expanded frame did not scroll"); let moved = frame_indicator(&board, 120, 20).expect("the indicator went away"); assert!(moved.starts_with("pg 2/"), "the indicator did not follow: {moved}"); // And the clamp is still the wrapped prose, not blank rows past the end of it. board.scroll_page(40, SCREEN); let text = frame_text_area(SCREEN, board.chrome()); let last = last_offset( &campaign_prose(board.current().selected_campaign().expect("no campaign")), text, ); assert_eq!(board.current().frame_offset, last, "the scroll ran past the description"); } /// A description that did not fit the collapsed frame and does fit the expanded one /// spends no indicator and leaves the keys inert, the answer ebad2fa gave for a short /// description in a collapsed frame. #[test] fn a_description_that_fits_the_expanded_frame_spends_no_indicator() { let dir = board_dir(); let mut board = frame_board(&dir, 5); board.select_card(-1, SCREEN); assert!(frame_indicator(&board, 120, 20).is_some(), "five lines fit three rows"); board.toggle_focused(SCREEN); assert_eq!(frame_indicator(&board, 120, 20), None, "an indicator over prose that fits"); board.scroll_page(1, SCREEN); assert_eq!(board.current().frame_offset, 0, "prose that fits scrolled"); } /// A description that fits the collapsed frame expands anyway. A key that worked on one /// campaign and not the next is worse than one that sometimes has little to reveal, which /// is the trade the scroll keys already take. #[test] fn a_short_description_still_expands_the_frame() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); assert!(board.current().expanded, "a one line description refused to expand"); assert!(frame_height(&board, SCREEN) > Chrome::FRAME_ROWS, "the frame did not grow"); } /// `q` takes the campaign filter off from an expanded frame exactly as it does from a /// collapsed one. The expanded frame is the frame at its other height, not a layer laid /// over the board, so it is not a press the reader has to spend on the way out. #[test] fn q_takes_the_filter_off_from_an_expanded_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); assert!(board.current().expanded, "nothing expanded"); board.dismiss(SCREEN); assert_eq!(board.current().filter.campaign(), None, "q was spent collapsing the frame"); assert!(!board.current().expanded, "the height outlived the frame"); assert!(!board.should_quit, "the board quit out from under the frame"); let all: usize = board.current().columns.iter().map(|c| c.cards.len()).sum(); assert_eq!(all, 4, "the whole board did not come back"); } /// Up and down leave the height where it was. The reader chose a view of the campaign; /// moving the selection off it is not asking for the view back. #[test] fn up_and_down_leave_the_frame_at_the_height_it_was() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); let expanded = frame_height(&board, SCREEN); board.select_card(1, SCREEN); assert_eq!(board.current().focus, Focus::Cards, "down did not leave the frame"); assert!(board.current().expanded, "down collapsed the frame"); assert_eq!(frame_height(&board, SCREEN), expanded, "the columns took the rows back"); board.select_card(-1, SCREEN); assert!(board.current().expanded, "up changed the height"); } /// The footer says which of the two `enter` is about to do, since the key is a toggle and /// the frame is already at one of its heights. ebad2fa left it out of this row because it /// did nothing here. #[test] fn the_footer_says_which_way_enter_will_go_on_the_frame() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); let row = footer(&board, 120, 20); assert!(row.contains("↵ expand"), "↵ is not named on the frame:\n{row}"); board.toggle_focused(SCREEN); let row = footer(&board, 120, 20); assert!(row.contains("↵ collapse"), "↵ still offered as expand:\n{row}"); assert!(!row.contains("↵ expand"), "the row names it both ways:\n{row}"); } /// Expanding and collapsing leave the reader where they were rather than at the top. The /// offset has to be re-clamped as the height changes, since a taller viewport has a /// smaller last offset than a shorter one. #[test] fn expanding_and_collapsing_leave_the_reader_where_they_were() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); board.scroll_page(1, SCREEN); let at = board.current().frame_offset; assert!(at > 0, "nothing scrolled"); board.toggle_focused(SCREEN); assert!(board.current().frame_offset > 0, "expanding went back to the top"); // And the stored offset is inside the taller viewport, not left past its end where // the next pgup would count down from a number the frame never showed. let text = frame_text_area(SCREEN, board.chrome()); let last = last_offset( &campaign_prose(board.current().selected_campaign().expect("no campaign")), text, ); assert!(board.current().frame_offset <= last, "the offset sits past the end"); board.toggle_focused(SCREEN); assert!(board.current().frame_offset > 0, "collapsing went back to the top"); } /// The height is the tab's own, beside the filter it belongs to, so switching away and /// back returns to it. #[test] fn the_expanded_frame_is_the_tabs_own() { let one = board_dir(); let two = board_dir(); write_campaign(&one, V1, "First public release", "v1", &long_description(60)); write_ticket( &one, "backlog", "11111111-0000-4000-8000-000000000000", "In v1", &campaign_field(V1), ); write_ticket(&two, "backlog", "77777777-0000-4000-8000-000000000000", "Elsewhere", ""); let mut board = boards(&[("one", &one), ("two", &two)]); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); assert!(board.current().expanded, "nothing expanded"); board.select_tab(2, SCREEN); assert!(!board.current().expanded, "the height came across to another tab"); board.select_tab(-2, SCREEN); assert!(board.current().expanded, "the tab did not keep its height"); } /// And selecting another campaign opens its frame collapsed, the answer `select_campaign` /// already gives the offset and the focus: it is a different description, and a reader /// who did not ask for half the board should not be given it. #[test] fn selecting_another_campaign_opens_its_frame_collapsed() { let dir = board_dir(); let mut board = frame_board(&dir, 60); board.select_card(-1, SCREEN); board.toggle_focused(SCREEN); board.select_filter(Filter::Campaign(BEAVER.to_string()), SCREEN); assert!(!board.current().expanded, "the new campaign opened at half the board"); assert_eq!(frame_height(&board, SCREEN), Chrome::FRAME_ROWS); } /// A campaign that leaves the board takes the frame with it, focus and offset both: the /// filter goes back to the whole board, and a frame nothing draws must not be holding /// the selection. #[test] fn a_campaign_that_leaves_the_board_takes_the_frame_with_it() { let dir = board_dir(); let mut board = frame_board(&dir, 40); board.select_card(-1, SCREEN); board.scroll_page(1, SCREEN); std::fs::remove_file(dir.join(CAMPAIGNS_DIR).join(format!( "{}_{}.md", V1, slug("First public release") ))) .unwrap(); assert!( board.tick().expect("the reload failed"), "the campaign file is not watched" ); assert_eq!(board.current().filter.campaign(), None, "the filter survived its campaign"); assert_eq!( board.current().focus, Focus::Cards, "the selection is on a frame nothing draws" ); assert_eq!(board.current().frame_offset, 0, "the offset outlived the description"); } /// `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_filter(Filter::Campaign(V1.to_string()), SCREEN); board.dismiss(SCREEN); assert_eq!(board.current().filter.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"); } /// 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_filter(Filter::Campaign(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().filter.campaign(), Some(V1), "the filter came off too"); } /// 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_filter(Filter::Campaign(BEAVER.to_string()), SCREEN); assert!(board.detail.is_none(), "the overlay survived the filter"); } /// 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(PickerKind::Campaign, SCREEN); for code in [KeyCode::Char('d'), KeyCode::Char('y'), KeyCode::Char('/')] { assert!( board.picker_key(KeyEvent::new(code, KeyModifiers::NONE), SCREEN), "the picker let {code:?} through" ); } assert_eq!(board.visibility, Visibility::Neither, "d reached the columns"); assert!(board.picker.is_some(), "the picker closed on a key it does not use"); // `/` last, and taken by the picker's own query rather than by the board's prompt: // the key that searches a list of cards searches this list, and the two must not // both be open. assert!(board.search.is_none(), "/ opened the board's prompt"); assert_eq!(query_of(&board).as_deref(), Some(""), "/ opened no query"); // Every other control combination is swallowed and does nothing, or `ctrl-d` would // reach the arm bound to `d`. board.picker_key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL), SCREEN); assert_eq!(board.visibility, Visibility::Neither, "ctrl-d reached the columns"); } /// `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(PickerKind::Campaign, SCREEN); assert!( !board.picker_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL), SCREEN) ); } /// 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(PickerKind::Campaign, SCREEN); // 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().filter.campaign(), Some(BEAVER)); } /// 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_filter(Filter::Campaign(V1.to_string()), SCREEN); board.open_picker(PickerKind::Campaign, SCREEN); 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().filter.campaign(), Some(V1), "the filter moved"); } /// 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_filter(Filter::Campaign(V1.to_string()), SCREEN); board.open_picker(PickerKind::Campaign, SCREEN); let held = board.picked(); assert_eq!( held.as_ref().map(PickerKey::name), Some(V1), "the highlight is on no campaign" ); } /// 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(PickerKind::Campaign, SCREEN); 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"); } /// 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(PickerKind::Campaign, SCREEN); 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("↵ view"), "the footer is the board's"); } /// The list is where a campaign is chosen from, so how far each has got belongs on the /// row rather than only on the frame: `0/2` after the summary, where a card draws its /// criteria count. #[test] fn the_picker_rows_carry_the_standing() { let dir = board_dir(); let mut board = campaign_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_rows(&board, 100, 24); // V1 holds two open members, so two done of two held is not reached. let v1 = &rows[row_with(&rows, short_id(V1))]; assert!(v1.contains("0/2"), "{v1:?}"); // BEAVER holds one open member. let beaver = &rows[row_with(&rows, short_id(BEAVER))]; assert!(beaver.contains("0/1"), "{beaver:?}"); } /// A campaign with no members has no standing to show, the way a card with no criteria /// spends no corner on it: the row ends at the summary. #[test] fn a_picker_row_with_no_members_shows_no_standing() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "For a public tag."); let mut board = one_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_rows(&board, 100, 24); let row = &rows[row_with(&rows, short_id(V1))]; assert!(!row.contains('/'), "a blank campaign claimed a standing: {row:?}"); } /// The standing gives way before the identity and the prose, and goes whole: half a /// count reads as the wrong number, the rule a corner drops itself by. #[test] fn a_campaign_row_drops_the_standing_whole_when_it_will_not_fit() { let dir = board_dir(); write_campaign(&dir, V1, "First public release", "v1", "Everything for a public tag."); write_member_card(&dir, "In v1", "cli", V1); let mut board = one_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let full = picker_rows(&board, 100, 24); let wide = &full[row_with(&full, short_id(V1))]; assert!(wide.contains('/'), "no standing on a wide row: {wide:?}"); let narrow = picker_rows(&board, 14, 24); let tight = &narrow[row_with(&narrow, short_id(V1))]; assert!(!tight.contains('/'), "a count given up in pieces: {tight:?}"); } /// 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(PickerKind::Campaign, SCREEN); 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:?}"); } /// 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")); } /// 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_filter(Filter::Campaign(V1.to_string()), SCREEN); std::fs::remove_dir_all(dir.join(CAMPAIGNS_DIR)).unwrap(); board.reload().unwrap(); assert_eq!(board.current().filter.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"); } /// One flat list ordered by title put the completed campaigns among the open ones /// forever. The tail only grows, so the campaigns worth picking were pushed towards the /// bottom of the picker and eventually off it by the ones that are finished. #[test] fn the_picker_draws_open_campaigns_above_completed() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_rows(&board, 100, 24); let open = row_at(&rows, OPEN_SECTION); let completed = row_at(&rows, COMPLETED_SECTION); assert!(open < completed, "completed came first: {rows:?}"); // An open campaign is under the first heading and a completed one under the second, // which is the whole of the split. let v1 = row_with(&rows, short_id(V1)); let audit = row_with(&rows, short_id(FINISHED[3].0)); assert!(open < v1 && v1 < completed, "an open campaign under completed: {rows:?}"); assert!(completed < audit, "a completed campaign under open: {rows:?}"); // A heading is chrome, and grey is what the guideline gives to what a reader skips. assert_eq!(picker_row_color(&board, open, 100, 24), Color::Grey.into()); } /// `Standing::state` calls a campaign with no members neither open nor done. For the /// split it lists under open, because completed means every member is done and it holds /// none to be done. #[test] fn a_campaign_is_completed_only_when_it_holds_members_and_every_one_is_done() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let campaigns = &board.current().campaigns; let beaver = campaigns .iter() .find(|row| row.uuid == BEAVER) .expect("no beaver"); assert_eq!((beaver.standing.done, beaver.standing.total), (0, 0)); assert!(!beaver.completed(), "a campaign with no members read as completed"); let audit = campaigns .iter() .find(|row| row.uuid == FINISHED[3].0) .expect("no tag audit"); assert_eq!((audit.standing.done, audit.standing.total), (1, 1)); assert!(audit.completed(), "every member done and still open"); // And the drawn list agrees: the empty one is above the completed heading. let rows = picker_rows(&board, 100, 24); assert!( row_with(&rows, short_id(BEAVER)) < row_at(&rows, COMPLETED_SECTION), "a campaign with no members listed as completed: {rows:?}" ); } /// The completed tail is truncated to the couple most recently filed, and the line under /// them says how many are being kept back: rows that are simply gone read as a board /// that never held them. #[test] fn the_completed_section_keeps_the_most_recent_and_names_what_it_hid() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_rows(&board, 100, 24); // By `Created At` newest first, and not by title: "Disk migration" and "Log rework" // are the two that would survive an alphabetical order. for (campaign, _, title, _) in [FINISHED[3], FINISHED[2]] { assert!( rows.iter().any(|row| row.contains(short_id(campaign))), "{title} was hidden: {rows:?}" ); } for (campaign, _, title, _) in [FINISHED[1], FINISHED[0]] { assert!( !rows.iter().any(|row| row.contains(short_id(campaign))), "{title} survived the truncation: {rows:?}" ); } let hidden = row_with(&rows, "older completed"); assert!( rows[hidden].contains("2 older completed campaigns hidden"), "the line does not say how many: {:?}", rows[hidden] ); assert_eq!(picker_row_color(&board, hidden, 100, 24), Color::Grey.into()); } /// One campaign hidden is one campaign, since a line that misspells what it is counting /// is read twice before it is believed. #[test] fn the_truncation_line_counts_one_hidden_campaign_in_the_singular() { assert_eq!(hidden_line(1), "… 1 older completed campaign hidden"); assert_eq!(hidden_line(2), "… 2 older completed campaigns hidden"); } /// `/` is the key that searches a list of cards, so it is the key that searches a list /// of campaigns. Id, codename and title, case insensitively, which is the three things /// the row draws and the three a campaign is chosen by. #[test] fn a_query_filters_the_picker_by_id_codename_and_title() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); // The codename, in the wrong case, since a query that has to be typed exactly is // not worth typing. type_picker_query(&mut board, "BEAV"); assert_eq!(picked_ids(&board), vec![BEAVER.to_string()], "the codename missed"); // The title, in the middle of it. board.picker = None; board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, "public rel"); assert_eq!(picked_ids(&board), vec![V1.to_string()], "the title missed"); // And the short id the row opens with. board.picker = None; board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, short_id(FINISHED[3].0)); assert_eq!(picked_ids(&board), vec![FINISHED[3].0.to_string()], "the id missed"); } /// The summary is drawn on the row but is not what the row is chosen by: a query that /// matched prose would answer "disk" with every campaign whose description mentions one. #[test] fn a_query_does_not_match_the_summary_the_row_draws() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); // Beaver's summary reads "Move the store off one disk." and its title does not. type_picker_query(&mut board, "disk"); assert_eq!(picked_ids(&board), vec![FINISHED[0].0.to_string()], "the summary matched"); } /// A search reaches the whole completed tail, untruncated, which is the point of having /// one: the campaign a reader is looking for is exactly the one the truncation hid. #[test] fn a_query_finds_the_completed_campaigns_the_truncation_hid() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let hidden = FINISHED[0].0; assert!( !picker_rows(&board, 100, 24) .iter() .any(|row| row.contains(short_id(hidden))), "the oldest was not hidden to begin with" ); type_picker_query(&mut board, "migration"); let rows = picker_rows(&board, 100, 24); assert!( rows.iter().any(|row| row.contains(short_id(hidden))), "the query did not reach the truncated tail: {rows:?}" ); assert!( !rows.iter().any(|row| row.contains("older completed")), "the query left the truncation on: {rows:?}" ); } /// While the query is open the picker still owns the keyboard, so `q` types rather than /// closing anything, and `esc` takes the query off before it takes the picker off: one /// layer at a time, the order `dismiss` closes the board's own layers in. #[test] fn the_query_takes_q_and_esc_closes_it_before_the_picker() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, "q"); assert!(board.picker.is_some(), "q closed the picker"); assert_eq!(query_of(&board).as_deref(), Some("q"), "q did not type"); // Backspace edits it in place rather than closing it, the way the search prompt's // does: a query worth correcting is not a query worth retyping. press(&mut board, KeyCode::Backspace); assert_eq!(query_of(&board).as_deref(), Some(""), "backspace closed the query"); press(&mut board, KeyCode::Esc); assert!(board.picker.is_some(), "esc closed the picker with a query open"); assert_eq!(query_of(&board), None, "the query outlived the esc"); press(&mut board, KeyCode::Esc); assert!(board.picker.is_none(), "the second esc left the picker open"); } /// Enter takes the highlighted row whether a query is open or not: filtering is how the /// row is found, not a different way of taking it. #[test] fn enter_under_a_query_takes_the_highlighted_campaign() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, "beav"); assert_eq!( highlighted(&board).as_deref(), Some(BEAVER), "the highlight missed the match" ); press(&mut board, KeyCode::Enter); assert!(board.picker.is_none(), "the picker stayed open"); assert_eq!(board.current().filter.campaign(), Some(BEAVER)); } /// A query that matches nothing keeps the picker and the query open, and says so in the /// box rather than leaving an empty one: the query can then be corrected in place, /// which is what the search prompt does with a miss. #[test] fn a_query_that_matches_nothing_keeps_the_picker_and_the_query_open() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, "zzz"); let rows = picker_rows(&board, 100, 24); assert!(rows[0].contains("no match"), "an empty box says nothing: {rows:?}"); assert_eq!(picker_row_color(&board, 0, 100, 24), Color::BrightRed.into()); press(&mut board, KeyCode::Enter); assert!(board.picker.is_some(), "enter on a miss closed the picker"); assert_eq!(query_of(&board).as_deref(), Some("zzz"), "the query was taken away"); assert_eq!(board.current().filter.campaign(), None, "a miss selected something"); } /// Section headings and the truncation line take no number: they are not campaigns, so /// a highlight resting on one would give enter nothing to do. The no-campaign row is not /// chrome, though — it takes the highlight when the walk reaches it, but never the /// opening one. #[test] fn the_highlight_moves_over_campaigns_and_never_onto_the_chrome() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); // It opens on the first campaign, not on the no-campaign row or the heading between // them: campaigns are what this list opens for. assert_eq!(board.picker.as_ref().expect("no picker").row, 2); // Down until it stops, which is the last campaign and not the truncation line under // it. Four campaigns are drawn: two open, and the two the truncation kept. let mut walked = vec![highlighted(&board).expect("the highlight opened on chrome")]; loop { let before = board.picker.as_ref().expect("no picker").row; press(&mut board, KeyCode::Down); if board.picker.as_ref().expect("no picker").row == before { break; } walked.push(highlighted(&board).expect("the highlight landed on chrome")); } assert_eq!(walked.len(), 4, "{walked:?}"); assert_eq!(walked[0], BEAVER, "the list is not in the index's order: {walked:?}"); assert_eq!(walked[3], FINISHED[2].0, "the walk stopped short: {walked:?}"); // And back up is the same walk in reverse, over the second heading rather than onto // it — ending one further than it began, on the row above the list rather than on // its heading. let mut back = Vec::new(); loop { let before = board.picker.as_ref().expect("no picker").row; press(&mut board, KeyCode::Up); if board.picker.as_ref().expect("no picker").row == before { break; } back.push(highlighted(&board).expect("the highlight landed on chrome")); } back.reverse(); assert_eq!(back[1..], walked[..3], "the walk back is not the walk out"); assert_eq!(back[0], NO_CAMPAIGN_ROW, "the walk back stopped short of the pile"); } /// The highlight follows the campaign it was on rather than the number it was at: a /// query reshapes the list, and a number kept across that names whichever campaign now /// sits at it. #[test] fn the_highlight_follows_its_campaign_through_a_query() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); press(&mut board, KeyCode::Down); assert_eq!(highlighted(&board).as_deref(), Some(V1), "down did not reach v1"); // Still a match, so it stays on it however far the row has moved. type_picker_query(&mut board, "release"); assert_eq!(highlighted(&board).as_deref(), Some(V1), "the highlight left its campaign"); // And back to the whole list, still on it. press(&mut board, KeyCode::Esc); assert_eq!(highlighted(&board).as_deref(), Some(V1), "clearing the query lost it"); } /// A query that excludes the highlighted campaign drops the highlight to the first row /// that does match, which is where an incremental filter puts it. #[test] fn a_query_that_excludes_the_highlight_moves_it_to_the_first_match() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); assert_eq!(highlighted(&board).as_deref(), Some(BEAVER)); type_picker_query(&mut board, "polish"); assert_eq!(highlighted(&board).as_deref(), Some(FINISHED[2].0)); } /// The footer is the picker's while it is open, and the query's while that is open: with /// every printable key going into a buffer, a list of keys describes nothing that works. #[test] fn the_picker_footer_names_the_search_key_and_then_becomes_the_query() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); assert!(footer(&board, 100, 24).contains("/ search"), "the key is unfindable"); type_picker_query(&mut board, "beav"); let row = footer(&board, 100, 24); assert!(row.contains("/beav"), "the query is not on the row: {row:?}"); assert!(row.contains("esc clear"), "the row does not say what esc does: {row:?}"); assert!(!row.contains("/ search"), "the row names a key that types: {row:?}"); } /// The bare count is what the box is. A query that cuts the list down makes the total /// alone a lie about what is on screen, so the title says both. #[test] fn the_picker_title_says_how_many_a_query_left() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let title = |board: &Board| { let picker = board.picker.as_ref().expect("no picker"); picker_title(board.current(), picker) }; assert_eq!(title(&board), " campaigns (6) "); type_picker_query(&mut board, "migration"); assert_eq!(title(&board), " campaigns (2 of 6) "); } /// The standing on every row is settled at reload, off the cards the reload already /// holds. A walk of the status directories per campaign is what `campaign ls` pays and /// what a keypress must not. #[test] fn the_standings_are_read_when_the_cards_are_and_not_per_draw() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); // Taken away after the board was built, so a standing that asked the filesystem // again would have nothing left to ask it. for status in Status::ALL { std::fs::remove_dir_all(dir.join(status.as_str())).unwrap(); } let rows = picker_rows(&board, 100, 24); assert!( rows.iter().any(|row| row.trim() == COMPLETED_SECTION), "the split was recounted per draw: {rows:?}" ); assert!( rows.iter().any(|row| row.contains(short_id(FINISHED[3].0))), "a completed campaign left the section: {rows:?}" ); } /// Paired with the test above, which would pass by never asking the filesystem again: /// a member finished elsewhere has to move its campaign into the completed section, and /// the reload is what recounts. #[test] fn a_member_finished_after_the_board_was_built_completes_its_campaign() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_rows(&board, 100, 24); assert!( row_with(&rows, short_id(V1)) < row_at(&rows, COMPLETED_SECTION), "v1 was completed to begin with: {rows:?}" ); // Its one member moves to done, which is the whole of the campaign finishing. let member = "11111111-0000-4000-8000-000000000000"; let from = dir .join("backlog") .join(format!("{member}_{}.md", slug("In v1"))); std::fs::rename(&from, dir.join("done").join(format!("{member}_{}.md", slug("In v1")))) .unwrap(); assert!(board.tick().unwrap(), "the tick saw nothing"); let campaigns = &board.current().campaigns; let v1 = campaigns.iter().find(|row| row.uuid == V1).expect("no v1"); assert_eq!((v1.standing.done, v1.standing.total), (1, 1), "the standing did not move"); assert!(v1.completed(), "a campaign whose every member is done stayed open"); } /// The highlight survives a tick, on the campaign rather than on the number: one filed /// or finished elsewhere splits the list differently, so the row that held it moves. #[test] fn the_highlight_survives_a_campaign_filed_under_an_open_picker() { let dir = board_dir(); let mut board = tail_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); press(&mut board, KeyCode::Down); assert_eq!(highlighted(&board).as_deref(), Some(V1)); // Filed first alphabetically, so every open row below it moves down one. write_campaign(&dir, "eeeeeeee-0000-4000-8000-000000000000", "Aardvark", "aa", "New."); assert!(board.tick().unwrap(), "the tick saw nothing"); assert_eq!( highlighted(&board).as_deref(), Some(V1), "the highlight held its row rather than its campaign" ); } /// A board whose picker list is taller than a short window draws, with the campaign /// filtered onto sitting at its foot: the shape where reaching the highlight takes /// scrolling, and `c` on the filtered board looks like `c` on any other until the /// highlight is actually inside the box. /// /// Fourteen numbered campaigns sort above it, so the deep one is the last open row; /// with no members anywhere nothing completes, so there is no completed section /// either and the arithmetic stays fixed. fn deep_picker_board(dir: &Path) -> Board { for n in 1..=14 { write_campaign( dir, &format!("{n:02}aaaaaa-0000-4000-8000-000000000000"), &format!("Campaign {n:02}"), &format!("c{n:02}"), "Filler.", ); } write_campaign( dir, "ffff9999-0000-4000-8000-000000000000", "Zeppelin survey", "zeppelin", "The one far down.", ); let mut board = one_board(dir); board .select_filter(Filter::Campaign("ffff9999-0000-4000-8000-000000000000".into()), SCREEN); board } /// The picker opens with the highlight inside the drawn window, whatever row the /// selected campaign sits on. #[test] fn the_picker_opens_with_the_highlight_inside_the_window() { let dir = board_dir(); let mut board = deep_picker_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_rows(&board, 100, 20); let deep = short_id("ffff9999-0000-4000-8000-000000000000"); assert!( rows.iter().any(|row| row.contains(deep)), "the highlighted campaign opened below the fold: {rows:?}" ); } /// The draw brings the highlight into the window on its own geometry, so a terminal /// resized between the keypress that aligned and this frame cannot hide it. Opening /// against a tall screen leaves an offset sized to the old window; the draw corrects /// it without a keypress, the way the draw follows the selected card in a column. #[test] fn a_resize_between_open_and_frame_cannot_hide_the_highlight() { let dir = board_dir(); let mut board = deep_picker_board(&dir); let tall = Size { width: 100, height: 60 }; board.open_picker(PickerKind::Campaign, tall); // Everything fits the tall window, so nothing but the resize stands between the // offset and the top of the list. assert_eq!(board.picker.as_ref().unwrap().offset, 0); let rows = picker_rows(&board, 100, 20); let deep = short_id("ffff9999-0000-4000-8000-000000000000"); assert!( rows.iter().any(|row| row.contains(deep)), "the draw drew the old window around the highlight: {rows:?}" ); } /// 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_eq!(keys_on(&board, 120, 24, "campaign"), Some(1), "the key is unfindable"); board.select_filter(Filter::Campaign(V1.to_string()), SCREEN); let row = footer(&board, 120, 24); assert!(row.contains("ctrl-c quit"), "q still claims to quit: {row:?}"); assert_eq!(keys_on(&board, 120, 24, "quit"), Some(0), "{row:?}"); } /// 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_filter(Filter::Campaign(V1.to_string()), SCREEN); assert_eq!(board.current().filter.campaign(), Some(V1)); board.select_tab(1, SCREEN); assert_eq!( board.current().filter.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().filter.campaign(), Some(V1)); } // --------------------------------------------------- the no-campaign filter -- /// A board like [`campaign_board`] but with a loose ticket and the finished tail behind /// it, which is what would push the pile down if it were listed among the sections /// instead of above them. fn tailed_campaign_board(dir: &Path) -> Board { write_ticket(dir, "backlog", "66666666-0000-4000-8000-000000000000", "In neither", ""); tail_board(dir) } /// The opposite question to picking a campaign: what is on this board that nobody /// grouped into anything. Every column kept, empty ones included, the rule /// `retain_campaign` holds. #[test] fn picking_no_campaign_filters_every_column_to_the_unset_field() { let dir = board_dir(); let mut board = campaign_board(&dir); board.visibility = Visibility::Both; board.select_filter(Filter::NoCampaign, SCREEN); let headings = headings(&board, 120, 20); assert!(headings.contains("backlog (1)"), "{headings}"); assert!(headings.contains("committed (0)"), "{headings}"); assert!(headings.contains("done (0)"), "{headings}"); } /// A Campaign field naming a uuid no campaign carries is *set* wrongly, not unset: the /// view answers what the field says, and the field does not say nothing here. #[test] fn a_dangling_campaign_uuid_is_set_and_not_unset() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "Dangling", &campaign_field("99999999-0000-4000-8000-000000000000"), ); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Free", ""); let mut board = one_board(&dir); board.select_filter(Filter::NoCampaign, SCREEN); let held: Vec = board.current().columns[0] .cards .iter() .map(|card| card.ticket.title.clone()) .collect(); assert_eq!(held, vec!["Free"], "the dangling uuid read as unset"); } /// First, above both sections, and never truncated: on a board whose completed tail is /// being kept back the pile is still row zero, reachable without scrolling — which is /// the whole reason it is not a member of either list. #[test] fn the_picker_draws_the_pile_above_the_sections_and_never_truncates_it() { let dir = board_dir(); let mut board = tailed_campaign_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_rows(&board, 100, 24); let open = row_at(&rows, OPEN_SECTION); // The count sits where a campaign row's standing sits, saying what picking this // will give before it is pressed. assert!(rows[0].starts_with(NO_CAMPAIGN_ROW), "the pile was not first: {rows:?}"); assert!(rows[0].contains(" 1"), "the count is not on the row: {:?}", rows[0]); assert!(open > 0, "the sections did not follow it: {rows:?}"); } /// A word a reader would type for it finds it; a query naming a campaign hides it like /// any other row; and a query matching nothing at all says so rather than leaving the /// pile up as a consolation row. #[test] fn a_query_finds_the_pile_and_hides_it_like_any_other_row() { let dir = board_dir(); let mut board = tailed_campaign_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); // By the shorter word, which hides every campaign and leaves the pile holding the // highlight, since it is the only thing left to take. type_picker_query(&mut board, "none"); assert_eq!( highlighted(&board).as_deref(), Some(NO_CAMPAIGN_ROW), "the query missed the pile" ); // A query naming a campaign hides it like any other row. board.picker = None; board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, "BEAV"); assert!( !picker_rows(&board, 100, 24)[0].contains(NO_CAMPAIGN_ROW), "the pile survived" ); assert_eq!(picked_ids(&board), vec![BEAVER.to_string()]); // And nothing matched at all. board.picker = None; board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, "zzz"); assert_eq!(highlighted(&board), None, "the miss took a row"); assert!(picker_rows(&board, 100, 24)[0].contains("no match")); } /// Taking the pile from under a query filters to it, which is how the row is found. #[test] fn taking_the_pile_under_a_query_filters_to_it() { let dir = board_dir(); let mut board = tailed_campaign_board(&dir); board.open_picker(PickerKind::Campaign, SCREEN); type_picker_query(&mut board, "none"); press(&mut board, KeyCode::Enter); assert!(board.picker.is_none(), "the picker stayed open"); assert_eq!(board.current().filter, Filter::NoCampaign); } /// Reopening the picker while the pile is selected opens on its row, the courtesy `c` /// pays a filtered board: it says where you are as well as offering somewhere to go. #[test] fn reopening_the_picker_while_the_pile_is_selected_opens_on_its_row() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_filter(Filter::NoCampaign, SCREEN); board.open_picker(PickerKind::Campaign, SCREEN); assert_eq!( highlighted(&board).as_deref(), Some(NO_CAMPAIGN_ROW), "the highlight is elsewhere" ); // And taking it again changes nothing: the filter is what was asked for. press(&mut board, KeyCode::Enter); assert!(board.picker.is_none()); assert_eq!(board.current().filter, Filter::NoCampaign); } /// `q` takes the filter off, as it does a campaign or tag filter, because every filter /// draws the frame whose border names it. #[test] fn q_gives_the_whole_board_back_from_the_no_campaign_filter() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_filter(Filter::NoCampaign, SCREEN); board.dismiss(SCREEN); assert!(board.current().filter.is_whole(), "the filter survived q"); assert_eq!(board.current().focus, Focus::Cards, "the focus outlived the frame"); assert!(!board.should_quit, "q quit out from under the filter"); } /// The frame speaks in its own words: what the view is on the top border, how many on /// the bottom right, and one grey sentence between them. #[test] fn the_no_campaign_frame_says_what_it_is_and_how_many() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_filter(Filter::NoCampaign, SCREEN); let rows = frame_lines(&board, 120, 20); let prose = &rows[1..rows.len() - 1]; assert!(rows[0].contains(NO_CAMPAIGN_ROW), "{:?}", rows[0]); assert!(rows[rows.len() - 1].contains("1 ticket"), "{:?}", rows[rows.len() - 1]); assert!( prose .iter() .any(|row| row.contains("Tickets that name no campaign.")), "{prose:?}" ); } /// The frame question stays `is_whole()` — every filter draws one — so the selection can /// go up onto this frame the way it goes onto any other, and there is no state where it /// rests on a frame that is not drawn. #[test] fn the_selection_reaches_the_no_campaign_frame_because_one_is_drawn() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_filter(Filter::NoCampaign, SCREEN); board.select_card(-1, SCREEN); assert_eq!(board.current().focus, Focus::Frame, "up did not reach the frame"); let rows = frame_lines(&board, 120, 20); assert!(rows[0].contains(NO_CAMPAIGN_ROW), "the frame was not drawn: {rows:?}"); } /// An unset field means the same thing on every board, so the pile is pickable on the /// merge tab where one campaign is not: the count adds across boards and the filter cuts /// all of them at once. #[test] fn the_pile_can_be_picked_on_the_merge_tab_where_a_campaign_cannot() { 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(&one, "backlog", "22222222-0000-4000-8000-000000000000", "Loose", ""); write_ticket(&two, "backlog", "44444444-0000-4000-8000-000000000000", "Adrift", ""); let mut board = boards(&[("one", &one), ("two", &two)]); // The merged pile is two: one loose ticket per board. board.open_picker(PickerKind::Campaign, SCREEN); let rows = picker_list(board.current(), board.picker.as_ref().expect("no picker")); assert!( matches!(rows.first(), Some(PickerRow::NoCampaign(2))), "the merged count is not the sum: {rows:?}" ); type_picker_query(&mut board, "none"); press(&mut board, KeyCode::Enter); let headings = headings(&board, 120, 20); assert!(headings.contains("backlog (2)"), "{headings}"); let held: Vec = board.current().columns[0] .cards .iter() .map(|card| card.ticket.title.clone()) .collect(); assert_eq!(held, vec!["Adrift", "Loose"], "the merge was not cut across boards"); // And a campaign filter could not have done that: it belongs to the tab, keyed on a // uuid from one board. board.select_tab(1, SCREEN); assert!(board.current().filter.is_whole(), "the filter crossed to a project"); } /// The frame has neither an id nor a word a command line takes, so `y` is left out of /// its footer rather than named into a notice — and pressing it anyway still says so, /// never an empty string over the reader's clipboard. #[test] fn y_has_nothing_to_copy_from_the_no_campaign_frame() { let dir = board_dir(); let mut board = campaign_board(&dir); board.select_filter(Filter::NoCampaign, SCREEN); board.select_card(-1, SCREEN); assert_eq!(board.copy_text(), None); let row = footer(&board, 120, 20); assert!(!row.contains("copy"), "the footer names a key into a notice: {row:?}"); let mut taken = None; board.copy_selected_id(recorder(&mut taken)); assert_eq!(taken, None, "something reached the clipboard"); let notice = board.notice.as_ref().expect("nothing was said"); assert_eq!(notice.text, "nothing to copy"); } }