Compare commits

...
2 Commits
Author SHA1 Message Date
Ansho ReiandClaude Opus 5 c606b5ba43 (4edc7fa) Lay the tui card out as corners, with a due date and a criteria count, and bump to 0.8.5
A card was three left-aligned rows: mark and id, one row of title, then owner
and due as prose. The title got one row, so worklane's own titles, routinely
longer than a quarter of a terminal, were cut mid-word with nothing to say so.
The due sat at the end of the bottom row where nothing drew the eye to it, and
nothing showed how far along a ticket was.

    ●◐ (1b78a24)        2026-12-31
    The tui detail view cannot
    scroll, and the footer says…
    Ansho Rei                [3/9]

The title takes one row or two, wrapped on spaces, ellipsis when even two are
not enough, one row when one is enough. A card's height therefore depends on the
column's width, so `card_lines` and `card_height` take it, and `column_areas` is
now shared between the draw and `follow_selection`: `Ratio` hands its remainder
column to whichever slot it likes, and reproducing that arithmetic by hand is
how a measurement and a draw come to disagree about where a card starts.

A corner that will not fit is dropped whole rather than truncated or moved to a
row of its own. 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. Checked by eye at
120, 76 and 52 columns; at 52 the due goes and the count still fits.

The criteria count is a field on `TicketItem`, filled in `collect_ticket_items`
where the file is already being read, so a rescan pays for it once rather than
every draw re-reading every ticket body. Counted through `criteria()`, so a
checkbox in a description is neither counted here nor numbered by `show`, and
`None` rather than `[0/0]` when a ticket has none.

`due_date` cuts a due value back to its date only when it has one. The field is
not validated, see daa0e79, so it holds whatever was typed; taking the first
word regardless would turn "next friday" into "next". A set due is now the
timestamp colour per the colour guideline, which is what makes the corner worth
looking at, and an unset one stays grey like everywhere else.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 16:56:38 +02:00
Ansho ReiandClaude Opus 5 90b313952b (6d327df) Stop colour escapes leaking into the board's detail view, and bump to 0.8.4
The detail view renders with colour off, because ratatui draws styled spans and
an escape sequence inside a paragraph is not one. `detail_of` asks for that with
`content_trim(&content, false)`. Two paths ignored the argument and asked the
terminal instead.

