(f6af387) Add the board view, and bump to 0.7.0

worklane was one-shot commands only, so reading the board meant running ls again
and again and nothing ever showed the four statuses side by side, which is the
one view a kanban flow is for.

Four columns, a card per ticket carrying the priority mark, short id, title,
owner and due. Arrows or hjkl to move, enter for the detail view, q to quit.
Read only: moving a card by keypress is a follow-up, kept out until the watch
and render loop were solid.

Modelled on frig throughout, same crates and same shape: event poll on a 250ms
timeout so the tick runs when nobody is typing, a panic hook that leaves the
alternate screen before the backtrace, and the terminal restored on the error
path as well as on quit. A bare worklane opens it, as a bare frig does, so
Cli::command is now an Option.

The watch looks at files, not directories. A directory's mtime only moves on
create and rename, so a ticket edited in place would be missed; the digest
hashes every ticket and comment file's path, length and mtime. Comment files
are in it because a comment added elsewhere has to reach the detail view. It
guards the rescan rather than the draw, since ratatui diffs its buffer but
reading the tree every frame would not be free. notify is deliberately not a
dependency, and the reason is on the ticket.

Two orderings are deliberate. The worklane directory is looked for before the
terminal, so running outside one gives the usual message rather than a complaint
about the tty, and both errors stay testable without a pty. And a missing tty is
refused by name, since raw mode on a pipe fails with a bare "No such device or
address" that explains nothing.

The palette is now a Color enum rather than a string, so the escape the CLI
writes and the ratatui colour the board draws come from one definition and a
colour missing from either is a compile error. That retires the test which
existed only to catch a name with no entry, the failure that once left magenta
undefined.

