//! The board as four columns, redrawn when the tree underneath it moves. //! //! Modelled on frig's TUI: event poll on a short timeout so timed work still runs when //! nobody is typing, state refreshed on a tick, and the terminal restored whatever //! happens. //! //! **Read only.** Moving a card by keypress is a follow-up. Everything here observes. use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime}; use anyhow::{Context, Result}; use ratatui::layout::{Constraint, Direction, Layout, Margin, Rect, Size}; use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Borders, Clear, Paragraph, Tabs, Wrap}; use ratatui::Frame; use crate::handlers::read_comments; use crate::util::*; /// How long the event poll waits before letting the tick run. pub const POLL: Duration = Duration::from_millis(250); /// The tab that throws every monitored board into one set of columns. /// /// Lowercase like the column headings, since it sits in the same row of chrome and is /// a label rather than a sentence. const ALL: &str = "all"; /// 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, } /// One status and the cards in it. pub struct Column { pub status: &'static str, pub cards: Vec, } /// 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, } impl Tab { fn new(name: String) -> Self { Tab { name, columns: Vec::new(), column: 0, card: 0, offsets: Vec::new(), } } /// The columns that are drawn: all of them, or everything up to done. /// /// A prefix rather than a filter, which is what keeps `column` and `offsets` usable /// as indices into either. Taken from where done actually is instead of assuming the /// last slot, with a test pinning done as last so the two cannot drift apart. fn visible(&self, show_done: bool) -> &[Column] { &self.columns[..self.visible_count(show_done)] } fn visible_count(&self, show_done: bool) -> usize { if show_done { return self.columns.len(); } match self.columns.iter().position(|column| column.status == DONE) { Some(index) => index, None => self.columns.len(), } } /// Keep the selection on a card that exists, after the board changes under it. fn clamp(&mut self, show_done: bool) { let visible = self.visible_count(show_done); if visible == 0 { self.column = 0; self.card = 0; return; } self.column = self.column.min(visible - 1); let count = self.columns[self.column].cards.len(); self.card = match count { 0 => 0, count => self.card.min(count - 1), }; } fn selected(&self) -> Option<&Card> { self.columns .get(self.column) .and_then(|column| column.cards.get(self.card)) } } /// What the detail view holds while it is open: the ticket it belongs to, then its /// body and comments as one plain text. /// /// The title travels beside the text rather than inside it, because it does not /// scroll: it names the overlay from the border, where no amount of reading can /// carry it off the screen. #[derive(Debug)] pub struct Detail { pub title: String, pub id: String, /// The project the ticket belongs to, on the All tab only. The overlay covers the /// card that said so, and the id alone is not an address across several boards: /// acting on the ticket means knowing which project to run the command in. pub project: Option, pub text: String, } /// 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, /// Whether the done column is drawn. Off at startup, and not remembered between /// runs: worklane has no config file, and one flag is not a reason to start one. /// Board-wide rather than per tab: it is a preference about the flow, not about a /// project. pub show_done: bool, pub should_quit: bool, projects: Vec, digest: u64, } impl Board { pub fn new(projects: Vec) -> Result { if projects.is_empty() { return Err(anyhow::anyhow!("no board to monitor")); } // The tabs are fixed for the run: a project cannot be added or dropped without // restarting, so only their contents are rebuilt on a tick. The merge goes // first because it is the reason to monitor several boards at once, and it is // therefore where the view opens. let mut tabs: Vec = Vec::new(); if projects.len() > 1 { tabs.push(Tab::new(ALL.to_string())); } tabs.extend( projects .iter() .map(|project| Tab::new(project.name.clone())), ); let mut board = Board { tabs, tab: 0, detail: None, offset: 0, show_done: false, should_quit: false, projects, digest: 0, }; board.reload()?; Ok(board) } /// Whether the tab row is drawn, which is whether there is more than one board. /// /// A single board keeps the view it has always had: no tabs, and the columns /// starting on the first row. pub fn tabbed(&self) -> bool { self.tabs.len() > 1 } pub fn current(&self) -> &Tab { &self.tabs[self.tab] } fn current_mut(&mut self) -> &mut Tab { &mut self.tabs[self.tab] } /// Re-read the trees only when the digest says one of them moved. /// /// The scan is the expensive part, not the draw, so this is what the tick guards. /// ratatui diffs its buffer, so drawing every iteration costs nothing. pub fn tick(&mut self) -> Result { let now = digest_of(&self.projects); if now == self.digest { return Ok(false); } self.reload()?; Ok(true) } fn reload(&mut self) -> Result<()> { // Each tree is read once. The merge is built from those cards rather than by // scanning every project a second time. let per_project: Vec> = self .projects .iter() .map(|project| columns_of(&project.dir)) .collect(); let mut built: Vec> = Vec::new(); if self.projects.len() > 1 { built.push(merge(&per_project, &self.projects)); } built.extend(per_project); for (tab, columns) in self.tabs.iter_mut().zip(built) { tab.columns = columns; // One scroll position per column, kept by index. A tick that adds or removes // columns is not a thing statuses do, but the resize keeps the two in step // regardless; `resize` both pads and truncates. tab.offsets.resize(tab.columns.len(), 0); tab.clamp(self.show_done); } self.digest = digest_of(&self.projects); // The selected ticket may have moved or gone, so the open detail follows it. // The scroll offset stays where the reader put it: an edit elsewhere in the tree // should not throw them back to the top of what they are reading. A ticket that // got shorter is caught by the clamp in the draw. if self.detail.is_some() { self.detail = self.selected().map(detail_of); } Ok(()) } /// The columns of the tab in view that are drawn. pub fn visible(&self) -> &[Column] { self.current().visible(self.show_done) } fn visible_count(&self) -> usize { self.current().visible_count(self.show_done) } /// Move to another tab, cycling at either end. /// /// Tabs cycle where the cards and columns clamp: a ring is what a row of tabs is /// everywhere else, and there is no bottom of a list to run out of. The tab keeps /// its own selection, so all this has to do is check that the selection is still on /// a card that exists — done may have been hidden while another tab was in view — /// and bring it into the window. pub fn select_tab(&mut self, delta: isize, screen: Size) { let count = self.tabs.len() as isize; if count < 2 { return; } self.tab = (self.tab as isize + delta).rem_euclid(count) as usize; let show_done = self.show_done; self.current_mut().clamp(show_done); self.follow_selection(screen); self.refresh_detail(); } /// Show or hide the done column. /// /// `ls` already holds this opinion: it counts done in its summary and leaves it out /// of the listing. Done only grows, so a quarter of the width goes to the column /// least often read while the three being worked get squeezed for it. /// /// Hiding is a change to what is drawn, never to what is read. The directory stays /// scanned and stays in the digest, so the count in the footer is right and revealing /// the column needs no rescan. pub fn toggle_done(&mut self, screen: Size) { self.show_done = !self.show_done; // Showing done again appends a column, so nothing below is reached and the // selection stays exactly where it was. Only the tab in view is corrected: the // others are clamped as they are switched to, since a selection nobody is // looking at cannot be pointing at anything on screen. if self.current().column < self.visible_count() { return; } // Hiding the column the selection is in moves it to the last one still drawn. // An open detail closes with it: it is showing a ticket that is no longer on the // board, and quietly swapping it for a different ticket is worse than closing. let show_done = self.show_done; self.current_mut().clamp(show_done); self.detail = None; self.offset = 0; self.follow_selection(screen); } pub fn selected(&self) -> Option<&Card> { self.current().selected() } /// Move between columns, keeping the card index where it can land. pub fn select_column(&mut self, delta: isize, screen: Size) { let visible = self.visible_count(); if visible == 0 { return; } // Bounded by what is drawn, so the selection cannot walk into a hidden column. let last = visible as isize - 1; let show_done = self.show_done; let tab = self.current_mut(); tab.column = (tab.column as isize + delta).clamp(0, last) as usize; tab.clamp(show_done); // Entering a column shows the card the selection landed on rather than // resetting to its top: the card index carries across columns, so a reset // would open the column with the highlight below the fold whenever it was. // The rest of the place the column was left in is kept. self.follow_selection(screen); self.refresh_detail(); } pub fn select_card(&mut self, delta: isize, screen: Size) { let tab = self.current_mut(); let count = match tab.columns.get(tab.column) { Some(column) => column.cards.len(), None => return, }; if count == 0 { return; } tab.card = (tab.card as isize + delta).clamp(0, count as isize - 1) as usize; 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 width = card_width(screen, self.tabbed(), self.visible_count(), column); let inner = column_text_height(screen, self.tabbed()); 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), }; } /// Scroll the open detail view by whole screenfuls, one line kept for overlap. /// /// Up and down move the selection, so the scroll is on PageUp and PageDown. That is /// worth keeping either way: with the modal open, up and down step through the /// tickets and the modal follows, so a column can be read without closing it. /// /// Clamped against the wrapped text rather than the raw lines, so the last page ends /// with the ticket instead of running on into blank space, and against zero at the /// top. The screen is asked for because both ends belong to the overlay, which only /// the draw otherwise measures. pub fn scroll_detail(&mut self, pages: isize, screen: Size) { let Some(detail) = &self.detail else { return }; let text = detail_text_area(Rect::new(0, 0, screen.width, screen.height)); // A screenful less a line, so the eye has something to land on after the jump. let step = text.height.saturating_sub(1).max(1) as isize; let last = last_offset(&detail.text, text) as isize; self.offset = (self.offset as isize + pages.saturating_mul(step)).clamp(0, last) as u16; } fn refresh_detail(&mut self) { // A newly selected ticket starts at its top, not partway down where the last one // was left. self.offset = 0; if self.detail.is_some() { self.detail = self.selected().map(detail_of); } } } /// The ticket as the detail view holds it: its name and short id, then the body as /// `show` renders it and the comments. /// /// Plain rather than coloured, since ratatui draws styled spans and an escape sequence /// in a paragraph would be printed as literal bytes. fn detail_of(card: &Card) -> Detail { let ticket = &card.ticket; let content = std::fs::read_to_string(&ticket.path).unwrap_or_default(); let uuid = parse_ticket_field(&content, "ID"); let worklane_dir = ticket.path.parent().and_then(|status| status.parent()); // All of these read the tree beside the ticket, and all fall back to nothing: one // unreadable file must not take the board down with it. The relations cost a scan of // the board, paid only while a ticket is open and only on a tick that changed // something, which is what already reloads every card. The campaign title costs a // read of one small directory beside it, for the same reason `show` pays it: the // field stores a uuid, and a card that displayed one raw would say nothing. let resolved = worklane_dir .and_then(|dir| crate::campaign::resolved_for(&content, dir, false).ok()) .unwrap_or_default(); let comments = match worklane_dir { Some(worklane_dir) => { read_comments(&worklane_dir.join("comments").join(&uuid)).unwrap_or_default() } None => Vec::new(), }; let mut out = content_trim(&content, false, &resolved); out.push('\n'); out.push_str(&format_comments_with(&comments, false)); Detail { title: ticket.title.clone(), id: ticket.id.clone(), project: card.project.clone(), text: out, } } /// The four columns of one board. fn columns_of(worklane_dir: &Path) -> Vec { status_dirs() .into_iter() .map(|status| { // An absent or unreadable directory is an empty column, not a missing one: // the four statuses are the shape of the board. let cards = collect_ticket_items(worklane_dir.join(status)) .unwrap_or_default() .into_iter() .map(|ticket| Card { ticket, project: None, }) .collect(); Column { status, cards } }) .collect() } /// Every board's columns as one set of four, each card labelled with the project it /// came from. /// /// Sorted through `by_priority_then_title`, the order the listing uses, rather than /// left as one project's column after another's: an overview whose order depended on /// the argument order would bury a p1 under another project's p5. fn merge(per_project: &[Vec], projects: &[Project]) -> Vec { status_dirs() .into_iter() .enumerate() .map(|(index, status)| { let mut cards: Vec = Vec::new(); for (columns, project) in per_project.iter().zip(projects) { let Some(column) = columns.get(index) else { continue; }; cards.extend(column.cards.iter().map(|card| Card { ticket: card.ticket.clone(), project: Some(project.name.clone()), })); } cards.sort_by(|a, b| by_priority_then_title(&a.ticket, &b.ticket)); Column { status, cards } }) .collect() } /// 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 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. /// /// Cheap enough on a tree of tens of small files that it needs no new dependency. If it /// ever stops being cheap, `notify` is the next step, and the reason belongs on the /// ticket. pub fn digest(worklane_dir: &Path) -> u64 { let mut entries: Vec<(String, u64, Duration)> = Vec::new(); let mut visit = |dir: PathBuf| { let Ok(read) = std::fs::read_dir(&dir) else { return; }; for entry in read.filter_map(|e| e.ok()) { let path = entry.path(); if path.extension().is_none_or(|e| e != "md") { continue; } let Ok(meta) = entry.metadata() else { continue }; let modified = meta .modified() .ok() .and_then(|at| at.duration_since(SystemTime::UNIX_EPOCH).ok()) .unwrap_or_default(); entries.push((path.to_string_lossy().to_string(), meta.len(), modified)); } }; for status in status_dirs() { visit(worklane_dir.join(status)); } // Comments live one level deeper, a directory per ticket. let comments = worklane_dir.join("comments"); if let Ok(read) = std::fs::read_dir(&comments) { for entry in read.filter_map(|e| e.ok()) { visit(entry.path()); } } // Sorted, so a directory handing entries back in a different order is not a change. entries.sort(); let mut hasher = DefaultHasher::new(); entries.hash(&mut hasher); hasher.finish() } pub fn draw(frame: &mut Frame, board: &Board) { let area = frame.area(); let rows = frame_rows(area, board.tabbed()); if board.tabbed() { draw_tabs(frame, board, rows[0]); } draw_columns(frame, board, rows[1]); draw_footer(frame, board, rows[2]); if let Some(detail) = &board.detail { draw_detail(frame, detail, board.offset, area); } } /// The rows of the frame: the tab row, 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, /// so the indices hold either way and rendering into it draws nothing. fn frame_rows(area: Rect, tabbed: bool) -> std::rc::Rc<[Rect]> { Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(u16::from(tabbed)), Constraint::Min(3), Constraint::Length(1), ]) .split(area) } /// One tab per monitored board, plus the merge, named after the directory each lives in. /// /// Cyan for the one in view, the colour the focused column's border already uses, and /// grey for the rest. fn draw_tabs(frame: &mut Frame, board: &Board, area: Rect) { let names: Vec = board.tabs.iter().map(|tab| tab.name.clone()).collect(); frame.render_widget( Tabs::new(names) .select(board.tab) .style(Style::default().fg(Color::Grey.into())) .highlight_style( Style::default() .fg(Color::Cyan.into()) .add_modifier(Modifier::BOLD), ), area, ); } fn draw_columns(frame: &mut Frame, board: &Board, area: Rect) { // Only the drawn columns are measured, so hiding done gives its width back to the // three that are left rather than leaving a gap where it was. let columns = board.visible(); let areas = column_areas(area, columns.len()); for (index, column) in columns.iter().enumerate() { let focused = index == board.current().column; let title = format!(" {} ({}) ", column.status, column.cards.len()); let block = Block::default() .borders(Borders::ALL) .title(Span::styled( title, Style::default() .fg(Color::Orange.into()) .add_modifier(if focused { Modifier::BOLD } else { Modifier::empty() }), )) .border_style(Style::default().fg(if focused { Color::Cyan.into() } else { Color::Grey.into() })); // The cards go into one paragraph, and where each card starts is recorded as // it is added: the scroll has to measure what is really drawn, not assume a // card size the renderer has to agree with. let text = areas[index].inner(Margin::new(1, 1)); let mut lines: Vec = Vec::new(); let mut starts: Vec = Vec::new(); for (at, card) in column.cards.iter().enumerate() { let selected = focused && at == board.current().card; starts.push(lines.len() as u16); lines.extend(card_lines(card, selected, text.width)); } let total = lines.len() as u16; let stored = board.current().offsets.get(index).copied().unwrap_or(0); // The focused column follows its selection here as well as on the keypress: // the terminal can be resized between the two, and a tick can shorten the // column under a reader who is already at the end. An unfocused column keeps // the place it was left in, capped so it cannot show blank space past its // last card. let offset = if focused { let card = board.current().card; let start = starts.get(card).copied().unwrap_or(total); let end = starts.get(card + 1).copied().unwrap_or(total); aligned_offset(stored, start, end, text.height, total) } else { stored.min(total.saturating_sub(text.height)) }; // An empty status is an empty column, not a column that is not there. frame.render_widget( Paragraph::new(lines) .block(block) .scroll((offset, 0)), areas[index], ); } } /// The lines one card occupies, measured the way `draw_columns` renders it. /// /// Width-dependent, because the title wraps: the same ticket is four rows in a wide /// column and five in a narrow one. fn card_height(card: &Card, width: u16) -> u16 { card_lines(card, false, width).len() as u16 } /// The rectangles the columns are drawn in, from one place. /// /// Shared with the measurement in `follow_selection`, so the width a card lays itself /// out in is the width it is drawn in. `Ratio` leaves a remainder column to whichever /// slot ratatui gives it, and guessing that arithmetic by hand is how the two come to /// disagree about where a card starts. fn column_areas(area: Rect, count: usize) -> std::rc::Rc<[Rect]> { let widths: Vec = (0..count) .map(|_| Constraint::Ratio(1, count.max(1) as u32)) .collect(); Layout::default() .direction(Direction::Horizontal) .constraints(widths) .split(area) } /// The width a card has inside one column, as the next draw will lay it out. fn card_width(screen: Size, tabbed: bool, count: usize, column: usize) -> u16 { column_areas(board_area(screen, tabbed), 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, tabbed: bool) -> u16 { board_area(screen, tabbed).height.saturating_sub(2) } /// The area the columns are drawn in, which is what `draw` hands to `draw_columns`. fn board_area(screen: Size, tabbed: bool) -> Rect { frame_rows(Rect::new(0, 0, screen.width, screen.height), tabbed)[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… /// #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 tags sit between the title and the bottom corners, on a row a ticket without /// them does not spend. See [`tags_line`]. 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), ), ]; let label = card .project .as_deref() .and_then(|name| project_label(name, width)); if let Some(label) = label { left.push(Span::raw(" ")); // Grey like the owner and the criteria count: the shape carries which project // this is, and colour here accentuates rather than encodes. left.push(Span::styled( label, Style::default().fg(Color::Grey.into()).add_modifier(emphasis), )); } let mut lines = vec![corner_line(left, due_span(&ticket.due), width)]; lines.extend(title_lines(&ticket.title, width).into_iter().map(|line| { Line::from(Span::styled( line, Style::default().add_modifier(emphasis), )) })); if let Some(row) = tags_line(&ticket.tags, width) { lines.push(row); } lines.push(corner_line( vec![Span::styled( ticket.owner.clone(), Style::default().fg(Color::Grey.into()), )], ticket.criteria.map(|progress| { Span::styled( format!("[{}/{}]", progress.met, progress.total), Style::default().fg(Color::Grey.into()), ) }), width, )); lines.push(Line::from("")); lines } /// The ticket's tags under the title, or nothing when it has none. /// /// 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. /// /// 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. An untagged ticket spends no row at all, the way a /// short title spends no second one. fn tags_line(tags: &[String], width: u16) -> Option> { if tags.is_empty() { return None; } let row = tags .iter() .map(|tag| format!("#{tag}")) .collect::>() .join(" "); if row.chars().count() > width as usize { return None; } Some(Line::from(Span::styled( row, Style::default().fg(Color::Grey.into()), ))) } /// The project name as it fits beside the mark and the id. /// /// The mark and the id are the ticket's identity and never give 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. /// /// 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) -> Option { // The mark and the space after it, the id in its brackets, and the space before the // label. let used = 2 + SHORT_ID_WIDTH + 2 + 1; let room = (width as usize).checked_sub(used)?; if room < 3 { return None; } match name.chars().count() <= room { true => Some(name.to_string()), false => Some(with_ellipsis(name, room)), } } /// A set due in the timestamp colour, an unset one dimmed, per the colour guideline. /// /// The date part only: the field is not validated, so it can hold a time as well, and a /// corner has no room to spare on one. fn due_span(due: &str) -> Option> { let colour = match is_unknown_value(due) { true => Color::Grey, false => Color::Cyan, }; Some(Span::styled( due_date(due).to_string(), Style::default().fg(colour.into()), )) } /// `left` at the left, `right` at the right, with the gap between them. /// /// The right-hand corner is dropped whole when it will not fit rather than truncated or /// wrapped: half a date reads as a different date, and a card that reflows in a narrow /// column changes height, which the scroll would then have to chase. The left corner is /// the ticket's identity and always stays. fn corner_line( left: Vec>, right: Option>, width: u16, ) -> Line<'static> { let mut spans = left; let used: usize = spans.iter().map(|span| span.content.chars().count()).sum(); let Some(right) = right else { return Line::from(spans); }; let wanted = right.content.chars().count(); // One space minimum, so the two corners never touch. No room at all and the right // corner goes rather than the line growing past the column. if let Some(gap) = (width as usize).checked_sub(used + wanted + 1) { spans.push(Span::raw(" ".repeat(gap + 1))); spans.push(right); } Line::from(spans) } /// The title over one row or two, wrapped on spaces, cut with an ellipsis if even two /// are not enough. /// /// One row when one is enough: a second, blank row on every short ticket would spend /// the column's height on nothing. A word longer than the column is broken rather than /// left to overflow, since a uuid or a path has no space to break at. fn title_lines(title: &str, width: u16) -> Vec { let width = width.max(1) as usize; let mut rows: Vec = Vec::new(); let mut row = String::new(); for word in title.split_whitespace() { let room = width - row.chars().count().min(width); let space = usize::from(!row.is_empty()); if word.chars().count() + space <= room { if space == 1 { row.push(' '); } row.push_str(word); continue; } if !row.is_empty() { rows.push(std::mem::take(&mut row)); } // A word too long for a row of its own is broken across rows. for chunk in chars_in_chunks(word, width) { if row.chars().count() + chunk.chars().count() > width { rows.push(std::mem::take(&mut row)); } row.push_str(&chunk); } } if !row.is_empty() { rows.push(row); } if rows.len() > 2 { rows.truncate(2); rows[1] = with_ellipsis(&rows[1], width); } if rows.is_empty() { rows.push(String::new()); } rows } fn chars_in_chunks(word: &str, width: usize) -> Vec { let chars: Vec = word.chars().collect(); chars .chunks(width) .map(|chunk| chunk.iter().collect()) .collect() } /// The row with an ellipsis on the end, making room for it if the row is full. fn with_ellipsis(row: &str, width: usize) -> String { let keep = match row.chars().count() < width { true => row.chars().count(), false => width.saturating_sub(1), }; let mut cut: String = row.chars().take(keep).collect(); // Trailing space before an ellipsis reads as a gap rather than a cut. while cut.ends_with(' ') { cut.pop(); } cut.push('…'); cut } fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { // While done is hidden its count goes here, which is the board's version of the // summary line `ls` prints above a listing that leaves done out. let done = match board.show_done { true => "d hide done".to_string(), false => format!("d show done ({})", done_count(board)), }; // Only when there is a tab to move to, since the footer names keys that work. let tabs = match board.tabbed() { true => "tab project ", false => "", }; let keys = match board.detail { Some(_) => { format!(" {tabs}←→↑↓ select pgup/pgdn scroll enter close {done} q quit ") } None => format!(" {tabs}←→ column ↑↓ card enter detail {done} q quit "), }; frame.render_widget( Paragraph::new(Span::styled(keys, Style::default().fg(Color::Grey.into()))), area, ); } /// How many tickets are in done on the tab in view, drawn or not. fn done_count(board: &Board) -> usize { board .current() .columns .iter() .find(|column| column.status == DONE) .map_or(0, |column| column.cards.len()) } /// Where the 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)) } /// The furthest the detail view can scroll: the last screenful, and no further. /// /// Measured by the widget rather than counted by hand, since it wraps on words. A clamp /// on the raw lines would stop short of the end on a wrapped ticket, and one that /// ignored the wrapping the other way would scroll past it into blank space. fn last_offset(detail: &str, text: Rect) -> u16 { let wrapped = Paragraph::new(detail) .wrap(Wrap { trim: false }) .line_count(text.width); u16::try_from(wrapped) .unwrap_or(u16::MAX) .saturating_sub(text.height) } fn draw_detail(frame: &mut Frame, detail: &Detail, offset: u16, area: Rect) { let overlay = detail_overlay(area); // 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. let offset = offset.min(last_offset(&detail.text, detail_text_area(area))); let 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()), )); frame.render_widget(Clear, overlay); frame.render_widget( Paragraph::new(detail.text.to_string()) .block(block) .wrap(Wrap { trim: false }) .scroll((offset, 0)), overlay, ); } /// The overlay's title: the short id and the name of the ticket it has open. /// /// The id goes first because that is how every other view addresses a ticket, and the /// name after it because that is what the id is shorthand for. Both sit on the border /// rather than at the head of the paragraph, so reading to the end of a long ticket /// cannot carry them off the screen. /// /// The string is cut here rather than left to the renderer, which truncates an /// overlong title at whatever cell it reaches and would take the id with it. Cut /// against the inner width — a border column on either side is not the title's to /// write on — the id survives whole and the name ends in an ellipsis where it was /// trimmed. On an overlay too narrow for even the id, what fits is what shows. fn detail_title(detail: &Detail, overlay_width: u16) -> String { // The project rides in the prefix, beside the id, so what survives the cut is the // whole address rather than half of one. Absent on a single board and on a // project's own tab, where the overlay reads exactly as it always has. let project = match &detail.project { Some(name) => format!("{name} "), None => String::new(), }; let room = overlay_width.saturating_sub(2) as usize; let full = format!(" ({}) {}· {} ", detail.id, project, detail.title); if full.chars().count() <= room { return full; } let prefix = format!(" ({}) {}· ", detail.id, project); match room.checked_sub(prefix.chars().count() + 1) { Some(keep) if keep > 0 => { let name: String = detail.title.chars().take(keep).collect(); format!("{prefix}{name}…") } _ => full.chars().take(room).collect(), } } #[cfg(test)] mod tests { use super::*; use ratatui::Terminal; use ratatui::backend::TestBackend; /// A board on disk, since everything here is about reading a real tree. /// /// The directory stands in for a `.worklane`, so its parent is the temp directory /// and `project_name` reads the generated name off it. fn board_dir() -> PathBuf { let dir = std::env::temp_dir().join(format!("worklane-tui-{}", uuid::Uuid::new_v4())); for status in status_dirs() { std::fs::create_dir_all(dir.join(status)).unwrap(); } dir } /// The single board case, which is what most of these tests are about. fn one_board(dir: &Path) -> Board { Board::new(vec![project_at(dir)]).unwrap() } fn project_at(dir: &Path) -> Project { Project { name: project_name(dir), dir: dir.to_path_buf(), } } /// Several boards, named so a test can tell their cards apart. fn boards(dirs: &[(&str, &Path)]) -> Board { Board::new( dirs.iter() .map(|(name, dir)| Project { name: name.to_string(), dir: dir.to_path_buf(), }) .collect(), ) .unwrap() } fn selected_title(board: &Board) -> Option { board.selected().map(|card| card.ticket.title.clone()) } fn write_ticket(dir: &Path, status: &str, uuid: &str, title: &str, extra: &str) -> PathBuf { let path = dir.join(status).join(format!("{}_{}.md", uuid, slug(title))); std::fs::write( &path, format!( "# {title}\n\n## Description\nA description.\n\n## Acceptance Criteria\n\ - [ ] Crit one\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ - **Tags**: _None_\n- **Due**: 2026-12-31\n- **Owner**: alice\n\ - **Created At**: 2026-08-21 02:00:00\n- **Status**: {status}\n{extra}" ), ) .unwrap(); path } /// A section of numbered lines, so a test can say which of them is on screen. /// /// Long enough not to fit any overlay the tests draw, which is true of every real /// ticket in the repo as well. fn long_section(lines: usize) -> String { let body: String = (1..=lines).map(|n| format!("Line {n:03}\n")).collect(); format!("\n## Notes\n{body}") } /// The screen the scrolling tests draw on, so the keypress and the draw measure the /// same overlay. const SCREEN: Size = Size { width: 120, height: 20, }; /// The rendered buffer as lines of text, escapes and styling dropped. fn render(board: &Board, width: u16, height: u16) -> Vec { let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); terminal.draw(|frame| draw(frame, board)).unwrap(); let buffer = terminal.backend().buffer().clone(); (0..buffer.area.height) .map(|y| { (0..buffer.area.width) .map(|x| buffer[(x, y)].symbol()) .collect::() }) .collect() } /// The column headings, which sit on the top border row. /// /// That row alone, because the footer names done as well: a whole-screen search for /// `done (0)` passes on the footer whether the column is drawn or not, which is how /// three of these tests came to be vacuous the moment done was hidden. Located /// through the layout rather than assumed to be row zero, since a tab row sits above /// it when more than one board is monitored. fn headings(board: &Board, width: u16, height: u16) -> String { let top = board_area(Size { width, height }, board.tabbed()).y as usize; render(board, width, height).remove(top) } /// The tab row, which is the top row whenever it is drawn at all. fn tab_row(board: &Board, width: u16, height: u16) -> String { render(board, width, height).remove(0) } fn footer(board: &Board, width: u16, height: u16) -> String { render(board, width, height).pop().expect("no rows rendered") } /// The overlay's top border row, where the block title sits. /// /// Counted in characters rather than bytes: the rows carry multi-byte glyphs. fn overlay_title_row(lines: &[String], width: u16, height: u16) -> String { let overlay = detail_overlay(Rect::new(0, 0, width, height)); lines[overlay.y as usize] .chars() .skip(overlay.x as usize) .take(overlay.width as usize) .collect() } #[test] fn the_board_draws_the_four_statuses_as_columns_once_done_is_shown() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); write_ticket(&dir, "committed", "22222222-0000-4000-8000-000000000000", "Second one", ""); let mut board = one_board(&dir); board.toggle_done(SCREEN); let row = headings(&board, 120, 20); for heading in ["backlog (1)", "committed (1)", "reviewing (0)", "done (0)"] { assert!(row.contains(heading), "no {heading:?} in:\n{row}"); } } /// Done only grows, and it is the column least often read. `ls` already leaves it /// out of its listing while counting it in the summary; this is the same opinion. #[test] fn the_board_opens_with_the_done_column_hidden() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished one", ""); let board = one_board(&dir); assert!(!board.show_done, "done was drawn at startup"); let row = headings(&board, 120, 20); for heading in ["backlog (1)", "committed (0)", "reviewing (0)"] { assert!(row.contains(heading), "no {heading:?} in:\n{row}"); } assert!(!row.contains("done"), "done is still a column:\n{row}"); // Hidden, not unread: the count is right and revealing it needs no rescan. assert_eq!(board.current().columns.len(), 4); assert_eq!(board.visible().len(), 3); assert_eq!(done_count(&board), 1); assert!( !render(&board, 120, 20).join("\n").contains("Finished one"), "a hidden done ticket was drawn" ); } /// The three that are left take the width done was using, rather than leaving a gap. #[test] fn the_visible_columns_share_the_full_width() { let dir = board_dir(); let mut board = one_board(&dir); let hidden = headings(&board, 120, 20); assert_eq!(hidden.matches('┌').count(), 3, "{hidden}"); assert!(hidden.ends_with('┐'), "the columns stop short of the edge:\n{hidden}"); board.toggle_done(SCREEN); let shown = headings(&board, 120, 20); assert_eq!(shown.matches('┌').count(), 4, "{shown}"); assert!(shown.ends_with('┐'), "{shown}"); } /// Hiding is a prefix of the columns, which only holds while done is last. The /// board leans on that, so the assumption is pinned rather than assumed. #[test] fn the_done_column_is_last() { assert_eq!(status_dirs().last(), Some(&DONE)); } #[test] fn the_footer_names_the_key_and_carries_the_count_while_done_is_hidden() { let dir = board_dir(); for (n, title) in [("44444444", "One"), ("55555555", "Two")] { write_ticket(&dir, "done", &format!("{n}-0000-4000-8000-000000000000"), title, ""); } let mut board = one_board(&dir); let hidden = footer(&board, 120, 20); assert!(hidden.contains("d show done (2)"), "{hidden}"); board.toggle_done(SCREEN); let shown = footer(&board, 120, 20); assert!(shown.contains("d hide done"), "{shown}"); // With the column drawn, its own heading carries the count. assert!(!shown.contains("(2)"), "the count is printed twice:\n{shown}"); } /// The modal footer names it too, since the key works with a ticket open. #[test] fn the_detail_footer_also_names_the_done_key() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); let row = footer(&board, 120, 20); assert!(row.contains("d show done (0)"), "{row}"); assert!(row.contains("pgup/pgdn scroll"), "{row}"); } /// Hiding the column under the selection has to move it, or it points at nothing. #[test] fn hiding_done_under_the_selection_moves_it_to_the_last_visible_column() { let dir = board_dir(); write_ticket(&dir, "reviewing", "33333333-0000-4000-8000-000000000000", "Ready", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.toggle_done(SCREEN); board.select_column(3, SCREEN); assert_eq!(selected_title(&board), Some("Finished".to_string())); board.toggle_done(SCREEN); assert_eq!(board.current().column, 2, "the selection stayed on a column that is gone"); assert_eq!(selected_title(&board), Some("Ready".to_string())); } /// And an open detail of a done ticket goes with it: showing a ticket that is no /// longer on the board is worse than closing, and swapping it for a different /// ticket without saying so is worse than both. #[test] fn hiding_done_closes_a_detail_view_of_a_done_ticket() { let dir = board_dir(); write_ticket(&dir, "reviewing", "33333333-0000-4000-8000-000000000000", "Ready", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.toggle_done(SCREEN); board.select_column(3, SCREEN); board.toggle_detail(); assert!(board.detail.is_some()); board.toggle_done(SCREEN); assert!(board.detail.is_none(), "{:?}", board.detail); } /// A ticket being read in a column that is not going anywhere stays open. #[test] fn hiding_done_leaves_a_detail_view_of_another_ticket_open() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); board.toggle_done(SCREEN); board.toggle_done(SCREEN); assert!(board.detail.is_some(), "an unrelated detail view was closed"); } /// Done is appended rather than inserted, so showing it moves nothing. #[test] fn showing_done_again_leaves_the_selection_where_it_was() { let dir = board_dir(); write_ticket(&dir, "committed", "22222222-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Beta", ""); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.select_column(1, SCREEN); board.select_card(1, SCREEN); let (column, card) = (board.current().column, board.current().card); board.toggle_done(SCREEN); assert_eq!((board.current().column, board.current().card), (column, card)); assert_eq!(selected_title(&board), Some("Beta".to_string())); } /// The selection cannot walk into a column that is not drawn. #[test] fn the_selection_stops_at_the_last_visible_column() { let dir = board_dir(); write_ticket(&dir, "done", "44444444-0000-4000-8000-000000000000", "Finished", ""); let mut board = one_board(&dir); board.select_column(9, SCREEN); assert_eq!(board.current().column, 2); assert!(board.selected().is_none(), "the selection reached the done column"); board.toggle_done(SCREEN); board.select_column(9, SCREEN); assert_eq!(board.current().column, 3); assert_eq!(selected_title(&board), Some("Finished".to_string())); } /// The card has to carry enough to identify the ticket without opening it. #[test] fn a_card_shows_the_short_id_title_owner_and_due() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let board = one_board(&dir); let screen = render(&board, 120, 20).join("\n"); assert!(screen.contains("(1111111)"), "no short id in:\n{screen}"); assert!(screen.contains("First one"), "no title in:\n{screen}"); assert!(screen.contains("alice"), "no owner in:\n{screen}"); assert!(screen.contains("2026-12-31"), "no due date in:\n{screen}"); } /// One ticket in backlog, written by hand so a test can set the fields the shared /// fixture pins: the due value, and the criteria. fn write_card(dir: &Path, title: &str, due: &str, criteria: &str) { write_tagged_card(dir, title, due, criteria, "_None_"); } /// The same, with the Tags field a test can set. Untagged is `_None_`, which is /// what `add` writes for a ticket given no tags. fn write_tagged_card(dir: &Path, title: &str, due: &str, criteria: &str, tags: &str) { let uuid = "11111111-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{}_{}.md", uuid, slug(title))), format!( "# {title}\n\n## Description\nA description.\n\n## Acceptance Criteria\n\ {criteria}\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ - **Tags**: {tags}\n- **Due**: {due}\n- **Owner**: alice\n\ - **Created At**: 2026-08-21 02:00:00\n- **Status**: backlog\n" ), ) .unwrap(); } /// The 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.tabbed(), 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.tabbed(), 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 }, false, 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:?}"); } /// Dimmed like the owner and the count beside it: the row is there to be scanned, /// not to compete with the title. #[test] fn the_tag_row_is_dimmed() { let dir = board_dir(); write_tagged_card(&dir, "Short", "2026-12-31", "- [ ] One", "cli, tui"); assert_eq!(card_colour(&dir, 120, "#cli #tui"), Some(Color::Grey.into())); } /// And an untagged one spends no row on them, the way a short title spends no /// second row. #[test] fn an_untagged_card_spends_no_row_on_tags() { let dir = board_dir(); write_tagged_card(&dir, "Short", "2026-12-31", "- [ ] One", "_None_"); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "{rows:?}"); assert!(!rows.iter().any(|row| row.contains('#')), "{rows:?}"); } /// A row too wide for the column goes whole, the rule a corner follows: a cut list /// reads as a shorter one, and bug and bugfix cut to the same width say the same /// thing. #[test] fn a_tag_row_too_wide_for_the_column_is_dropped_whole() { let dir = board_dir(); write_tagged_card(&dir, "Short", "2026-12-31", "- [ ] One", "frontend, operations"); // One character short of "#frontend #operations", and one over it. let narrow = only_card_at(&dir, 20); assert_eq!(narrow.len(), 4, "the row was kept: {narrow:?}"); assert!(!narrow.iter().any(|row| row.contains('#')), "{narrow:?}"); let fits = only_card_at(&dir, 21); assert_eq!(fits[2], "#frontend #operations", "{fits:?}"); } /// And a title that fits gets one row, or the second is wasted on every short /// ticket in the column. #[test] fn a_short_title_leaves_the_card_four_rows() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [ ] One"); let rows = only_card(&dir, 120, 20); assert_eq!(rows.len(), 4, "{rows:?}"); assert_eq!(rows[1], "Short"); } /// The corners: id and due on top, owner and progress at the bottom. #[test] fn the_due_date_and_the_criteria_count_sit_on_the_right() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [x] One\n- [ ] Two\n- [ ] Three"); let rows = only_card(&dir, 120, 20); assert!(rows[0].starts_with("\u{25cf}\u{25d0} (1111111)"), "{rows:?}"); assert!(rows[0].ends_with("2026-12-31"), "the due is not on the right: {rows:?}"); assert!(rows[2].starts_with("alice"), "{rows:?}"); assert!(rows[2].ends_with("[1/3]"), "the count is not on the right: {rows:?}"); } /// The field is not validated, so it can hold a time. A corner has no room for one. #[test] fn a_due_with_a_time_shows_the_date_only() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31 09:30:00", "- [ ] One"); let rows = only_card(&dir, 120, 20); assert!(rows[0].ends_with("2026-12-31"), "{rows:?}"); assert!(!rows[0].contains("09:30"), "the time reached the card: {rows:?}"); } /// Greyed like everywhere else, rather than left as an empty corner. The set case is /// the timestamp colour, which is what makes the corner worth looking at. #[test] fn an_unset_due_is_dimmed_and_a_set_one_carries_the_timestamp_colour() { let dir = board_dir(); write_card(&dir, "Short", "_Not set_", "- [ ] One"); assert_eq!( card_colour(&dir, 120, "_Not set_"), Some(Color::Grey.into()), "an unset due is not dimmed" ); let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [ ] One"); assert_eq!(card_colour(&dir, 120, "2026-12-31"), Some(Color::Cyan.into())); } /// `[0/0]` says less than saying nothing. #[test] fn a_ticket_with_no_criteria_shows_no_count() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "_No acceptance criteria provided._"); let rows = only_card(&dir, 120, 20); assert_eq!(rows[2], "alice", "a count appeared from nowhere: {rows:?}"); } /// Counted through `criteria()`, so the card and the numbers `show` prints cannot /// disagree: a checkbox in a description is not a criterion in either. #[test] fn a_checkbox_outside_the_criteria_section_is_not_counted() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; std::fs::write( dir.join("backlog").join(format!("{uuid}_short.md")), format!( "# Short\n\n## Description\n- [x] not a criterion\n\n## Acceptance Criteria\n\ - [x] One\n- [ ] Two\n\n## Metadata\n\n- **ID**: {uuid}\n- **Priority**: 2\n\ - **Due**: 2026-12-31\n- **Owner**: alice\n- **Status**: backlog\n" ), ) .unwrap(); let rows = only_card(&dir, 120, 20); assert!(rows[2].ends_with("[1/2]"), "the description was counted: {rows:?}"); } /// A column too narrow for both corners keeps the identity and drops the rest, /// rather than overflowing the border or reflowing to a taller card. #[test] fn a_narrow_column_drops_the_right_corner() { let dir = board_dir(); write_card(&dir, "Short", "2026-12-31", "- [ ] One"); let rows = only_card(&dir, 52, 14); let inner = card_width(Size { width: 52, height: 14 }, false, 3, 0) as usize; assert!(rows[0].starts_with("\u{25cf}\u{25d0} (1111111)"), "{rows:?}"); assert!(!rows[0].contains("2026"), "the due overran the column: {rows:?}"); for row in &rows { assert!(row.chars().count() <= inner, "row past the column: {row:?}"); } } /// An empty status is a column with nothing in it, not a column that is missing. #[test] fn an_empty_status_renders_as_an_empty_column() { let dir = board_dir(); let mut board = one_board(&dir); assert_eq!(board.current().columns.len(), 4); board.toggle_done(SCREEN); let row = headings(&board, 120, 20); for status in status_dirs() { assert!(row.contains(&format!("{status} (0)")), "{row}"); } } /// Even with a status directory absent altogether, the board keeps its shape. #[test] fn a_missing_status_directory_is_still_a_column() { let dir = board_dir(); std::fs::remove_dir_all(dir.join(DONE)).unwrap(); let mut board = one_board(&dir); assert_eq!(board.current().columns.len(), 4); board.toggle_done(SCREEN); assert!(headings(&board, 120, 20).contains("done (0)")); } #[test] fn the_digest_is_stable_when_nothing_changes() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); assert_eq!(digest(&dir), digest(&dir)); } #[test] fn the_digest_moves_when_a_ticket_is_created_or_moved() { let dir = board_dir(); let before = digest(&dir); let path = write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let created = digest(&dir); assert_ne!(before, created, "a new ticket went unnoticed"); let moved = dir.join("committed").join(path.file_name().unwrap()); std::fs::rename(&path, &moved).unwrap(); assert_ne!(created, digest(&dir), "a moved ticket went unnoticed"); std::fs::remove_file(&moved).unwrap(); assert_eq!(before, digest(&dir), "a deleted ticket left a trace"); } /// The case a directory watch would miss: no create, no rename, only the body. #[test] fn the_digest_moves_when_a_ticket_is_edited_in_place() { let dir = board_dir(); let path = write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let before = digest(&dir); let content = std::fs::read_to_string(&path).unwrap(); std::fs::write(&path, content.replace("A description.", "A longer description.")).unwrap(); assert_ne!(before, digest(&dir), "an in-place edit went unnoticed"); } /// And the harder half of it: an edit that does not change the length either, so /// only the modified time gives it away. #[test] fn the_digest_moves_on_an_edit_of_the_same_length() { let dir = board_dir(); let path = write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let content = std::fs::read_to_string(&path).unwrap(); let same_length = content.replace("A description.", "A descriptionA"); assert_eq!(content.len(), same_length.len(), "the fixture changed length"); std::fs::write(&path, &same_length).unwrap(); let before = digest(&dir); // Stamped rather than slept on, so the test does not depend on how coarse the // filesystem's timestamps are. let file = std::fs::File::options().write(true).open(&path).unwrap(); file.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000)) .unwrap(); assert_ne!(before, digest(&dir), "a same-length edit went unnoticed"); } /// A comment added elsewhere has to reach the detail view, so it counts as a change. #[test] fn the_digest_moves_when_a_comment_is_added() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let before = digest(&dir); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA note from elsewhere.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); assert_ne!(before, digest(&dir), "a new comment went unnoticed"); } #[test] fn navigation_moves_between_columns_and_cards() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", ""); write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Gamma", ""); let mut board = one_board(&dir); assert_eq!(selected_title(&board), Some("Alpha".to_string())); board.select_card(1, SCREEN); assert_eq!(selected_title(&board), Some("Beta".to_string())); // Clamped at both ends rather than wrapping board.select_card(5, SCREEN); assert_eq!(selected_title(&board), Some("Beta".to_string())); board.select_card(-9, SCREEN); assert_eq!(selected_title(&board), Some("Alpha".to_string())); board.select_column(1, SCREEN); assert_eq!(selected_title(&board), Some("Gamma".to_string())); // reviewing is empty, so there is nothing selected there board.select_column(1, SCREEN); assert!(board.selected().is_none()); board.select_column(-9, SCREEN); assert_eq!(board.current().column, 0); } /// Moving from a column with three cards to one with one must not leave the /// selection pointing past the end. #[test] fn the_card_index_is_clamped_when_the_column_is_shorter() { let dir = board_dir(); for (n, title) in [("11111111", "Alpha"), ("22222222", "Beta"), ("33333333", "Gamma")] { write_ticket(&dir, "backlog", &format!("{n}-0000-4000-8000-000000000000"), title, ""); } write_ticket(&dir, "committed", "44444444-0000-4000-8000-000000000000", "Delta", ""); let mut board = one_board(&dir); board.select_card(2, SCREEN); board.select_column(1, SCREEN); assert_eq!(board.current().card, 0); assert_eq!(selected_title(&board), Some("Delta".to_string())); } /// A column long enough that one window cannot hold it: twelve cards at four lines /// each against seventeen visible rows on [`SCREEN`]. fn fill_column(dir: &Path, status: &str, count: usize) { for n in 1..=count { write_ticket( dir, status, &format!("{n:08}-0000-4000-8000-000000000000"), &format!("Ticket {n:02}"), "", ); } } /// The reported bug: walking the selection down past the fold left the highlight on /// a card the window could not see, so from the keyboard nothing appeared to move. #[test] fn selecting_down_past_the_fold_brings_the_selected_card_into_view() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); let top = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(top.contains("Ticket 01"), "{top}"); assert!( !top.contains("Ticket 12"), "the fixture fits without scrolling:\n{top}" ); board.select_card(11, SCREEN); let scrolled = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( scrolled.contains("Ticket 12"), "the selection fell below the fold:\n{scrolled}" ); assert!(!scrolled.contains("Ticket 01"), "nothing scrolled:\n{scrolled}"); } /// And back up again: reaching the top returns the column to its head. #[test] fn selecting_up_scrolls_back_to_the_top() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); board.select_card(11, SCREEN); assert_eq!(board.current().offsets[0], 31); board.select_card(-99, SCREEN); assert_eq!(board.current().offsets[0], 0, "the column stayed where the bottom left it"); let top = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(top.contains("Ticket 01"), "{top}"); assert!(!top.contains("Ticket 12"), "{top}"); } /// Down stops at the last card rather than running into blank space past it, and /// the last card is what ends the view. #[test] fn the_column_scroll_stops_at_the_last_card() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); // More downs than the column has, since the clamp and the cap are what stop it. for _ in 0..30 { board.select_card(1, SCREEN); } assert_eq!(board.current().card, 11); // Twelve cards at four lines, seventeen visible rows. assert_eq!(board.current().offsets[0], 48 - 17); let end = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(end.contains("Ticket 12"), "the end is out of reach:\n{end}"); assert!(!end.contains("Ticket 01"), "nothing scrolled:\n{end}"); } /// A ticket moved elsewhere shortens the column under the reader; the draw has to /// take that without waiting for a keypress, and the stored offset heals on the /// next one rather than throwing the reader anywhere first. #[test] fn a_tick_that_shrinks_a_column_keeps_the_selection_in_view() { let dir = board_dir(); fill_column(&dir, "backlog", 12); let mut board = one_board(&dir); board.select_card(11, SCREEN); for n in 6..=12 { let uuid = format!("{n:08}-0000-4000-8000-000000000000"); let name = format!("{uuid}_ticket-{n:02}.md"); std::fs::remove_file(dir.join("backlog").join(name)).unwrap(); } assert!(board.tick().unwrap(), "the tick saw no change"); assert_eq!(board.current().card, 4, "the selection was not clamped to the new end"); let shrunk = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(shrunk.contains("Ticket 05"), "the new end is out of reach:\n{shrunk}"); assert!(!shrunk.contains("Ticket 06"), "{shrunk}"); // The stored value is stale until the next navigation, which is fine: the draw // corrected what was shown, and this is what writes the correction back. board.select_card(0, SCREEN); assert_eq!(board.current().offsets[0], 3); } /// Each column keeps its own place: leaving one must not snap it back to the top, /// and entering one must show the card the selection landed on, not its head. #[test] fn each_column_keeps_its_place_and_entering_one_shows_the_selection() { let dir = board_dir(); fill_column(&dir, "backlog", 12); for n in 1..=3 { write_ticket( &dir, "committed", &format!("{:08}-0000-4000-8000-000000000000", n + 20), &format!("Other {n:02}"), "", ); } let mut board = one_board(&dir); board.select_card(11, SCREEN); board.select_column(1, SCREEN); // The card index carried over and clamps onto committed's last card. assert_eq!(board.current().card, 2); let away = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( away.contains("Ticket 12"), "leaving snapped the column back to its top:\n{away}" ); assert!(away.contains("Other 03"), "{away}"); board.select_column(-1, SCREEN); // Back in backlog the selection is card 2: the index is shared and it moved // while we were away, so the column follows where it is now rather than // holding a scroll position for a highlight it no longer has. assert_eq!(board.current().card, 2); let back = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( back.contains("Ticket 03"), "returning lost the selection:\n{back}" ); assert!(!back.contains("Ticket 12"), "{back}"); } /// The terminal can shrink between the keypress and the draw; the draw measures the /// real geometry, so the selection cannot be left above or below the fold. #[test] fn a_resize_between_the_keypress_and_the_draw_is_taken_at_draw_time() { let dir = board_dir(); fill_column(&dir, "backlog", 12); // Tall enough that every card fits, so the keypress stores no scroll at all. let roomy = Size { width: 120, height: 60, }; let mut board = one_board(&dir); board.select_card(11, roomy); assert_eq!(board.current().offsets[0], 0); let shrunk = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!( shrunk.contains("Ticket 12"), "the smaller window hid the selection:\n{shrunk}" ); assert!(!shrunk.contains("Ticket 01"), "{shrunk}"); } #[test] fn the_detail_view_shows_the_body_and_the_comments() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", ""); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA note from elsewhere.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); let mut board = one_board(&dir); assert!(board.detail.is_none()); board.toggle_detail(); let detail = board.detail.as_ref().expect("no detail"); assert!(detail.text.contains("A description."), "{}", detail.text); assert!(detail.text.contains("Crit one"), "{}", detail.text); assert!(detail.text.contains("A note from elsewhere."), "{}", detail.text); assert!(detail.text.contains("bob"), "{}", detail.text); // Plain text, since ratatui would print an escape as literal bytes assert!( !detail.text.contains('\x1b'), "escapes reached the detail view: {:?}", detail.text ); board.toggle_detail(); assert!(board.detail.is_none()); } /// The reported bug: the modal showed a description, criteria and a metadata /// table belonging to a ticket it never named. #[test] fn the_detail_view_names_the_ticket_it_has_open() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); board.toggle_detail(); let screen = render(&board, SCREEN.width, SCREEN.height); let row = overlay_title_row(&screen, SCREEN.width, SCREEN.height); assert!(row.contains("(1111111)"), "no short id on the border:\n{row}"); assert!(row.contains("First one"), "no title on the border:\n{row}"); // The heading stays out of the text: `show` prints it and here the border // carries it, so it is on screen once rather than twice. assert!( !board.detail.as_ref().unwrap().text.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().text.contains("A late note.")); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA late note.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); assert!(board.tick().unwrap(), "the tick saw no change"); assert!( board.detail.as_ref().unwrap().text.contains("A late note."), "{:?}", board.detail ); } #[test] fn a_tick_with_nothing_changed_does_not_reload() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); let mut board = one_board(&dir); assert!(!board.tick().unwrap()); } /// The reported bug: a ticket longer than the overlay had no way to be read past its /// first screenful, comments included. #[test] fn paging_down_reaches_the_end_of_a_long_ticket() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", &long_section(60)); let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nThe last word.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); let mut board = one_board(&dir); board.toggle_detail(); let top = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(top.contains("A description."), "not at the top:\n{top}"); assert!(!top.contains("Line 060"), "the fixture is too short:\n{top}"); // More pages than the ticket has, since the clamp is what stops it. for _ in 0..20 { board.scroll_detail(1, SCREEN); } let end = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(end.contains("Line 060"), "the end is out of reach:\n{end}"); assert!(end.contains("The last word."), "the comments are out of reach:\n{end}"); assert!(!end.contains("A description."), "nothing scrolled:\n{end}"); } /// The end of the scroll is the end of the text, not blank space past it, and the top /// of it is the top of the ticket. #[test] fn the_scroll_offset_stops_at_both_ends() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", &long_section(60), ); let mut board = one_board(&dir); board.toggle_detail(); for _ in 0..20 { board.scroll_detail(1, SCREEN); } let settled = board.offset; assert!(settled > 0, "a long ticket did not scroll at all"); board.scroll_detail(1, SCREEN); assert_eq!(board.offset, settled, "the offset ran past the end"); // The last screenful is full: text on the bottom row of the overlay, not the // blank space a clamp on the raw lines would have left there. let lines = render(&board, SCREEN.width, SCREEN.height); let text = detail_text_area(Rect::new(0, 0, SCREEN.width, SCREEN.height)); let bottom: String = lines[(text.bottom() - 1) as usize] .chars() .skip(text.x as usize) .take(text.width as usize) .collect(); assert!( !bottom.trim().is_empty(), "the last page ran into blank space:\n{}", lines.join("\n") ); board.scroll_detail(-40, SCREEN); assert_eq!(board.offset, 0, "the offset went above the top"); } /// A ticket that fits has nothing to scroll, so the keys do nothing to it. #[test] fn a_ticket_shorter_than_the_overlay_does_not_scroll() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", ""); // Tall enough that the whole ticket is on screen at once. let roomy = Size { width: 120, height: 60, }; let mut board = one_board(&dir); board.toggle_detail(); let before = render(&board, roomy.width, roomy.height); board.scroll_detail(1, roomy); assert_eq!(board.offset, 0); assert_eq!(render(&board, roomy.width, roomy.height), before); } /// Up and down still move the selection with the detail view open, and the modal /// follows, which is the reason the scroll went on pgup and pgdn in the first place. #[test] fn the_selection_still_moves_under_an_open_detail_view() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", ""); let mut board = one_board(&dir); board.toggle_detail(); // By id in the text: the heading is stripped from the body, and the title // travels beside it for the block title instead. assert!( board.detail.as_ref().unwrap().text.contains("11111111"), "{:?}", board.detail ); board.select_card(1, SCREEN); assert_eq!(selected_title(&board), Some("Beta".to_string())); assert!( board.detail.as_ref().unwrap().text.contains("22222222"), "{:?}", board.detail ); } /// A newly selected ticket starts at its own top, not where the last one was left. #[test] fn the_scroll_offset_resets_when_the_selection_moves() { let dir = board_dir(); let long = long_section(60); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", &long); write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", &long); write_ticket(&dir, "committed", "33333333-0000-4000-8000-000000000000", "Gamma", &long); let mut board = one_board(&dir); board.toggle_detail(); board.scroll_detail(1, SCREEN); assert!(board.offset > 0); board.select_card(1, SCREEN); assert_eq!(board.offset, 0, "the next card opened partway down"); board.scroll_detail(1, SCREEN); assert!(board.offset > 0); board.select_column(1, SCREEN); assert_eq!(board.offset, 0, "the next column opened partway down"); } #[test] fn the_scroll_offset_resets_when_the_detail_view_is_reopened() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", &long_section(60), ); let mut board = one_board(&dir); board.toggle_detail(); board.scroll_detail(1, SCREEN); assert!(board.offset > 0); board.toggle_detail(); board.toggle_detail(); assert_eq!(board.offset, 0, "the ticket reopened where it was left"); } /// An edit elsewhere in the tree must not throw the reader back to the top. #[test] fn a_tick_leaves_the_scroll_where_the_reader_put_it() { let dir = board_dir(); let uuid = "11111111-0000-4000-8000-000000000000"; write_ticket(&dir, "backlog", uuid, "First one", &long_section(60)); let mut board = one_board(&dir); board.toggle_detail(); board.scroll_detail(1, SCREEN); let offset = board.offset; let comments = dir.join("comments").join(uuid); std::fs::create_dir_all(&comments).unwrap(); std::fs::write( comments.join("20260821_120000_000000.md"), "**Comment**\nA late note.\n\n**Author**: bob\n**Time**: 2026-08-21 12:00:00\n", ) .unwrap(); assert!(board.tick().unwrap(), "the tick saw no change"); assert_eq!(board.offset, offset); } /// The footer is what sent the reporter looking for their own mistake, so it has to /// name the keys that exist and only those. #[test] fn the_footer_names_the_keys_that_work() { let dir = board_dir(); write_ticket( &dir, "backlog", "11111111-0000-4000-8000-000000000000", "First one", &long_section(60), ); let mut board = one_board(&dir); let closed = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(closed.contains("↑↓ card"), "{closed}"); assert!(closed.contains("enter detail"), "{closed}"); assert!(!closed.contains("scroll"), "a scroll offered with nothing open:\n{closed}"); board.toggle_detail(); let open = render(&board, SCREEN.width, SCREEN.height).join("\n"); assert!(open.contains("pgup/pgdn scroll"), "{open}"); assert!(open.contains("select"), "{open}"); assert!(open.contains("enter close"), "{open}"); } // ------------------------------------------------------- several boards at once -- /// A project tree: a directory holding a `.worklane`, which is what a path argument /// is resolved to. fn project_tree(name: &str) -> PathBuf { let root = std::env::temp_dir() .join(format!("worklane-project-{}", uuid::Uuid::new_v4())) .join(name); for status in status_dirs() { std::fs::create_dir_all(root.join(".worklane").join(status)).unwrap(); } root } /// No path is the working directory, which is what a bare `worklane` has always /// done, and the tab is named after the project rather than after `.worklane`. #[test] fn no_path_resolves_the_working_directory() { let root = project_tree("alpha"); let found = projects(&[], &root).unwrap(); assert_eq!(found.len(), 1); assert_eq!(found[0].name, "alpha"); assert_eq!(found[0].dir.file_name().unwrap(), ".worklane"); } /// A path is resolved the way the working directory is: the first board at or above /// it, so pointing at a subdirectory finds the project it belongs to. #[test] fn a_path_resolves_the_first_board_at_or_above_it() { let root = project_tree("alpha"); let deep = root.join("src").join("nested"); std::fs::create_dir_all(&deep).unwrap(); let found = projects(&[deep], &std::env::temp_dir()).unwrap(); assert_eq!(found.len(), 1); assert_eq!(found[0].name, "alpha"); } #[test] fn several_paths_are_monitored_together() { let (alpha, beta) = (project_tree("alpha"), project_tree("beta")); let found = projects(&[alpha, beta], &std::env::temp_dir()).unwrap(); let names: Vec<&str> = found.iter().map(|p| p.name.as_str()).collect(); assert_eq!(names, ["alpha", "beta"]); } /// With several arguments, "No .worklane directory found" does not say which one was /// wrong, so the path is named. #[test] fn a_path_with_no_board_fails_naming_that_path() { let alpha = project_tree("alpha"); let bare = std::env::temp_dir().join(format!("worklane-bare-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&bare).unwrap(); let error = projects(&[alpha, bare.clone()], &std::env::temp_dir()).unwrap_err(); let printed = format!("{error:#}"); assert!( printed.contains(&bare.display().to_string()), "the failing path is not named: {printed}" ); // And the usual message is still there, underneath the path. assert!(printed.contains("No .worklane directory found"), "{printed}"); } /// Two paths inside one project reach one board, and drawing it twice would show the /// same tickets under two tabs. #[test] fn two_paths_reaching_one_board_are_monitored_once() { let root = project_tree("alpha"); let deep = root.join("src"); std::fs::create_dir_all(&deep).unwrap(); let found = projects(&[root, deep], &std::env::temp_dir()).unwrap(); assert_eq!(found.len(), 1, "the same board was monitored twice"); } /// One board is the view it has always been: no tabs, columns on the top row. #[test] fn a_single_board_has_no_tab_row() { let dir = board_dir(); write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); let board = one_board(&dir); assert!(!board.tabbed()); assert_eq!(board.tabs.len(), 1); let top = tab_row(&board, 120, 20); assert!(top.starts_with('┌'), "something took the top row:\n{top}"); assert!(top.contains("backlog (1)"), "{top}"); } /// A tab per project, plus the merge, and the merge is where the view opens: it is /// the reason to monitor several boards at once. #[test] fn several_boards_get_a_tab_each_beside_the_all_tab() { let (first, second) = (board_dir(), board_dir()); let board = boards(&[("alpha", &first), ("beta", &second)]); assert!(board.tabbed()); let names: Vec<&str> = board.tabs.iter().map(|tab| tab.name.as_str()).collect(); assert_eq!(names, [ALL, "alpha", "beta"]); assert_eq!(board.current().name, ALL); let row = tab_row(&board, 120, 20); for name in [ALL, "alpha", "beta"] { assert!(row.contains(name), "no {name:?} in the tab row:\n{row}"); } // The columns moved down a row rather than being drawn over. assert!(headings(&board, 120, 20).contains("backlog (0)")); } /// The merge holds every board's tickets, in the order the listing uses rather than /// one project's column after another's. #[test] fn the_all_tab_holds_every_board_in_one_set_of_columns() { let (first, second) = (board_dir(), board_dir()); // Written the wrong way round on purpose: the merge has to sort, not concatenate. write_ticket(&first, "backlog", "22222222-0000-4000-8000-000000000000", "Beta", ""); write_ticket(&second, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha", ""); write_ticket(&second, "committed", "33333333-0000-4000-8000-000000000000", "Gamma", ""); let board = boards(&[("alpha", &first), ("beta", &second)]); let titles: Vec<&str> = board.current().columns[0] .cards .iter() .map(|card| card.ticket.title.as_str()) .collect(); assert_eq!(titles, ["Alpha", "Beta"], "the merge kept the argument order"); let row = headings(&board, 120, 20); assert!(row.contains("backlog (2)"), "{row}"); assert!(row.contains("committed (1)"), "{row}"); // And each project's own tab still holds only its own tickets. let mut board = board; board.select_tab(1, SCREEN); assert_eq!(board.current().name, "alpha"); assert_eq!(board.current().columns[0].cards.len(), 1); } /// Two boards can hold the same title, and seven characters of uuid do not say where /// a ticket lives, so the card on the merge names its project. #[test] fn a_card_on_the_all_tab_names_its_project() { let (first, second) = (board_dir(), board_dir()); write_ticket(&first, "backlog", "11111111-0000-4000-8000-000000000000", "Same name", ""); write_ticket(&second, "backlog", "22222222-0000-4000-8000-000000000000", "Same name", ""); let mut board = boards(&[("alpha", &second), ("beta", &first)]); let merged = render(&board, 120, 20).join("\n"); assert!(merged.contains("alpha"), "no project on the card:\n{merged}"); assert!(merged.contains("beta"), "no project on the card:\n{merged}"); // Not on a project's own tab, where the tab name already says it. board.select_tab(1, SCREEN); let own = board.current().columns[0].cards[0].project.as_deref(); assert_eq!(own, None, "the label was drawn where the tab says it"); } /// The label takes what the row has left, never the mark or the id, and says it was /// cut. A column too narrow for even that keeps the identity alone. #[test] fn the_project_label_gives_way_to_the_mark_and_the_id() { assert_eq!(project_label("alpha", 38).as_deref(), Some("alpha")); // Room for four characters of a longer name, the last of them the ellipsis. assert_eq!(project_label("factry-core", 16).as_deref(), Some("fac…")); assert_eq!(project_label("factry-core", 13), None); assert_eq!(project_label("alpha", 4), None); } /// 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.text.contains(uuid), "the overlay opened another project's ticket: {project} {:?}", detail.text ); 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.text.contains(uuid), "{:?}", moved.text); } /// 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 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").text; assert!(text.contains("blocked by (2222222) The target"), "{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").text; assert!(text.contains("blocks (1111111) A holder"), "{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").text; 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").text; 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").text; assert!(text.contains("A description."), "the body was lost: {text:?}"); } }