`colorize_ordered` took no colour parameter at all and called `color_text`,
which is `paint(.., should_use_colors())`, and `content_trim` routes every
Implementation Plan line through it. In the TUI stdout is a terminal, so each
numbered step arrived as ESC[36m, the number, ESC[0m, then the text: exactly the
gap between the number and the step text where the reported artifact showed.
`colorize_line` did the same for a hand-written line inside a Metadata section,
and `colorize_bold` honoured its `enabled` flag on the early return and then
asked `should_use_colors()` again for the bold run, which made the flag a lie in
half the function.

`colorize_ordered` now takes the decision and is private, `content_trim` being
its only caller. `colorize_line` is deleted rather than given the argument: it
was a `pub` alias for `colorize_bold` with one caller, and asking the terminal
was the only thing it added, so `render_metadata_table` calls `colorize_bold`
with the decision it already holds.

Why this shipped, and the reason for the shape of the tests. The guard was an
assert that the detail view holds no escape byte, and it could not fail: a test
binary has no tty, so `should_use_colors()` was false and the leaking branch was
never taken. An absence is now asserted alongside a presence, `content_trim(..,
false)` carries no escape and `content_trim(.., true)` still colours, which pins
the flag as the only thing that decides. A third test scans this file for
`color_text` callers and fails on a new one; it also corrected the assumption
this commit started from, since the remaining caller is `ambiguous` and not
`display_ticket_items`.

The visible symptom is a terminal artifact that no test here can see, since
TestBackend applies cell updates and parses no escapes. What is proven is that
the escapes are gone, and that the CLI still paints its plan numbers cyan in a
pty, which is the condition the leak needed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 16:48:01 +02:00
5 changed files with 582 additions and 48 deletions
+10 -1
View File
@@ -98,6 +98,12 @@ and this file is for what someone changing worklane's own code needs.
- `detail_title` cuts the string itself instead of leaving it to ratatui, which truncates an overlong block title at whatever cell it reaches and would take the id with it. Cut against the inner width, so the id survives whole and the name ends in an ellipsis. The id goes first because that is how every other view addresses a ticket
- The detail view renders with colour off. ratatui draws styled spans, so an escape sequence in a paragraph would be printed as literal bytes. `content_trim` and `format_comments_with` take the colour decision for that reason
- Read only. Moving a card by keypress is a follow-up, deliberately kept out until the watch and render loop were solid
- **A card is four corners with the title between them:** mark and short id top left, due top right, owner bottom left, criteria count bottom right. The two numbers are in corners because that is where the eye goes for one, and both were invisible at the end of a line of prose
- The title takes one row or two, wrapped on spaces, with an ellipsis when even two are not enough. One row when one is enough: a second, blank row on every short ticket spends the column's height on nothing
- **A card's height therefore depends on the column's width**, so `card_lines` and `card_height` both take it. `column_areas` is shared between the draw and `follow_selection` for the same reason: `Ratio` hands the remainder column to whichever slot it likes, and reproducing that arithmetic by hand is how the measurement and the draw come to disagree about where a card starts
- **A corner that will not fit is dropped whole**, never 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
- The criteria count is a field on `TicketItem`, filled in `collect_ticket_items` where the file is already being read, and counted through `criteria()` so a checkbox in a description is not counted here or numbered by `show`. Do not count per card: that re-reads every ticket body on every draw instead of on the tick that changed something. `None` rather than `[0/0]` for a ticket with no criteria
- `due_date` cuts a due value back to its date only when it has one. The field is not validated (daa0e79), so it can hold a time or free text, and taking the first word regardless would turn "next friday" into "next"
- **Done is hidden until `d` asks for it.** Not a new opinion: `ls` already counts done in its summary and leaves it out of the listing. Done only grows, so a quarter of the width was going to the column least often read. The footer carries its count while it is hidden, which is the board's version of that summary line
- **Hiding is a change to what is drawn, never to what is read.** `reload` still scans the done directory and `digest` still watches it, so the footer count is right and revealing the column needs no rescan. Do not "optimise" that into a conditional scan
- `visible()` returns a prefix of `columns`, not a filter, which is what keeps `column` and `offsets` valid as indices into either. It is derived from where `DONE` actually sits rather than assuming the last slot, and `the_done_column_is_last` pins the assumption. A status inserted after done would otherwise hide two columns in silence
@@ -117,6 +123,9 @@ and this file is for what someone changing worklane's own code needs.
### Color and Output
- Use `color_text()` for coloured output — it respects `should_use_colors()` (terminal detection), and `paint()` is the same with the decision passed in
- **`color_text()` is for the CLI's own printing only. Anything reachable from `content_trim` takes the decision as an argument and calls `paint()`**, because the board renders with colour off and an escape sequence in a ratatui paragraph is drawn as literal bytes. `nothing_the_body_renders_asks_the_terminal_for_the_colour_decision` scans this file and fails on a new caller; the allowlist is `ambiguous`, which builds a failed-search message for stderr
- A function that takes an `enabled` flag must use it all the way down. `colorize_bold` honoured its flag on the early return and then asked `should_use_colors()` for the bold run, which made the flag a lie in half the function
- **A test that asserts an absence has to be paired with one that asserts the presence.** The guard for this, an assert that the detail view holds no escape byte, could not fail: a test binary has no tty, so `should_use_colors()` was false and the leaking branch was never taken. The pair is now `content_trim(.., false)` has no escape and `content_trim(.., true)` still colours, which pins the flag as the only thing that decides
- **The palette is the `Color` enum, not a string.** `Color::ansi()` gives the CLI its SGR sequence and `From<Color> for ratatui::style::Color` gives the TUI its equivalent, so a colour that exists for one renderer and not the other is a compile error. The stringly-typed version needed a test for exactly that, and a missing entry silently produced an empty prefix, which is how `magenta` came to be undefined
- Reset color with `\x1b[0m` after colored text
- Bold uses `\x1b[1;35m` (magenta bold)
@@ -133,7 +142,7 @@ and this file is for what someone changing worklane's own code needs.
- Grey is indexed colour 8 in the 256-colour form, not SGR 90 or 37. Both of those failed on a real palette: 90 leans on the bright-black slot and 37 can sit on top of the default foreground. `\x1b[38;5;8m` is byte for byte what crossterm emits for ratatui's `Color::DarkGray`, the grey frig and pantop use for dimmed rows
### Code Organization
- Colorization functions (`colorize_line`, `colorize_ordered`, `content_trim_colored`) handle markdown formatting
- Colorization functions (`colorize_ordered`, `colorize_bold`, `content_trim_colored`) handle markdown formatting. `colorize_line` is gone: it was a `pub` alias for `colorize_bold` with one caller, and the only thing it added was asking the terminal
- `show` renders the Metadata section as a two column table via `render_metadata_table`, not line by line. Column width is measured on the raw field names in characters and padding is applied before anything is styled: measuring a coloured string counts its escapes towards its width. `paint()` is `color_text()` with the colour decision passed in, which is what lets a test render both ways in one process
- The title is printed once, by `cmd_show`. `content_trim_colored` skips the `# ` heading in the file content
- Rules under headings are measured on the displayed name in characters, never on the raw line or in bytes
Generated
+1 -1
View File
@@ -1494,7 +1494,7 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.8.3"
version = "0.8.5"
dependencies = [
"anyhow",
"assert_cmd",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.8.3"
version = "0.8.5"
edition = "2024"
[dependencies]
+375 -36
View File
@@ -239,6 +239,10 @@ impl Board {
/// 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 the next draw will give this column, since a card's height depends
// on how much of the title has to wrap. Measured before the borrows below.
let width = card_width(screen, self.visible_count(), self.column);
let Some(column) = self.columns.get(self.column) else {
return;
};
@@ -246,18 +250,15 @@ impl Board {
return;
};
let height = |ticket: &TicketItem| card_height(ticket, width);
let start: u16 = column
.tickets
.get(..self.card)
.map(|before| before.iter().map(card_height).sum())
.map(|before| before.iter().map(height).sum())
.unwrap_or(0);
let end = start
+ column
.tickets
.get(self.card)
.map(card_height)
.unwrap_or(0);
let total: u16 = column.tickets.iter().map(card_height).sum();
let end = start + column.tickets.get(self.card).map(height).unwrap_or(0);
let total: u16 = column.tickets.iter().map(height).sum();
*slot = aligned_offset(*slot, start, end, column_text_height(screen), total);
}
@@ -400,15 +401,7 @@ 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 widths: Vec<Constraint> = columns
.iter()
.map(|_| Constraint::Ratio(1, columns.len().max(1) as u32))
.collect();
let areas = Layout::default()
.direction(Direction::Horizontal)
.constraints(widths)
.split(area);
let areas = column_areas(area, columns.len());
for (index, column) in columns.iter().enumerate() {
let focused = index == board.column;
@@ -435,15 +428,15 @@ fn draw_columns(frame: &mut Frame, board: &Board, area: Rect) {
// 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<Line> = Vec::new();
let mut starts: Vec<u16> = Vec::new();
for (card, ticket) in column.tickets.iter().enumerate() {
let selected = focused && card == board.card;
starts.push(lines.len() as u16);
lines.extend(card_lines(ticket, selected));
lines.extend(card_lines(ticket, selected, text.width));
}
let total = lines.len() as u16;
let text = areas[index].inner(Margin::new(1, 1));
let stored = board.offsets.get(index).copied().unwrap_or(0);
// The focused column follows its selection here as well as on the keypress:
@@ -470,8 +463,39 @@ fn draw_columns(frame: &mut Frame, board: &Board, area: Rect) {
}
/// The lines one card occupies, measured the way `draw_columns` renders it.
fn card_height(ticket: &TicketItem) -> u16 {
card_lines(ticket, false).len() as u16
///
/// 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(ticket: &TicketItem, width: u16) -> u16 {
card_lines(ticket, 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<Constraint> = (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, count: usize, column: usize) -> u16 {
// The footer takes the last row; the columns get everything above it, which is the
// area `draw` hands to `draw_columns`.
let board = Rect::new(0, 0, screen.width, screen.height.saturating_sub(1));
column_areas(board, count)
.get(column)
.map(|area| area.inner(Margin::new(1, 1)).width)
.unwrap_or(0)
}
/// The rows a column's cards share: above the footer row and inside the border.
@@ -501,8 +525,20 @@ fn aligned_offset(offset: u16, start: u16, end: u16, inner: u16, total: u16) ->
offset.min(total.saturating_sub(inner))
}
/// One card: the priority mark and short id, the title, then owner and due.
fn card_lines(ticket: &TicketItem, selected: bool) -> Vec<Line<'static>> {
/// 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…
/// 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.
fn card_lines(ticket: &TicketItem, selected: bool, width: u16) -> Vec<Line<'static>> {
let (glyph, colour) = priority_mark(ticket.priority);
let emphasis = if selected {
Modifier::REVERSED
@@ -510,8 +546,8 @@ fn card_lines(ticket: &TicketItem, selected: bool) -> Vec<Line<'static>> {
Modifier::empty()
};
vec![
Line::from(vec![
let mut lines = vec![corner_line(
vec![
Span::styled(
glyph.to_string(),
Style::default().fg(colour.into()).add_modifier(emphasis),
@@ -519,21 +555,154 @@ fn card_lines(ticket: &TicketItem, selected: bool) -> Vec<Line<'static>> {
Span::raw(" "),
Span::styled(
format!("({})", ticket.id),
Style::default()
.fg(Color::Red.into())
.add_modifier(emphasis),
Style::default().fg(Color::Red.into()).add_modifier(emphasis),
),
]),
],
due_span(&ticket.due),
width,
)];
lines.extend(title_lines(&ticket.title, width).into_iter().map(|line| {
Line::from(Span::styled(
ticket.title.clone(),
line,
Style::default().add_modifier(emphasis),
)),
Line::from(Span::styled(
format!("{} · {}", ticket.owner, ticket.due),
))
}));
lines.push(corner_line(
vec![Span::styled(
ticket.owner.clone(),
Style::default().fg(Color::Grey.into()),
)),
Line::from(""),
]
)],
ticket.criteria.map(|progress| {
Span::styled(
format!("[{}/{}]", progress.met, progress.total),
Style::default().fg(Color::Grey.into()),
)
}),
width,
));
lines.push(Line::from(""));
lines
}
/// 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<Span<'static>> {
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<Span<'static>>,
right: Option<Span<'static>>,
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<String> {
let width = width.max(1) as usize;
let mut rows: Vec<String> = 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<String> {
let chars: Vec<char> = 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) {
@@ -936,6 +1105,175 @@ mod tests {
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) {
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**: _None_\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<String> {
let board = Board::new(dir).unwrap();
let inner = card_width(Size { width, height }, 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 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<ratatui::style::Color> {
let board = Board::new(dir).unwrap();
let inner = card_width(Size { width, height: 20 }, 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 }, 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:?}");
}
}
/// 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 }, 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() {
@@ -1649,4 +1987,5 @@ mod tests {
}
}
}
+195 -9
View File
@@ -403,7 +403,7 @@ pub fn content_trim(content: &str, colored: bool) -> String {
// Implementation Plan - color numbers in cyan
if current_section == "## Implementation Plan" {
result.push_str(&colorize_ordered(line));
result.push_str(&colorize_ordered(line, colored));
result.push('\n');
continue;
}
@@ -454,7 +454,13 @@ pub fn content_trim(content: &str, colored: bool) -> String {
result
}
pub fn colorize_ordered(line: &str) -> String {
/// Colour the `1.` at the head of a numbered line, leaving the rest alone.
///
/// Takes the decision rather than asking for it. Asking is what put `\x1b[36m` and
/// `\x1b[0m` around every Implementation Plan number in the board's detail view,
/// which renders with colour off precisely because a paragraph is not a place an
/// escape sequence can go.
fn colorize_ordered(line: &str, colored: bool) -> String {
if line.chars().next().is_none_or(|c| !c.is_ascii_digit()) {
return line.to_string();
}
@@ -468,7 +474,7 @@ pub fn colorize_ordered(line: &str) -> String {
// still scanning digits
} else if *c == '.' && i + 1 < chars.len() && chars[i + 1] == ' ' {
let number = &line[..i + 1];
result.push_str(&color_text(number, Color::Cyan));
result.push_str(&paint(number, Color::Cyan, colored));
result.push_str(&line[i + 1..]);
return result;
} else {
@@ -558,7 +564,10 @@ fn render_metadata_table(lines: &[&str], colored: bool) -> String {
result.push_str(METADATA_GUTTER);
result.push_str(&metadata_value_cell(name, value, colored));
}
MetadataRow::Other(text) => result.push_str(&colorize_line(text)),
// The decision this row is rendered under, not the one the terminal
// would give: `colorize_line` asked `should_use_colors()` here, which is
// how escapes reached the board's detail view.
MetadataRow::Other(text) => result.push_str(&colorize_bold(text, colored)),
}
result.push('\n');
}
@@ -571,10 +580,6 @@ pub fn is_unknown_value(value: &str) -> bool {
trimmed == "_None_" || trimmed == "_Not set_" || trimmed == "-None-" || trimmed == "-Not set-"
}
pub fn colorize_line(line: &str) -> String {
colorize_bold(line, should_use_colors())
}
/// Replace `**bold**` with colour, or leave the line exactly as it is.
///
/// Taking `enabled` rather than asking makes both paths testable, and the
@@ -600,7 +605,9 @@ fn colorize_bold(line: &str, enabled: bool) -> String {
match (i + 2..chars.len()).find(|&at| is_delimiter(&chars, at)) {
Some(close) => {
let bold: String = chars[i + 2..close].iter().collect();
result.push_str(&color_text(&bold, Color::Magenta));
// `enabled`, not `should_use_colors()`. Asking again here made the
// flag a lie: the early return above respected it and this did not.
result.push_str(&paint(&bold, Color::Magenta, enabled));
i = close + 2;
}
// Unterminated: the rest is literal. The old scan walked off the end
@@ -1152,6 +1159,16 @@ pub fn parse_priority(content: &str) -> Priority {
priority_from_value(&parse_ticket_field(content, "Priority"))
}
/// How far along a ticket is: criteria ticked against criteria written.
///
/// `total` is never zero. A ticket with no criteria has no progress to show, and a card
/// reading `[0/0]` says less than a card saying nothing, so the absence is `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Progress {
pub met: usize,
pub total: usize,
}
pub struct TicketItem {
pub title: String,
pub owner: String,
@@ -1159,11 +1176,42 @@ pub struct TicketItem {
pub id: String,
pub created: String,
pub priority: Priority,
/// Ticked against total, or `None` for a ticket with no criteria.
///
/// Counted where the file is already being read, so the board pays nothing for it
/// beyond the count itself: the alternative, counting per card, would re-read every
/// ticket body on every draw rather than on the tick that changed something. The
/// listing ignores it, as it ignores `path`.
pub criteria: Option<Progress>,
/// The file this came from. The listing ignores it; the TUI opens it for the
/// detail view rather than resolving the ticket a second time.
pub path: std::path::PathBuf,
}
/// The date part of a due value, for a view with only a corner to spend on it.
///
/// The field is not validated, see daa0e79, so it holds whatever a caller typed: a bare
/// date, a date and a time, or free text. Only a real `YYYY-MM-DD` prefix is cut back
/// to. Taking the first word regardless would turn a free-text due into its first word,
/// which is worse than showing what is stored and letting the column decide.
pub fn due_date(due: &str) -> &str {
let candidate = due.split([' ', 'T']).next().unwrap_or(due);
match is_ymd(candidate) {
true => candidate,
false => due,
}
}
fn is_ymd(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& [0, 1, 2, 3, 5, 6, 8, 9]
.iter()
.all(|at| bytes[*at].is_ascii_digit())
}
/// Grey for a value that is not set, per the colour guideline.
///
/// `show` already did this in its metadata rendering, so the listing was the one
@@ -1265,6 +1313,18 @@ pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketI
let filename = e.path().file_stem()?.to_string_lossy().to_string();
let created_at = parse_ticket_field(&content, "Created At");
// Through `criteria()`, so the card and the numbers `show` prints cannot
// disagree: a checkbox written into a description is not a criterion there
// and is not counted here.
let counted = criteria(&content);
let progress = match counted.len() {
0 => None,
total => Some(Progress {
met: counted.iter().filter(|criterion| criterion.checked).count(),
total,
}),
};
Some(TicketItem {
title,
owner,
@@ -1272,6 +1332,7 @@ pub fn collect_ticket_items(status_path: impl AsRef<Path>) -> Result<Vec<TicketI
id: short_id(&filename).to_string(),
created: format_created_at(&created_at),
priority: parse_priority(&content),
criteria: progress,
path: e.path(),
})
})
@@ -1552,6 +1613,131 @@ mod tests {
assert_eq!(rendered, format!("Priority {glyph} _Not set_\n"));
}
/// A ticket with the two things that used to leak: a numbered plan, and a
/// hand-written line inside the Metadata section.
const BOTH_LEAKS: &str = "# T\n\n## Implementation Plan\n1. First step\n2. Second step\n\
\n## Metadata\n\n- **ID**: abc\nA **handwritten** note\n";
/// The bug: the board asks for `content_trim(content, false)` because a paragraph
/// is no place for an escape sequence, and two paths asked the terminal instead.
#[test]
fn the_body_carries_no_escape_when_the_colour_is_off() {
let rendered = content_trim(BOTH_LEAKS, false);
assert!(
!rendered.contains('\x1b'),
"an escape survived colour being off: {rendered:?}"
);
// And the content is all still there, in plain form.
assert!(rendered.contains("1. First step"), "{rendered:?}");
assert!(rendered.contains("**handwritten**"), "{rendered:?}");
}
/// The other half of the pair, and the one that makes the first mean something:
/// with the flag on, both paths still colour. Without this, the passing test above
/// could be a colouring path that was simply deleted.
#[test]
fn the_body_colours_the_plan_number_and_a_metadata_note_when_the_colour_is_on() {
let rendered = content_trim(BOTH_LEAKS, true);
assert!(
rendered.contains(&format!("{}1.", Color::Cyan.ansi())),
"the plan number lost its colour: {rendered:?}"
);
assert!(
rendered.contains(&format!("{}handwritten", Color::Magenta.ansi())),
"the bold run lost its colour: {rendered:?}"
);
}
/// The flag has to be the only thing that decides, or the disabled path is just
/// the terminal's answer in disguise — which is why the leak survived a test
/// asserting the detail view holds no escapes. In a test binary there is no tty,
/// so `should_use_colors()` is false and the leaking branch was never taken.
#[test]
fn nothing_the_body_renders_asks_the_terminal_for_the_colour_decision() {
let callers = callers_of_color_text(include_str!("util.rs"));
// `ambiguous` is the one that may: it builds the candidate list for a failed
// search, reaches the user on stderr, and is not reachable from `content_trim`.
assert_eq!(
callers,
vec!["ambiguous".to_string()],
"`color_text` asks `should_use_colors()`. Everything reachable from \
`content_trim` has to take the decision as an argument and pass it to \
`paint` instead, because the board renders with colour off and an escape \
in a ratatui paragraph is drawn as literal bytes. If the new caller really \
is CLI-only, add it here and say why."
);
}
/// Which functions in this file call `color_text`, by name, definitions and the
/// test module excluded.
fn callers_of_color_text(source: &str) -> Vec<String> {
let body = match source.find("\n#[cfg(test)]") {
Some(end) => &source[..end],
None => source,
};
let mut current = String::new();
let mut callers = Vec::new();
for line in body.lines() {
if let Some(rest) = line.strip_prefix("fn ").or_else(|| line.strip_prefix("pub fn ")) {
current = rest.split('(').next().unwrap_or_default().to_string();
continue;
}
if line.contains("color_text(") && !callers.contains(&current) {
callers.push(current.clone());
}
}
callers
}
/// The field is not validated, see daa0e79, so the card cannot trust it to be a
/// bare date. Only a real date prefix is cut back to: free text is left alone,
/// since turning "next friday" into "next" would be a worse answer than the width.
#[test]
fn a_due_value_is_cut_back_to_its_date_only_when_it_has_one() {
assert_eq!(due_date("2026-12-31"), "2026-12-31");
assert_eq!(due_date("2026-12-31 09:30:00"), "2026-12-31");
assert_eq!(due_date("2026-12-31T09:30:00Z"), "2026-12-31");
assert_eq!(due_date("_Not set_"), "_Not set_");
assert_eq!(due_date("next friday"), "next friday");
assert_eq!(due_date("2026-1-1 09:30"), "2026-1-1 09:30");
}
/// The count on a card comes from `criteria()`, the same function that numbers them
/// in `show`, so the two cannot disagree about what a criterion is.
#[test]
fn collect_ticket_items_counts_the_criteria_show_would_number() {
let dir = std::env::temp_dir().join(format!("worklane-count-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&dir).unwrap();
let write = |name: &str, body: &str| {
fs::write(
dir.join(format!("11111111-0000-4000-8000-00000000000{name}.md")),
format!("# T{name}\n\n{body}\n\n## Metadata\n\n- **Owner**: alice\n"),
)
.unwrap();
};
// A checkbox in the description is not a criterion, in either view.
write(
"1",
"## Description\n- [x] not a criterion\n\n## Acceptance Criteria\n- [x] One\n- [ ] Two",
);
write("2", "## Acceptance Criteria\n_No acceptance criteria provided._");
let items = collect_ticket_items(&dir).unwrap();
let counted: Vec<Option<Progress>> = items.iter().map(|item| item.criteria).collect();
assert!(counted.contains(&Some(Progress { met: 1, total: 2 })), "{counted:?}");
assert!(counted.contains(&None), "a ticket with no criteria got a count: {counted:?}");
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_section_rule_matches_the_width_of_its_name() {
let rendered = content_trim_colored("# T\n\n## Description\nbody\n");