Cards come from collect_ticket_items, so there is no second parser;
TicketItem gained the path the detail view opens. content_trim and
format_comments_with take the colour decision, because ratatui draws spans and
would print an escape as literal bytes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ansho Rei
2026-08-21 11:44:37 +02:00
co-authored by Claude Opus 5
parent bbb1568a0f
commit 78831f1a39
10 changed files with 1532 additions and 105 deletions
+672
View File
@@ -0,0 +1,672 @@
//! 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::Result;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, 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);
/// One status and the tickets in it.
pub struct Column {
pub status: &'static str,
pub tickets: Vec<TicketItem>,
}
/// What is on screen.
pub struct Board {
pub columns: Vec<Column>,
pub column: usize,
pub card: usize,
/// The body and comments of the selected ticket, when the detail view is open.
pub detail: Option<String>,
pub should_quit: bool,
worklane_dir: PathBuf,
digest: u64,
}
impl Board {
pub fn new(worklane_dir: &Path) -> Result<Self> {
let mut board = Board {
columns: Vec::new(),
column: 0,
card: 0,
detail: None,
should_quit: false,
worklane_dir: worklane_dir.to_path_buf(),
digest: 0,
};
board.reload()?;
Ok(board)
}
/// Re-read the tree only when the digest says it 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<bool> {
let now = digest(&self.worklane_dir);
if now == self.digest {
return Ok(false);
}
self.reload()?;
Ok(true)
}
fn reload(&mut self) -> Result<()> {
self.columns = status_dirs()
.into_iter()
.map(|status| {
let path = self.worklane_dir.join(status);
// An absent or unreadable directory is an empty column, not a missing
// one: the four statuses are the shape of the board.
let tickets = collect_ticket_items(&path).unwrap_or_default();
Column { status, tickets }
})
.collect();
self.digest = digest(&self.worklane_dir);
self.clamp();
// The selected ticket may have moved or gone, so the open detail follows it.
if self.detail.is_some() {
self.detail = self.selected().map(detail_of);
}
Ok(())
}
/// Keep the selection on a card that exists, after the board changes under it.
fn clamp(&mut self) {
if self.columns.is_empty() {
self.column = 0;
self.card = 0;
return;
}
self.column = self.column.min(self.columns.len() - 1);
let count = self.columns[self.column].tickets.len();
self.card = match count {
0 => 0,
count => self.card.min(count - 1),
};
}
pub fn selected(&self) -> Option<&TicketItem> {
self.columns
.get(self.column)
.and_then(|column| column.tickets.get(self.card))
}
/// Move between columns, keeping the card index where it can land.
pub fn select_column(&mut self, delta: isize) {
if self.columns.is_empty() {
return;
}
let last = self.columns.len() as isize - 1;
let next = (self.column as isize + delta).clamp(0, last);
self.column = next as usize;
self.clamp();
self.refresh_detail();
}
pub fn select_card(&mut self, delta: isize) {
let count = match self.columns.get(self.column) {
Some(column) => column.tickets.len(),
None => return,
};
if count == 0 {
return;
}
let next = (self.card as isize + delta).clamp(0, count as isize - 1);
self.card = next as usize;
self.refresh_detail();
}
/// Open the detail view on the selected card, or close it if it is already open.
pub fn toggle_detail(&mut self) {
self.detail = match self.detail {
Some(_) => None,
None => self.selected().map(detail_of),
};
}
fn refresh_detail(&mut self) {
if self.detail.is_some() {
self.detail = self.selected().map(detail_of);
}
}
}
/// The whole ticket as plain text: the body as `show` renders it, then 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(ticket: &TicketItem) -> String {
let content = std::fs::read_to_string(&ticket.path).unwrap_or_default();
let mut out = content_trim(&content, false);
let uuid = parse_ticket_field(&content, "ID");
let comments = match ticket.path.parent().and_then(|status| status.parent()) {
Some(worklane_dir) => {
read_comments(&worklane_dir.join("comments").join(&uuid)).unwrap_or_default()
}
None => Vec::new(),
};
out.push('\n');
out.push_str(&format_comments_with(&comments, false));
out
}
/// 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 = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(3), Constraint::Length(1)])
.split(area);
draw_columns(frame, board, rows[0]);
draw_footer(frame, board, rows[1]);
if let Some(detail) = &board.detail {
draw_detail(frame, detail, area);
}
}
fn draw_columns(frame: &mut Frame, board: &Board, area: Rect) {
let widths: Vec<Constraint> = board
.columns
.iter()
.map(|_| Constraint::Ratio(1, board.columns.len().max(1) as u32))
.collect();
let areas = Layout::default()
.direction(Direction::Horizontal)
.constraints(widths)
.split(area);
for (index, column) in board.columns.iter().enumerate() {
let focused = index == board.column;
let title = format!(" {} ({}) ", column.status, column.tickets.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()
}));
let mut lines: Vec<Line> = Vec::new();
for (card, ticket) in column.tickets.iter().enumerate() {
let selected = focused && card == board.card;
lines.extend(card_lines(ticket, selected));
}
// An empty status is an empty column, not a column that is not there.
frame.render_widget(Paragraph::new(lines).block(block), areas[index]);
}
}
/// One card: the priority mark and short id, the title, then owner and due.
fn card_lines(ticket: &TicketItem, selected: bool) -> Vec<Line<'static>> {
let (glyph, colour) = priority_mark(ticket.priority);
let emphasis = if selected {
Modifier::REVERSED
} else {
Modifier::empty()
};
vec![
Line::from(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),
),
]),
Line::from(Span::styled(
ticket.title.clone(),
Style::default().add_modifier(emphasis),
)),
Line::from(Span::styled(
format!("{} · {}", ticket.owner, ticket.due),
Style::default().fg(Color::Grey.into()),
)),
Line::from(""),
]
}
fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) {
let keys = match board.detail {
Some(_) => " ↑↓ scroll enter close q quit ",
None => " ←→ column ↑↓ card enter detail q quit ",
};
frame.render_widget(
Paragraph::new(Span::styled(keys, Style::default().fg(Color::Grey.into()))),
area,
);
}
fn draw_detail(frame: &mut Frame, detail: &str, area: Rect) {
// Inset, so the board stays visible around the edges and the overlay reads as one.
let width = area.width.saturating_sub(area.width / 5).max(20);
let height = area.height.saturating_sub(area.height / 6).max(6);
let overlay = 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),
};
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::Cyan.into()))
.title(Span::styled(
" ticket ",
Style::default().fg(Color::Orange.into()),
));
frame.render_widget(Clear, overlay);
frame.render_widget(
Paragraph::new(detail.to_string())
.block(block)
.wrap(Wrap { trim: false }),
overlay,
);
}
#[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.
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
}
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
}
/// The rendered buffer as lines of text, escapes and styling dropped.
fn render(board: &Board, width: u16, height: u16) -> Vec<String> {
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::<String>()
})
.collect()
}
#[test]
fn the_board_draws_the_four_statuses_as_columns() {
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 board = Board::new(&dir).unwrap();
let screen = render(&board, 120, 20).join("\n");
for heading in ["backlog (1)", "committed (1)", "reviewing (0)", "done (0)"] {
assert!(screen.contains(heading), "no {heading:?} in:\n{screen}");
}
}
/// 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 = Board::new(&dir).unwrap();
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}");
}
/// 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 board = Board::new(&dir).unwrap();
assert_eq!(board.columns.len(), 4);
let screen = render(&board, 120, 20).join("\n");
for status in status_dirs() {
assert!(screen.contains(&format!("{status} (0)")), "{screen}");
}
}
/// 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 board = Board::new(&dir).unwrap();
assert_eq!(board.columns.len(), 4);
assert!(render(&board, 120, 20).join("\n").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 = Board::new(&dir).unwrap();
assert_eq!(board.selected().map(|t| t.title.clone()), Some("Alpha".to_string()));
board.select_card(1);
assert_eq!(board.selected().map(|t| t.title.clone()), Some("Beta".to_string()));
// Clamped at both ends rather than wrapping
board.select_card(5);
assert_eq!(board.selected().map(|t| t.title.clone()), Some("Beta".to_string()));
board.select_card(-9);
assert_eq!(board.selected().map(|t| t.title.clone()), Some("Alpha".to_string()));
board.select_column(1);
assert_eq!(board.selected().map(|t| t.title.clone()), Some("Gamma".to_string()));
// reviewing is empty, so there is nothing selected there
board.select_column(1);
assert!(board.selected().is_none());
board.select_column(-9);
assert_eq!(board.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 = Board::new(&dir).unwrap();
board.select_card(2);
board.select_column(1);
assert_eq!(board.card, 0);
assert_eq!(board.selected().map(|t| t.title.clone()), Some("Delta".to_string()));
}
#[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 = Board::new(&dir).unwrap();
assert!(board.detail.is_none());
board.toggle_detail();
let detail = board.detail.clone().expect("no detail");
assert!(detail.contains("A description."), "{detail}");
assert!(detail.contains("Crit one"), "{detail}");
assert!(detail.contains("A note from elsewhere."), "{detail}");
assert!(detail.contains("bob"), "{detail}");
// Plain text, since ratatui would print an escape as literal bytes
assert!(!detail.contains('\x1b'), "escapes reached the detail view: {detail:?}");
board.toggle_detail();
assert!(board.detail.is_none());
}
/// 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 = Board::new(&dir).unwrap();
board.toggle_detail();
assert!(!board.detail.clone().unwrap().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.clone().unwrap().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 = Board::new(&dir).unwrap();
assert!(!board.tick().unwrap());
}
/// 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");
}
}
}