From 96cddc14adf7009b5dacaa0d4cfcae6cad9c433a Mon Sep 17 00:00:00 2001 From: Ansho Rei Date: Thu, 27 Aug 2026 23:36:13 +0200 Subject: [PATCH] (53ffb94) Run the command the prompt parsed, and redraw the board on what it wrote, and bump to 0.32.16 The prompt parsed a line and named what it resolved to. This is the half that does it: the parsed command goes to the same cmd_* handler main.rs hands it to, against the selected tab's own .worklane, with a Sink over a buffer collecting what the handler says instead of stdout. One dispatch table, not two. main.rs's match on Command is lifted into `dispatch`, over the command, the start path and the sink, and both callers go through it. A second copy in tui.rs would drift the first time a command was added and would drift silently, since both halves go on compiling; the match is exhaustive so a new verb cannot fall into an `_` arm either. Only `tui` is matched outside it, in main, because the board is that table's caller rather than an entry in it, and reached from the prompt it is refused in those words. Two things the board has to do that the CLI never had to. It reloads unconditionally after a command returns rather than waiting for the digest, so a reader does not watch their own mv take up to a poll interval to appear, and either way, since a handler that failed part way through has still written. And the selection is restored by uuid across that reload: mv puts the card in another column, set --title renames its file, and a filter can drop it out of view, so the slot is not the ticket. Where the board cannot follow it, the notice says so and which key shows it. What the handler says is what the board reports, word for word. Notice therefore holds as many lines as the command used, and notice_on_row is the one rule for where they go: one line on the footer row where a copy's notice has always gone, anything else as a box at the foot of the columns. A box rather than more rows of footer, because a footer that grew and shrank as notices came and went would reflow the columns on every keypress. A handler that errors leaves the prompt open with the line intact, the usual cause being an ambiguous id. `without_escapes` in util.rs is the guard at the seam. A handler's own output is plain because the sink is, but an error message is built with color_text, which asks the process about its stdout and under the board answers yes about a terminal the message is not going to; a ratatui paragraph prints an escape rather than obeying it. That is 6d327df's fault on a new path. The merge tab is refused for now, resolved by index rather than by the tab's name, which is a label two projects can share. Routing by the card a command names is ebc5755. Not done here, and both tracked: check with no criterion still reaches ask_which_criterion and reads a raw-mode stdin, which is 6d37042's criterion 4 and commented there; and check_blockers warns about a dangling blocker with eprintln!, which reaches the alternate screen because it never passes through dispatch's result, filed as c680e24. --- AGENTS.md | 15 +- Cargo.lock | 2 +- Cargo.toml | 2 +- src/main.rs | 168 ++++++----- src/tui.rs | 821 +++++++++++++++++++++++++++++++++++++++++++++++----- src/util.rs | 41 ++- 6 files changed, 894 insertions(+), 155 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 17f4a17..5e7b009 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md ## Project Structure -- `src/main.rs` - dispatch, the SIGPIPE reset, and the TUI event loop +- `src/main.rs` - `dispatch`, the one mapping from a parsed command to its handler, the SIGPIPE reset, and the TUI event loop - `src/command.rs` - CLI argument definitions using clap derive - `src/completions.rs` - the generated completion script and the fish half that asks the board - `src/handlers.rs` - one `cmd_*` per subcommand @@ -353,15 +353,22 @@ and this file is for what someone changing worklane's own code needs. ### The Command Prompt - **`prompt: Option` is the whole mode**, the shape `search` and `detail` use: open and content cannot disagree, and closing it leaves nothing to reset. `Prompt` carries the line, the cursor as a byte offset into it, and `refused`, which is `Search::missed` with something to say -- **`Board::prompt_key` is third in the pre-dispatch**, beside `search_key` and `picker_key` and on the same contract: while a command is being typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the project tabs, and `ctrl-c` is the one key declined. It takes no `Size`, because nothing it does measures the board — the keypress that will is 53ffb94, which redraws on what the command wrote. Only one of the two prompts can be open at once: `:` is reachable from the action arms alone, and while either has the keyboard the other's key is a character in a line +- **`Board::prompt_key` is third in the pre-dispatch**, beside `search_key` and `picker_key` and on the same contract: while a command is being typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the project tabs, and `ctrl-c` is the one key declined. It takes a `Size` for enter's sake: running a command reloads the board and then has to bring the ticket it moved back into view, which is the measurement `follow_selection` takes. Only one of the two prompts can be open at once: `:` is reachable from the action arms alone, and while either has the keyboard the other's key is a character in a line - **`esc` and `enter` are the mode's own keys and are answered in `prompt_key`; everything else belongs to the line and goes to `Prompt::key`.** That is also what keeps the borrow straight, since closing the prompt takes the whole board and editing takes only the prompt. Left, right, home, end, backspace and `ctrl-w` behave as they do in a shell, and `ctrl-w` eats the separators behind the cursor before the word behind those, so one press at the end of `mv 1b78a24 ` takes the id. There is deliberately no `tab`: suggesting the selected ticket is 00a14e7, and until then it is a key that must not reach the tabs - **The grammar is clap's, with nothing restated.** The line is tokenised by `split_line`, the binary's own name goes in front, and the arguments go to the same `Cli` definition the shell reaches, so a flag added to a command is typeable here the day it is added. Through `Cli::command().try_get_matches_from_mut` rather than `try_parse_from`, for what the matches give back: `command_name` walks the subcommands to name what resolved (`campaign show`, not `campaign`) instead of a `match` over every variant, which would be a second list of every verb the CLI has and one that goes stale silently - **`refused` is cleared by an edit and not by a movement.** The message is about the line, and moving the cursor does not change the line. `Prompt::key` clears it in the three arms that write to the line - **A line that ends inside a quote never reaches clap.** That is what `Unclosed` is for: a grammar complaint about a sentence nobody finished describes the wrong thing. Enter on an empty line, or one of nothing but separators, closes the prompt with nothing said, the way `esc` does — the bare form of the CLI opens a board and there is one on the screen -- **Enter resolves the line and does not run it**, so the notice says `parsed, not run yet` rather than reading like a move that happened, and the prompt's own key is drawn as `↵ check`. Both are replaced by 53ffb94, which is the ticket that runs it; naming the key `run` here would be the fault 1b78a24 was, in the other direction +- **Enter runs it, through `main.rs`'s `dispatch` and never through a handler this file names.** That match is the one mapping from a parsed command to the function that performs it: `main` calls it with its own stdout and the working directory, `Board::run` calls it with a buffer and the selected tab's root. A second copy inside `tui.rs` would drift the first time a command was added, and it would drift *silently*, since both halves go on compiling. The match is exhaustive so a new verb cannot fall into an `_` arm and do nothing, and `main_and_the_prompt_run_one_dispatch_table` reads both files as text to pin it. Only `tui` is matched outside the table, in `main`, because the board is that table's caller rather than an entry in it; reached from the prompt it is refused in those words +- **`from_arg_matches` on the same matches gives `run` the typed values.** One parse, two readings: `command_name` walks the subcommands to name what resolved and `from_arg_matches` reconstructs the `Cli`. A `match` over every `Command` variant to get one or the other would be a second list of every verb the CLI has +- **The handler's own words are what the board reports, word for word.** Those messages are written for a person already, and a second set kept here would go stale the first time one of them changed. The sink is a buffer, so the words come back as text and the board styles them; it is plain for the same reason `Detail` holds spans, since a ratatui paragraph prints an escape rather than obeying it. An error never goes through a sink at all — `color_text` asks the *process* about its stdout, which under the board answers yes about a terminal the message is not going to — so `error_lines` runs `without_escapes` over it and puts each cause on a line of its own +- **A handler that errors leaves the prompt open with the line intact.** The usual cause is an ambiguous id, and the fix is two more characters rather than the whole line retyped from `:`. Ambiguity is an `Err` carrying the candidates, not a print and an `exit`, which is what makes it safe to reach from here at all +- **The reload after a command is unconditional, and runs whether it failed or not.** `tick` reloads on the digest, which is right for a change made in another pane and needless latency for one the board just made: the reader would watch their own `mv` take up to a poll interval to appear. Either way, because a handler that failed part way through has still written +- **The selection is restored by uuid across that reload, never by index.** `mv` puts the card in another column, `set --title` renames its file, and a filter can drop it out of view entirely, so the slot is not the ticket. `Board::reselect` has three answers: the card is in a drawn column and the selection goes to it; it is on the board but in a column the rotation is hiding, which is where `--status done` lands by default, so the notice says where it went and which key shows it; or the filter no longer holds it, which is said too, since a card vanishing from under the highlight reads as a bug in the board +- **The merge tab is refused, for now.** It is the one tab that is not a board — its cards came from several `.worklane` directories and it is none of them — so `Board::current_project` answers `None` there and the command is refused rather than landing on whichever project came first. Routing by the card a command names is ebc5755. The project is resolved by index and not by the tab's name, which is a label two projects can share: e1d79c3 is exactly that, and a write routed by name would be that bug with a file changing at the end of it +- **`Notice` holds as many lines as the command used, and `Board::notice_on_row` decides where they go.** One line with nothing else holding the row draws on the footer, where a copy's notice has always drawn. Anything else — several lines, or any answer at all while the prompt is still open on an error — draws as a box at the foot of the columns, cut to what the columns leave with the dropped count on its last row. A box rather than more rows of footer, and that is the whole reason it is an overlay: a footer that grew and shrank as notices came and went would reflow the columns on every keypress, moving every card the reader is looking at. `draw` and `draw_footer` both ask `notice_on_row`, so the two cannot come to disagree and draw the message twice or not at all - **What a refused line shows is clap's own message with the usage block cut off**, which is also what drops the `--help` line after it. `--help` is the exception: it parses as an error of the kind that means *print this* and what it would print is a page, so it is caught and answered in a row's worth of words, or clap's help lands on the alternate screen the way an unsunk `println!` would. `--version` goes through the ordinary path, because what it prints is one line by construction. `ColorChoice::Never` on the command, so nothing that reaches the row carries an escape - **The keys' width comes off the row before the line is windowed**, so a long command does not push them off the end; a message takes the row from the keys instead, since the reader has just been told something and `esc` and `enter` still do what they did. `prompt_window` anchors the window on the cursor's right edge, which costs the text *after* the cursor on a long line: keeping both ends needs a scroll offset in state, and the draw is where the width is known and the state is not writable -- `: command` is named in every footer state, because the key works in every one of them +- `: command` is named in every footer state, because the key works in every one of them, and the prompt's own key is drawn as `↵ run` ### Splitting a Typed Line - **`split_line` is the whole module, and it knows nothing about `Board`.** The command prompt reads one string and clap reads an argv, so `comment 1b78a24 the offset was never passed` has to be tokenised before anything can parse it: split on whitespace it is five arguments and `comment` takes two. A pure function over the line and the cursor is what makes every rule reachable from a unit test, and it is in a file of its own rather than in `tui.rs`, which is eleven thousand lines already diff --git a/Cargo.lock b/Cargo.lock index 0d48613..a5eea93 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1503,7 +1503,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.32.15" +version = "0.32.16" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 148ef16..9b53980 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.32.15" +version = "0.32.16" edition = "2024" [dependencies] diff --git a/src/main.rs b/src/main.rs index e37882d..c227f86 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +use std::path::Path; + use anyhow::Result; use clap::Parser; @@ -50,76 +52,16 @@ fn main() -> Result<()> { let mut sink = Sink::std(); let result = match cli.command { + // The board is the one thing `dispatch` does not run, and it is matched here + // rather than there because it is the *caller* of that table rather than an entry + // in it: a `tui` reached from the command prompt would enter the alternate screen + // a second time from inside the draw loop. `dispatch` refuses it in those words. + // // No subcommand opens the board, the way a bare `frig` does, and with no path // it opens the board above the working directory. None => run_tui(&[], &start), Some(Command::Tui { paths }) => run_tui(&paths, &start), - Some(Command::Init) => cmd_init(&start, &mut sink), - Some(Command::Add(args)) => cmd_add(&args, &start, &mut sink), - Some(Command::Ls(args)) => { - let worklane_dir = find_worklane_dir(&start)?; - cmd_ls(&args, &worklane_dir, &mut sink) - } - Some(Command::Show { id }) => { - let worklane_dir = find_worklane_dir(&start)?; - cmd_show(&id, &worklane_dir, &mut sink) - } - Some(Command::Mv(args)) => cmd_mv(&args, &start, &mut sink), - Some(Command::Set(args)) => cmd_set(&args, &start, &mut sink), - Some(Command::Append(args)) => cmd_append(&args, &start, &mut sink), - Some(Command::Relate(args)) => cmd_relate(&args, &start, &mut sink), - Some(Command::Chown(args)) => cmd_chown(&args, &start, &mut sink), - Some(Command::Check(args)) => cmd_check(&args, true, &start, &mut sink), - Some(Command::Uncheck(args)) => cmd_check(&args, false, &start, &mut sink), - Some(Command::Comment { - ticket, - body, - actor, - actor_from_git, - }) => cmd_comment(&ticket, &body, &actor, actor_from_git, &start, &mut sink), - Some(Command::Campaign { command }) => match command { - CampaignCommand::Add(args) => cmd_campaign_add(&args, &start, &mut sink), - CampaignCommand::Ls { ids } => { - let worklane_dir = find_worklane_dir(&start)?; - cmd_campaign_ls(&worklane_dir, ids, &mut sink) - } - CampaignCommand::Set(args) => cmd_campaign_set(&args, &start, &mut sink), - CampaignCommand::Append(args) => cmd_campaign_append(&args, &start, &mut sink), - CampaignCommand::Show { campaign } => { - let worklane_dir = find_worklane_dir(&start)?; - cmd_campaign_show(&campaign, &worklane_dir, &mut sink) - } - }, - Some(Command::Assign { - campaign, - ticket, - actor, - actor_from_git, - }) => cmd_assign(&campaign, &ticket, &actor, actor_from_git, &start, &mut sink), - // The bare form and `ls` are one arm: `worklane tags` was the listing before the - // group existed and the fish completion still calls it that way, so the two - // spellings cannot be allowed to drift into two behaviours. - Some(Command::Tags { command }) => match command { - None | Some(TagCommand::Ls) => { - let worklane_dir = find_worklane_dir(&start)?; - cmd_tags(&worklane_dir, &mut sink) - } - Some(TagCommand::Add(args)) => cmd_tag_add(&args, &start, &mut sink), - Some(TagCommand::Set(args)) => cmd_tag_set(&args, &start, &mut sink), - }, - // No board either, for the reason `install-skill` has none: a completion script - // is generated from the clap definition and is the same wherever it is run. - Some(Command::Completions { shell }) => { - completions::generate(shell, sink.as_write()).map_err(Into::into) - } - // No board is looked for: the point of the skill is to teach an agent worklane - // before there is a `.worklane` anywhere. - Some(Command::InstallSkill { skill, force, print }) => { - cmd_install_skill(skill.as_deref(), force, print, &mut sink) - } - // No board either, and one agent rather than both: opencode loads the tool file, - // Claude Code has no path for one. - Some(Command::InstallTool { force, print }) => cmd_install_tool(force, print, &mut sink), + Some(command) => dispatch(&command, &start, &mut sink), }; // The board (and every handler) own their own writing, so flush what the last one @@ -128,6 +70,93 @@ fn main() -> Result<()> { result } +/// Run one parsed command against the board at or above `start`, saying what it did +/// through `sink`. +/// +/// **The one mapping from a parsed command to the function that performs it.** `main` +/// calls it with the process's stdout and the working directory; the command prompt on +/// the board calls it with a buffer and the selected tab's own root, and reads back what +/// the handler said. A second copy of this match inside `tui.rs` would be a copy that +/// drifted the first time a command was added, and it would drift *silently*, since both +/// halves would go on compiling. +/// +/// A command added to [`Command`] therefore lands here once and is runnable from both. +/// The match is exhaustive for exactly that reason: there is no `_` arm for a new verb to +/// fall into and do nothing. +pub fn dispatch(command: &Command, start: &Path, sink: &mut Sink) -> Result<()> { + match command { + // Reachable only from the prompt, since `main` takes this arm before it gets + // here. A board is not something a board can open. + Command::Tui { .. } => Err(anyhow::anyhow!("`tui` opens a board, and you are on one")), + Command::Init => cmd_init(start, sink), + Command::Add(args) => cmd_add(args, start, sink), + Command::Ls(args) => { + let worklane_dir = find_worklane_dir(start)?; + cmd_ls(args, &worklane_dir, sink) + } + Command::Show { id } => { + let worklane_dir = find_worklane_dir(start)?; + cmd_show(id, &worklane_dir, sink) + } + Command::Mv(args) => cmd_mv(args, start, sink), + Command::Set(args) => cmd_set(args, start, sink), + Command::Append(args) => cmd_append(args, start, sink), + Command::Relate(args) => cmd_relate(args, start, sink), + Command::Chown(args) => cmd_chown(args, start, sink), + Command::Check(args) => cmd_check(args, true, start, sink), + Command::Uncheck(args) => cmd_check(args, false, start, sink), + Command::Comment { + ticket, + body, + actor, + actor_from_git, + } => cmd_comment(ticket, body, actor, *actor_from_git, start, sink), + Command::Campaign { command } => match command { + CampaignCommand::Add(args) => cmd_campaign_add(args, start, sink), + CampaignCommand::Ls { ids } => { + let worklane_dir = find_worklane_dir(start)?; + cmd_campaign_ls(&worklane_dir, *ids, sink) + } + CampaignCommand::Set(args) => cmd_campaign_set(args, start, sink), + CampaignCommand::Append(args) => cmd_campaign_append(args, start, sink), + CampaignCommand::Show { campaign } => { + let worklane_dir = find_worklane_dir(start)?; + cmd_campaign_show(campaign, &worklane_dir, sink) + } + }, + Command::Assign { + campaign, + ticket, + actor, + actor_from_git, + } => cmd_assign(campaign, ticket, actor, *actor_from_git, start, sink), + // The bare form and `ls` are one arm: `worklane tags` was the listing before the + // group existed and the fish completion still calls it that way, so the two + // spellings cannot be allowed to drift into two behaviours. + Command::Tags { command } => match command { + None | Some(TagCommand::Ls) => { + let worklane_dir = find_worklane_dir(start)?; + cmd_tags(&worklane_dir, sink) + } + Some(TagCommand::Add(args)) => cmd_tag_add(args, start, sink), + Some(TagCommand::Set(args)) => cmd_tag_set(args, start, sink), + }, + // No board either, for the reason `install-skill` has none: a completion script + // is generated from the clap definition and is the same wherever it is run. + Command::Completions { shell } => { + completions::generate(*shell, sink.as_write()).map_err(Into::into) + } + // No board is looked for: the point of the skill is to teach an agent worklane + // before there is a `.worklane` anywhere. + Command::InstallSkill { skill, force, print } => { + cmd_install_skill(skill.as_deref(), *force, *print, sink) + } + // No board either, and one agent rather than both: opencode loads the tool file, + // Claude Code has no path for one. + Command::InstallTool { force, print } => cmd_install_tool(*force, *print, sink), + } +} + // ---------------------------------------------------------------------- tui -- /// Restore the terminal whatever happens. @@ -222,9 +251,10 @@ fn run_tui(paths: &[std::path::PathBuf], start: &std::path::Path) -> Result<()> // And the command prompt, third, on the same contract: while a command is being // typed `q` is a letter, `d` leaves the columns alone and `tab` stays out of the - // project tabs. No screen, because nothing it does measures the board yet. The - // rule is `Board::prompt_key`, where a test can reach it. - if board.prompt_key(key) { + // project tabs. It takes the screen because enter runs the command and then has + // to bring the ticket it moved back into view. The rule is `Board::prompt_key`, + // where a test can reach it. + if board.prompt_key(key, screen) { continue; } diff --git a/src/tui.rs b/src/tui.rs index 599974c..a163611 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -6,7 +6,10 @@ //! 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. +//! **Reads by keypress, writes by command.** Every key on the board observes; `:` opens a +//! prompt whose line is a worklane command, run through the same `dispatch` the shell +//! reaches. Nothing here is a second front end to the board: there is no grammar the CLI +//! does not have, and no handler this file calls directly. use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, HashMap}; @@ -20,10 +23,10 @@ use ratatui::Frame; use ratatui::layout::{Constraint, Direction, Layout, Margin, Rect, Size}; use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span, Text}; -use ratatui::widgets::{Block, Borders, Clear, Paragraph, Tabs, Wrap}; +use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph, Tabs, Wrap}; use crate::campaign::{CAMPAIGNS_DIR, CampaignIndex, Standing}; -use crate::command::Cli; +use crate::command::{Cli, Command}; use crate::history::{HistoryPart, history_parts, history_root, read_history}; use crate::split::{Unclosed, split_line}; use crate::tag::{NO_ANNOTATION, TAGS_FILE, TagIndex}; @@ -869,7 +872,24 @@ fn refusal(err: &clap::Error) -> String { .join(" ") } -/// A line the footer carries in place of the key list until the next keypress. +/// What a handler's failure says on the board: its own message, and every cause under it +/// on a line of its own. +/// +/// The message is the handler's for the reason its output is — `mv` names each open +/// blocker on a line and tells the reader about `-f`, and a sentence written here would +/// have to be kept in step with that one. Painted, since an error is built with +/// `color_text` rather than through a sink, so the escapes come off before it is drawn. +/// +/// The causes are joined by newlines rather than by `: `, which is what anyhow's own +/// `Debug` does, because the box has the rows and a chain folded onto one line is where +/// the useful half ends up off the right edge. +fn error_lines(err: &anyhow::Error) -> String { + let mut lines = vec![err.to_string()]; + lines.extend(err.chain().skip(1).map(|cause| cause.to_string())); + without_escapes(&lines.join("\n")).trim_end().to_string() +} + +/// What the board has to say in words until the next keypress takes it away. /// /// The board otherwise says everything by drawing it, and a copy leaves nothing on the /// screen to look at: the id was already there and the clipboard is somewhere else. So @@ -878,6 +898,13 @@ fn refusal(err: &clap::Error) -> String { /// `failed` is "nothing reached the clipboard", not "an error occurred": an empty column /// and a terminal that refused the write are the same answer to the reader, who pressed /// a key and has nothing to paste. Both are drawn in red for the reason `no match` is. +/// +/// **The text is what a command said, so it is as many lines as the command used.** A +/// handler's answer is written for a person and already spells its own paragraphs; cutting +/// it to the one row the footer has would drop the half of `mv` that names the blockers. +/// Where it is drawn follows from that and is `Board::notice_on_row`: one line goes on the +/// footer row where a copy's has always gone, and anything the row cannot hold is a box +/// over the columns instead. #[derive(Debug)] pub struct Notice { pub text: String, @@ -898,6 +925,15 @@ impl Notice { failed: true, } } + + /// The lines to draw, never none: an empty notice is one empty line rather than a box + /// with nothing in it, since `lines()` on `""` yields nothing at all. + fn lines(&self) -> Vec<&str> { + match self.text.lines().collect::>() { + rows if rows.is_empty() => vec![""], + rows => rows, + } + } } /// The open campaign picker: which row the highlight is on, and where the list is @@ -1335,6 +1371,34 @@ impl Board { &mut self.tabs[self.tab] } + /// The project whose board the tab in view is showing, or nothing on the merge. + /// + /// The merge tab is the one tab that is not a board: its cards came from several + /// `.worklane` directories and the tab itself is none of them. Routing a write there + /// is ebc5755, which resolves the board off the card a command names; until then a + /// command typed on it is refused rather than landing on whichever project came first. + /// + /// Resolved by index rather than by the tab's name, which is a label two projects can + /// share — e1d79c3 is exactly that, and a write routed by name would be that bug with + /// a file changing at the end of it. + fn current_project(&self) -> Option<&Project> { + // The merge takes index 0 when there is one, so the projects start one along. + let first = usize::from(self.tabbed()); + self.projects.get(self.tab.checked_sub(first)?) + } + + /// Where a command typed on this tab runs, which is the project *above* its board. + /// + /// A handler takes the path to start looking from and walks up to the first + /// `.worklane`, the way every shell invocation does, so what it wants is the directory + /// holding the board rather than the board itself. Handing it `.worklane` would walk + /// from inside the board and find the same one, but only by accident of there being + /// nothing in the way; a `.worklane/.worklane` would take the write. + fn command_root(&self) -> Option { + let dir = &self.current_project()?.dir; + Some(dir.parent().unwrap_or(dir).to_path_buf()) + } + /// Re-read the trees only when the digest says one of them moved. /// /// The scan is the expensive part, not the draw, so this is what the tick guards. @@ -1543,6 +1607,28 @@ impl Board { self.current().selected() } + /// Whether the footer row itself carries the notice, rather than a box over the columns. + /// + /// **One rule, two readers**: `draw_footer` asks it before spending the row, and `draw` + /// asks it to decide whether to put the box up. Written twice they would come to + /// disagree, and the way that shows is a message drawn in both places or in neither. + /// + /// The row holds a notice when it is one line and nothing else has taken the row. A + /// command's answer is as many lines as the command used, and an error leaves the + /// prompt open on the row it would otherwise have gone on, so both of those go in the + /// box. It is where a copy's notice has always gone, which is the case this keeps + /// unchanged: one line, on the row, no box. + pub fn notice_on_row(&self) -> bool { + let Some(notice) = &self.notice else { + return false; + }; + + notice.lines().len() == 1 + && self.prompt.is_none() + && self.search.is_none() + && self.picker.is_none() + } + /// Move between columns, keeping the card index where it can land. /// /// Inert while the frame holds the selection. The frame spans the width of the board, so @@ -2119,9 +2205,9 @@ impl Board { /// belongs to the line and goes to `Prompt::key`. That split is also what keeps the /// borrow straight: closing the prompt takes the whole board, editing takes the prompt. /// - /// No screen: nothing here measures the board. The keypress that will is 53ffb94, which - /// redraws on what the command wrote. - pub fn prompt_key(&mut self, key: KeyEvent) -> bool { + /// The screen is enter's: a command that moves a ticket has to leave the selection on + /// it, and bringing a card into view is the measurement `follow_selection` takes. + pub fn prompt_key(&mut self, key: KeyEvent, screen: Size) -> bool { if self.prompt.is_none() { return false; } @@ -2133,7 +2219,7 @@ impl Board { match key.code { KeyCode::Esc if !control => self.prompt = None, - KeyCode::Enter if !control => self.submit(), + KeyCode::Enter if !control => self.submit(screen), _ => { if let Some(prompt) = &mut self.prompt { prompt.key(key, control); @@ -2144,7 +2230,7 @@ impl Board { true } - /// What enter does with the line: name the command it resolved to, or say why it did + /// What enter does with the line: run the command it resolved to, or say why it did /// not resolve to one. /// /// The grammar is clap's, with nothing restated. The line is tokenised the way a shell @@ -2153,15 +2239,15 @@ impl Board { /// command is typeable here the day it is added, and no list of verbs lives on the /// board to go stale. /// - /// A line that resolves closes the prompt and says what it resolved to, in the footer's - /// one channel for saying something in words. **It does not run it** — running is - /// 53ffb94 — so the notice says so rather than reading like a move that happened. + /// The matches are what `command_name` walks to name what resolved; `from_arg_matches` + /// on the same matches is what gives `run` the typed values. One parse, two readings, + /// rather than a second `match` over every `Command` variant to name a verb. /// /// A line that does not resolve keeps the prompt open with the line and the cursor /// exactly as they were, and puts the message on the row, so a typo is corrected in /// place instead of retyped from `:`. That is `Search`'s hit-closes-miss-stays rule, /// and the reason both are true of one field. - fn submit(&mut self) { + fn submit(&mut self, screen: Size) { let Some(prompt) = &self.prompt else { return }; // Before clap sees anything, because a line ending inside a quote is not a line @@ -2185,17 +2271,157 @@ impl Board { let mut command = ::command().color(clap::ColorChoice::Never); let argv = std::iter::once(command.get_name().to_string()).chain(split.args); - match command.try_get_matches_from_mut(argv) { - // No subcommand is the bare form, which opens a board: there is one on the - // screen, so there is nothing to name and nothing to do but close. - Ok(matches) => { - self.prompt = None; - if let Some(named) = command_name(&matches) { - self.notice = Some(Notice::done(format!("{named}: parsed, not run yet"))); - } - } - Err(err) => self.refuse(refusal(&err)), + let matches = match command.try_get_matches_from_mut(argv) { + Ok(matches) => matches, + Err(err) => return self.refuse(refusal(&err)), + }; + let named = command_name(&matches); + let parsed = match ::from_arg_matches(&matches) { + Ok(cli) => cli, + // Unreachable in practice, the derive reading back the matches it just made. + // Reported rather than unwrapped, since a panic here takes the terminal down + // with the alternate screen still on. + Err(err) => return self.refuse(refusal(&err)), + }; + + // No subcommand is the bare form, which opens a board: there is one on the screen, + // so there is nothing to name and nothing to do but close. + let Some(command) = parsed.command else { + self.prompt = None; + return; + }; + + self.run(&command, named.as_deref(), screen); + } + + /// Run a parsed command against the tab in view, and redraw the board on what it wrote. + /// + /// The handler is the same one `main` reaches, through the same `dispatch`: this is a + /// caller of that table, never a second copy of it. It writes into a buffer rather than + /// stdout, which under the board is the alternate screen in raw mode, so nothing a + /// handler says can land on the frame — that is what `Sink` is for, and it is why the + /// buffer is plain: the words come back as text and the board styles them itself. + /// + /// **What the handler said is what the board reports.** Those messages are already + /// written for a person, and a second set kept here would go stale the first time one + /// of them changed. A handler that says nothing gets the verb and `done`, since the + /// row saying nothing at all reads as a keypress that missed. + /// + /// A handler that returns `Err` leaves the prompt open with the line intact: the usual + /// cause is an ambiguous id, and the fix is two more characters rather than the whole + /// line retyped from `:`. + /// + /// The reload is unconditional and runs either way. `tick` reloads on the digest, which + /// is right for a change made in another pane and needless latency for one the board + /// just made — the reader would watch their own `mv` take up to a poll interval to + /// appear. Either way, because a handler that failed part way through has still + /// written, and the columns must not go on drawing what is no longer on disk. + fn run(&mut self, command: &Command, named: Option<&str>, screen: Size) { + let Some(root) = self.command_root() else { + self.refuse("a command needs a board: type it on a project tab".to_string()); + return; + }; + + // Taken before the reload, while the indices still point at the card the reader was + // on. `mv` puts it in another column, `set --title` renames its file and a filter + // can drop it out of view entirely, so an index kept across the rebuild is a + // different ticket and the reader loses their place on every write. + // + // A ticket whose ID field is unset reads as the sentinel every unset field reads + // as, which is not an address: two malformed tickets would carry the same one and + // the selection would land on whichever came first. Nothing to follow, so the + // clamp has it, the way it does for a selection that was on the frame. + let held = self + .selected() + .map(|card| (card.ticket.uuid.clone(), card.ticket.id.clone())) + .filter(|(uuid, _)| !is_unknown_value(uuid)); + + let mut buffer: Vec = Vec::new(); + let outcome = { + let mut sink = Sink::buffer(&mut buffer); + crate::dispatch(command, &root, &mut sink).and_then(|()| sink.flush()) + }; + // Plain by construction, since the sink is: stripped anyway, because an escape + // drawn into a ratatui paragraph is printed rather than obeyed, and this is the + // one seam where a handler's bytes become a frame. + let said = without_escapes(&String::from_utf8_lossy(&buffer)) + .trim_end() + .to_string(); + + if let Err(err) = self.reload() { + self.notice = Some(Notice::failed(format!("reload failed: {err}"))); + return; } + + // The board is redrawn on what the command wrote before anything is said about it, + // so the sentence about where the selection went is about the board now on screen. + let moved = held.and_then(|(uuid, id)| self.reselect(&uuid, &id, screen)); + + match outcome { + Err(err) => self.notice = Some(Notice::failed(error_lines(&err))), + Ok(()) => { + self.prompt = None; + let words = match said.is_empty() { + true => format!("{}: done", named.unwrap_or("the command")), + false => said, + }; + self.notice = Some(Notice::done(match moved { + Some(gone) => format!("{words}\n{gone}"), + None => words, + })); + } + } + } + + /// Put the selection back on the ticket it was on before the reload, and say so when + /// the board no longer draws it. + /// + /// By uuid, never by index, for the reason `Tab::campaign` is a uuid: the slot is not + /// the ticket. A `mv` moves the card to another column and a `set --title` renames its + /// file, and either leaves the old indices pointing at whatever has taken that place. + /// + /// Three answers, and the second is the one worth the sentence. The card is in a drawn + /// column, so the selection goes to it. It is on the board but in a column the rotation + /// is hiding, which is where a `mv --status done` lands by default: the selection + /// cannot follow it there, so the notice says where it went and which key shows it. Or + /// it is not on the tab at all, which is a filter that no longer holds it — say that + /// too, since a card silently vanishing from under the highlight reads as a bug. + fn reselect(&mut self, uuid: &str, id: &str, screen: Size) -> Option { + let visibility = self.visibility; + let tab = self.current(); + + // Where the card is now, and whether that column is one of the drawn ones. + let found = tab.columns.iter().enumerate().find_map(|(index, column)| { + let card = column.cards.iter().position(|card| card.ticket.uuid == uuid)?; + Some((index, card, column.status)) + }); + let drawn = tab.visible_count(visibility); + + let gone = match found { + Some((column, card, _)) if column < drawn => { + let tab = self.current_mut(); + tab.column = column; + tab.card = card; + // The frame cannot hold the selection while a card does, and a command run + // from the frame is a command run about no ticket at all. + tab.focus = Focus::Cards; + None + } + // On the board, in a column `d` has not revealed. The status is named rather + // than the column number, since that is what the reader asked for. + Some((_, _, status)) => { + self.current_mut().clamp(visibility); + Some(format!("({id}) is in {status}, which d shows")) + } + None => { + self.current_mut().clamp(visibility); + Some(format!("({id}) is no longer on this tab")) + } + }; + + self.follow_selection(screen); + self.refresh_detail(); + gone } /// Keep the prompt open, with the line untouched, carrying what enter had to say. @@ -3072,6 +3298,87 @@ pub fn draw(frame: &mut Frame, board: &Board) { if let Some(picker) = &board.picker { draw_picker(frame, board.current(), picker, area); } + // Last, so it is over everything: it is the newest thing said, it lives one keypress, + // and what it is usually about is the ticket the overlay behind it is showing. + // + // A box rather than more rows of footer, and that is the whole reason it is an overlay: + // a footer that grew and shrank as notices came and went would reflow the columns on + // every keypress, moving every card the reader is looking at. Nothing here measures + // into `Chrome`, so the columns are the same height with the box up as without it. + if !board.notice_on_row() + && let Some(notice) = &board.notice + { + draw_notice_box(frame, notice, rows[BOARD_ROW]); + } +} + +/// The notice as a box at the foot of the columns, for the answers the footer row cannot +/// hold: a command that said several lines, and any command at all while the prompt is +/// still open on an error. +/// +/// Bottom left, against the row the one-line notice would have used, so a reader who has +/// just pressed enter looks in one place either way. Sized to the text rather than to the +/// board — a two line answer draws a two line box — and cut to what the columns leave when +/// the answer is longer than the screen, with the count of what was dropped on the last +/// row so a cut never passes for the whole of it. +/// +/// Red for a failure, where `no match` and the refused line are red, and cyan otherwise: +/// the accent this tool draws its keys and its focused border in. +fn draw_notice_box(frame: &mut Frame, notice: &Notice, area: Rect) { + let accent = match notice.failed { + true => Color::BrightRed, + false => Color::Cyan, + }; + + // Two rows of border and at least one of text, and the same on the other axis: a box + // too small for a line of the answer says nothing at all, and is worse than a cut one. + // The width guard is also what keeps the clamp below from being asked for a range that + // runs backwards, which panics — and a panic here takes the terminal down with it. + let Some(room) = area.height.checked_sub(2).filter(|rows| *rows > 0) else { + return; + }; + if area.width < 3 { + return; + } + + let lines = notice.lines(); + let mut rows: Vec = lines.iter().take(room as usize).map(|l| l.to_string()).collect(); + if lines.len() > room as usize { + // The last row spends itself saying so, rather than the box ending mid-answer as + // though that were all of it. + let dropped = lines.len() - room as usize + 1; + rows.pop(); + rows.push(format!("… {dropped} more lines")); + } + + // A border either side of the text, and a space either side of that, the padding the + // overlay's own prose keeps. + let width = rows.iter().map(|row| row.chars().count()).max().unwrap_or(0); + let width = (width as u16).saturating_add(4).clamp(1, area.width); + let height = rows.len() as u16 + 2; + + let box_area = Rect { + x: area.x, + y: area.y + area.height - height, + width, + height, + }; + + let text: Vec = rows + .into_iter() + .map(|row| Line::from(Span::styled(row, Style::default().fg(accent.into())))) + .collect(); + + frame.render_widget(Clear, box_area); + frame.render_widget( + Paragraph::new(text).block( + Block::default() + .borders(Borders::ALL) + .border_style(Style::default().fg(accent.into())) + .padding(Padding::horizontal(1)), + ), + box_area, + ); } /// The rows of the frame, in the order `screen_rows` lays them out. @@ -4047,7 +4354,13 @@ fn draw_footer(frame: &mut Frame, board: &Board, area: Rect) { // beside the list would move every key in it, and the row is the only place on the // board that is not a ticket. Ordered after the prompt, which is an input and cannot // be covered, and a keypress clears the notice before it can open one anyway. - if let Some(notice) = &board.notice { + // + // Only the notice the row can hold, which is `Board::notice_on_row` rather than a + // condition written here: `draw` asks the same question to decide whether to put the + // box up, and two spellings of it would draw the message twice or not at all. + if board.notice_on_row() + && let Some(notice) = &board.notice + { draw_notice(frame, notice, area); return; } @@ -4221,11 +4534,10 @@ const PROMPT_OPENING: &str = " :"; /// what they did. It is brightred beside the line it is about, the one thing on the row /// that is neither a key nor what was typed, which is where `no match` sits. /// -/// `check` and not `run`: enter resolves the line and names it, and running it is 53ffb94. -/// A row naming a key by what it does not do yet is the fault 1b78a24 was, in the other -/// direction. +/// `run` and not `check`: enter hands the line to the same handler the shell reaches, and +/// the row has to say which of the two it is about to do. fn draw_prompt(frame: &mut Frame, prompt: &Prompt, area: Rect) { - let keys = key_hints(&[("↵", "check"), ("esc", "cancel")]); + let keys = key_hints(&[("↵", "run"), ("esc", "cancel")]); let spent: usize = PROMPT_OPENING.chars().count() + KEY_GAP.chars().count() + keys @@ -7329,7 +7641,7 @@ approach"; /// Type a whole line into an open command prompt, one key at a time, the way it arrives. fn type_line(board: &mut Board, line: &str) { for c in line.chars() { - assert!(board.prompt_key(letter(c)), "'{c}' was not taken"); + assert!(board.prompt_key(letter(c), SCREEN), "'{c}' was not taken"); } } @@ -7347,7 +7659,7 @@ approach"; /// Press enter on the open prompt, which is the whole of what this ticket does. fn submit(board: &mut Board) { - assert!(board.prompt_key(typed(KeyCode::Enter)), "enter was not taken"); + assert!(board.prompt_key(typed(KeyCode::Enter), SCREEN), "enter was not taken"); } /// The prompt takes the row, names its own two keys, and the board is still behind it. @@ -7360,7 +7672,7 @@ approach"; let screen = render(&board, SCREEN.width, SCREEN.height); let row = screen.last().expect("no rows rendered"); - assert!(row.contains("↵ check"), "{row}"); + assert!(row.contains("↵ run"), "{row}"); assert!(row.contains("esc cancel"), "{row}"); assert!(!row.contains("quit"), "the key list survived the prompt:\n{row}"); assert!( @@ -7390,41 +7702,41 @@ approach"; board.open_prompt(); type_line(&mut board, "mv 1111111"); - board.prompt_key(typed(KeyCode::Home)); + board.prompt_key(typed(KeyCode::Home), SCREEN); type_line(&mut board, "x"); assert_eq!(prompt_line(&board), Some("xmv 1111111"), "home did not reach the front"); // Backspace takes the character before the cursor, not the last one on the line. - board.prompt_key(typed(KeyCode::Backspace)); + board.prompt_key(typed(KeyCode::Backspace), SCREEN); assert_eq!(prompt_line(&board), Some("mv 1111111")); - board.prompt_key(typed(KeyCode::Right)); - board.prompt_key(typed(KeyCode::Right)); + board.prompt_key(typed(KeyCode::Right), SCREEN); + board.prompt_key(typed(KeyCode::Right), SCREEN); type_line(&mut board, "!"); assert_eq!(prompt_line(&board), Some("mv! 1111111")); - board.prompt_key(typed(KeyCode::Left)); - board.prompt_key(typed(KeyCode::Backspace)); + board.prompt_key(typed(KeyCode::Left), SCREEN); + board.prompt_key(typed(KeyCode::Backspace), SCREEN); assert_eq!(prompt_line(&board), Some("m! 1111111")); // `ctrl-w` takes the word before the cursor, and the separators behind the cursor // with it, so a second press takes the word before those rather than the space. - board.prompt_key(typed(KeyCode::End)); - board.prompt_key(ctrl('w')); + board.prompt_key(typed(KeyCode::End), SCREEN); + board.prompt_key(ctrl('w'), SCREEN); assert_eq!(prompt_line(&board), Some("m! ")); - board.prompt_key(ctrl('w')); + board.prompt_key(ctrl('w'), SCREEN); assert_eq!(prompt_line(&board), Some("")); // Nothing to take is nothing done, at either end. - board.prompt_key(typed(KeyCode::Backspace)); - board.prompt_key(ctrl('w')); - board.prompt_key(typed(KeyCode::Left)); + board.prompt_key(typed(KeyCode::Backspace), SCREEN); + board.prompt_key(ctrl('w'), SCREEN); + board.prompt_key(typed(KeyCode::Left), SCREEN); assert_eq!(prompt_line(&board), Some("")); // A cursor counted in bytes still moves by whole characters, so a backspace over a // multi-byte one takes the character rather than splitting it. type_line(&mut board, "comment é"); - board.prompt_key(typed(KeyCode::Backspace)); + board.prompt_key(typed(KeyCode::Backspace), SCREEN); assert_eq!(prompt_line(&board), Some("comment ")); } @@ -7452,7 +7764,7 @@ approach"; typed(KeyCode::BackTab), typed(KeyCode::PageDown), ] { - assert!(board.prompt_key(key), "{key:?} was not taken"); + assert!(board.prompt_key(key, SCREEN), "{key:?} was not taken"); } assert!(!board.should_quit, "typing 'q' quit the board"); @@ -7472,11 +7784,11 @@ approach"; board.open_prompt(); assert!( - !board.prompt_key(ctrl('c')), + !board.prompt_key(ctrl('c'), SCREEN), "the prompt ate ctrl-c and left no way off the board" ); - assert!(board.prompt_key(ctrl('d')), "ctrl-d fell through to the 'd' arm"); + assert!(board.prompt_key(ctrl('d'), SCREEN), "ctrl-d fell through to the 'd' arm"); assert_eq!(prompt_line(&board), Some(""), "a control key typed its letter"); } @@ -7491,7 +7803,7 @@ approach"; board.open_prompt(); type_line(&mut board, "mv 1111111"); - assert!(board.prompt_key(typed(KeyCode::Esc)), "esc was not taken"); + assert!(board.prompt_key(typed(KeyCode::Esc), SCREEN), "esc was not taken"); assert!(board.prompt.is_none(), "the prompt stayed open"); assert!(board.detail.is_some(), "esc reached the overlay arm"); assert!(!board.should_quit, "esc reached the quit arm"); @@ -7499,7 +7811,7 @@ approach"; assert!(board.notice.is_none(), "a cancel said something in the footer"); // And the next esc is the overlay's again. - assert!(!board.prompt_key(typed(KeyCode::Esc))); + assert!(!board.prompt_key(typed(KeyCode::Esc), SCREEN)); board.open_prompt(); submit(&mut board); @@ -7514,36 +7826,388 @@ approach"; assert!(board.notice.is_none(), "a line of spaces named a command"); } - /// A line clap takes closes the prompt and is named, in the footer's one channel for - /// saying something in words. It is *not* run here, and the notice has to say so. + /// A board a command can actually be run against. + /// + /// `board_dir` stands in for a `.worklane` without being one, which is enough to read + /// a tree and not enough to write to it: a handler resolves its board by walking up + /// from the path it is given, the way every shell invocation does, so what the prompt + /// hands it has to be a directory with a real `.worklane` under it. + /// + /// The fixture is returned beside the board because dropping it takes the tree with + /// it, and a board reading a deleted tree draws nothing. + fn runnable() -> (Fixture, Board) { + let root = Fixture::new("worklane-run").child("alpha"); + let dir = root.join(".worklane"); + for status in status_dirs() { + std::fs::create_dir_all(dir.join(status)).unwrap(); + } + write_ticket(&dir, "backlog", "11111111-0000-4000-8000-000000000000", "Alpha first", ""); + write_ticket(&dir, "backlog", "22222222-0000-4000-8000-000000000000", "Beta second", ""); + write_ticket( + &dir, + "committed", + "33333333-0000-4000-8000-000000000000", + "Gamma third", + "", + ); + + let board = Board::new(projects(&[], &root).unwrap()).unwrap(); + (root, board) + } + + /// Type a line into a fresh prompt and press enter on it. + fn run_line(board: &mut Board, line: &str) { + board.open_prompt(); + type_line(board, line); + submit(board); + } + + /// Which column a title is in, by the status it is drawn under, or nothing when the + /// tab is not holding that ticket at all. + fn column_of(board: &Board, title: &str) -> Option<&'static str> { + board.current().columns.iter().find_map(|column| { + let held = column.cards.iter().any(|card| card.ticket.title == title); + held.then_some(column.status) + }) + } + + /// What the whole frame says, rows joined, for an assertion about a box that is not on + /// the footer row. + fn screen_text(board: &Board) -> String { + render(board, SCREEN.width, SCREEN.height).join("\n") + } + + /// The point of the ticket: the line clap took is handed to the same handler `main` + /// hands it to, against the selected tab's own board, and the file on disk changes. + /// + /// And the board shows it at once. `tick` reloads on a digest, which is right for a + /// change made in another pane and needless latency for one the board just made, so the + /// run reloads unconditionally — which is what the tick reporting nothing to do + /// afterwards says. #[test] - fn enter_names_the_command_the_line_resolved_to_and_closes_the_prompt() { - let dir = searchable(); - let mut board = one_board(&dir); + fn enter_runs_the_command_against_the_selected_tab_and_redraws_at_once() { + let (root, mut board) = runnable(); + let dir = root.join(".worklane"); + assert_eq!(column_of(&board, "Alpha first"), Some("backlog")); - board.open_prompt(); - type_line(&mut board, "mv 1111111 --status committed"); - submit(&mut board); + run_line(&mut board, "mv 1111111 --status committed"); - assert!(board.prompt.is_none(), "the prompt stayed open on a line clap took"); - let row = footer(&board, SCREEN.width, SCREEN.height); - assert!(row.contains("mv"), "the command was not named: {row}"); - assert!(row.contains("not run"), "the notice reads like the move happened: {row}"); + assert!(board.prompt.is_none(), "the prompt stayed open: {:?}", refused(&board)); + assert!( + std::fs::read_dir(dir.join("committed")) + .unwrap() + .filter_map(|entry| entry.ok()) + .any(|entry| entry.file_name().to_string_lossy().starts_with("11111111")), + "the file did not move" + ); - // A command inside a group is named by the words that reach it, off the matches - // rather than a list of verbs kept here. - board.open_prompt(); - type_line(&mut board, "campaign show v1"); - submit(&mut board); - let row = footer(&board, SCREEN.width, SCREEN.height); - assert!(row.contains("campaign show"), "the group was not named: {row}"); + // Drawn from the reload the command did, not from a tick nobody has run yet. + assert_eq!(column_of(&board, "Alpha first"), Some("committed")); + assert!( + !board.tick().unwrap(), + "the reload was left to the next tick, so the reader waits a poll interval for \ + their own write" + ); - // And the reason the line is tokenised at all: `comment` takes two arguments, so a - // body split on whitespace would be five and clap would refuse it. - board.open_prompt(); - type_line(&mut board, "comment 1111111 \"the offset was never passed\""); - submit(&mut board); + // And the quoted body, which is the reason the line is tokenised at all: split on + // whitespace `comment` would be handed five arguments and clap would refuse it. + run_line(&mut board, "comment 1111111 \"the offset was never passed\""); assert!(board.prompt.is_none(), "a quoted body was refused: {:?}", refused(&board)); + let log = read_history(&dir, "11111111-0000-4000-8000-000000000000").unwrap(); + assert!( + log.iter() + .any(|entry| entry.body == "the offset was never passed"), + "the quoted body did not arrive whole: {log:?}" + ); + } + + /// What the handler said is what the board reports, word for word: those messages are + /// already written for a person, and a second set kept on the board would go stale the + /// first time one of them changed. + /// + /// Compared against the same command run straight through `dispatch`, which is also + /// what says the words were *collected* rather than printed: a handler that reached + /// stdout would leave the notice empty and the frame corrupt. + #[test] + fn the_footer_reports_the_handlers_own_words() { + let (root, mut board) = runnable(); + + let mut buffer: Vec = Vec::new(); + let command = + ::try_parse_from(["worklane", "chown", "alice", "2222222"]) + .unwrap() + .command + .unwrap(); + { + let mut sink = Sink::buffer(&mut buffer); + crate::dispatch(&command, &root, &mut sink).unwrap(); + sink.flush().unwrap(); + } + let said = String::from_utf8(buffer).unwrap().trim_end().to_string(); + assert!(!said.is_empty(), "the handler said nothing to compare against"); + + // The same command again, this time through the prompt. `chown` is idempotent in + // its wording, so the two answers are the same sentence. + run_line(&mut board, "chown alice 2222222"); + let notice = board.notice.as_ref().expect("the command said nothing"); + assert_eq!(notice.text, said, "the board rewrote what the handler said"); + assert!(!notice.failed, "a command that worked was reported as a failure"); + } + + /// An answer of several lines is drawn as the lines it has. The footer is one row, so + /// it cannot be the place: a box takes the foot of the columns instead, and the row + /// keeps the one-line notice a copy has always put there. + #[test] + fn an_answer_of_several_lines_is_drawn_as_the_lines_it_has() { + let (_root, mut board) = runnable(); + + run_line(&mut board, "relate 1111111 --blocked-by 2222222"); + assert!(board.prompt.is_none(), "relate was refused: {:?}", refused(&board)); + + // `mv` names every open blocker on a line of its own and then says what `-f` does, + // which is three lines and the reason none of them may be dropped. + run_line(&mut board, "mv 1111111 --status committed"); + let notice = board.notice.as_ref().expect("the refusal said nothing"); + assert!(notice.failed, "a refused move was reported as a success"); + assert!(notice.lines().len() >= 3, "the answer was cut: {:?}", notice.text); + assert!(!board.notice_on_row(), "three lines were put on a one-row footer"); + + let screen = screen_text(&board); + for line in notice.lines() { + assert!(screen.contains(line.trim()), "`{line}` never reached the frame:\n{screen}"); + } + + // The one-line case is unchanged: the row, and no box. + board.notice = Some(Notice::done("copied 1111111")); + board.prompt = None; + assert!(board.notice_on_row(), "a one-line notice was taken off the row"); + assert!( + footer(&board, SCREEN.width, SCREEN.height).contains("copied 1111111"), + "the row lost the notice it has always carried" + ); + } + + /// A handler that errors leaves the prompt open with the line exactly as it was: the + /// usual cause is an ambiguous id, and the fix is two more characters rather than the + /// whole line retyped from `:`. + #[test] + fn a_handler_that_errors_reports_it_and_leaves_the_prompt_open() { + let (root, mut board) = runnable(); + + run_line(&mut board, "mv 1111111 --status reviewing"); + + assert_eq!( + prompt_line(&board), + Some("mv 1111111 --status reviewing"), + "the line was not kept for correcting" + ); + let notice = board.notice.as_ref().expect("the error said nothing"); + assert!(notice.failed, "an error was reported as a success"); + assert!( + notice.text.contains("one stage"), + "not the handler's own words: {notice:?}" + ); + assert!(!board.notice_on_row(), "the error took the row the prompt is holding"); + assert!( + screen_text(&board).contains("one stage"), + "the error never reached the frame" + ); + + // And nothing was written, so the correction is a real one. + assert_eq!(column_of(&board, "Alpha first"), Some("backlog")); + + // An ambiguous id is the case this shape exists for: the fix is two more + // characters on a line the reader has already typed correctly. + write_ticket( + &root.join(".worklane"), + "backlog", + "11119999-0000-4000-8000-000000000000", + "Alpha twin", + "", + ); + board.prompt = None; + run_line(&mut board, "mv 1111 --status committed"); + assert_eq!( + prompt_line(&board), + Some("mv 1111 --status committed"), + "the line was lost" + ); + let notice = board.notice.as_ref().expect("an ambiguous id said nothing"); + assert!( + notice.failed && notice.lines().len() > 1, + "the candidates were cut: {notice:?}" + ); + } + + /// The selection stays on the ticket, not on the slot. `mv` puts the card in another + /// column and `set --title` renames its file, and an index kept across the reload + /// points at whatever has taken that place. + #[test] + fn the_selection_follows_the_ticket_the_command_moved() { + let (_root, mut board) = runnable(); + assert_eq!(selected_title(&board).as_deref(), Some("Alpha first")); + + run_line(&mut board, "mv 1111111 --status committed"); + assert_eq!( + selected_title(&board).as_deref(), + Some("Alpha first"), + "the selection stayed on the slot rather than the ticket" + ); + assert_eq!(board.current().column, 1, "the selection did not follow into committed"); + + // Renaming the file is the other half: the card is addressed by uuid, so a new + // title and a new filename change nothing about which card is selected. + run_line(&mut board, "set 1111111 --title \"Alpha renamed\""); + assert_eq!(selected_title(&board).as_deref(), Some("Alpha renamed")); + } + + /// And when the board cannot follow it, it says where it went. A card vanishing from + /// under the highlight with nothing said reads as a bug in the board. + #[test] + fn the_notice_says_where_a_ticket_went_when_the_board_stops_drawing_it() { + let (_root, mut board) = runnable(); + + // Done is hidden until `d` reveals it, so this is where a finished ticket goes by + // default and the selection cannot go with it. + run_line(&mut board, "mv 1111111 --status done -f"); + let notice = board.notice.as_ref().expect("nothing was said"); + assert!( + notice.text.contains("(1111111) is in done"), + "the ticket went out of view unannounced: {notice:?}" + ); + assert!(notice.text.contains('d'), "nothing said which key shows it: {notice:?}"); + assert_ne!( + selected_title(&board).as_deref(), + Some("Alpha first"), + "the selection followed a card into a column that is not drawn" + ); + + // A filter that no longer holds it is the other way off the tab. Two tickets carry + // the tag, so clearing one leaves the tag — and the filter — standing. + let (_root, mut board) = runnable(); + run_line(&mut board, "set 1111111 --tags urgent"); + run_line(&mut board, "set 2222222 --tags urgent"); + board.select_filter(Filter::Tag("urgent".to_string()), SCREEN); + assert_eq!(column_of(&board, "Alpha first"), Some("backlog")); + + run_line(&mut board, "set 1111111 --clear tags"); + assert_eq!(column_of(&board, "Alpha first"), None, "the filter kept it after all"); + let notice = board.notice.as_ref().expect("nothing was said"); + assert!( + notice.text.contains("(1111111) is no longer on this tab"), + "the filter dropped it unannounced: {notice:?}" + ); + } + + /// The merge tab is the one tab that is not a board: its cards came from several + /// `.worklane` directories and it is none of them. Routing a write by the card it names + /// is ebc5755; until then a command typed there is refused rather than landing on + /// whichever project happened to come first. + #[test] + fn a_command_typed_on_the_merge_tab_is_refused_rather_than_guessed_at() { + let (_first, one) = runnable(); + let (_second, two) = runnable(); + let of = |board: &Board| { + let project = board + .current_project() + .expect("a single board has a project tab"); + Project { + name: project.name.clone(), + dir: project.dir.clone(), + } + }; + let mut board = Board::new(vec![of(&one), of(&two)]).unwrap(); + + assert_eq!(board.tab, 0, "the merge is not the tab the board opens on"); + run_line(&mut board, "mv 1111111 --status committed"); + + let message = refused(&board).expect("the merge tab ran the command somewhere"); + assert!(message.contains("project tab"), "{message}"); + assert_eq!( + prompt_line(&board), + Some("mv 1111111 --status committed"), + "the line was lost on a refusal" + ); + + // On a project tab the same line runs, against that project's own board. + board.select_tab(1, SCREEN); + board.prompt = None; + run_line(&mut board, "mv 1111111 --status committed"); + assert!( + board.prompt.is_none(), + "a project tab refused it too: {:?}", + refused(&board) + ); + assert_eq!(column_of(&board, "Alpha first"), Some("committed")); + } + + /// Nothing a handler writes reaches the alternate screen, which is the whole reason the + /// sink exists: under the board stdout *is* the frame, in raw mode. + /// + /// Two halves. The words come back as text, which is what having them in the notice at + /// all proves. And nothing carrying an escape is drawn, which the sink answers for + /// ordinary output and `error_lines` has to answer for an error, since a message built + /// with `color_text` asks the process about its stdout rather than the sink. + #[test] + fn nothing_a_handler_writes_reaches_the_alternate_screen() { + let (_root, mut board) = runnable(); + + run_line(&mut board, "mv 1111111 --status committed"); + let notice = board.notice.as_ref().expect("the words went somewhere else"); + assert!(!notice.text.contains('\x1b'), "an escape reached the notice: {notice:?}"); + + // A paragraph prints an escape rather than obeying it, so one on the frame is + // literal bytes over the columns. + assert!(!screen_text(&board).contains('\x1b'), "an escape reached the drawn frame"); + + // The error path, which never goes through a sink at all. + let painted = anyhow::anyhow!( + "Cannot move backward from {} to {}", + paint("done", Color::Orange, true), + paint("backlog", Color::Orange, true), + ); + let drawn = error_lines(&painted); + assert!( + !drawn.contains('\x1b'), + "a painted error would be drawn as bytes: {drawn:?}" + ); + assert!( + drawn.contains("from done to backlog"), + "the words were stripped too: {drawn}" + ); + } + + /// `main` and the prompt run one dispatch table. Two would be two, and the second would + /// drift the first time a command was added — silently, since both halves go on + /// compiling. + /// + /// Read as text, the way the pre-dispatch's own contract is: neither is reachable from + /// a test. The needles are built rather than written out, or this test's own source + /// would be the second copy it is looking for. + #[test] + fn main_and_the_prompt_run_one_dispatch_table() { + let main = include_str!("main.rs"); + let here = include_str!("tui.rs"); + + assert!( + main.contains("pub fn dispatch("), + "the table is not a function both can call" + ); + + for verb in ["mv", "add", "comment", "check", "assign", "relate", "set"] { + let handler = format!("cmd_{verb}("); + assert!(main.contains(&handler), "`{handler}` is not in the table"); + assert!( + !here.contains(&handler), + "tui.rs reaches `{handler}` itself, which is a second dispatch table" + ); + } + + // What the board calls instead. + assert!( + here.contains("crate::dispatch(command, &root, &mut sink)"), + "the board does not go through the table" + ); } /// A line clap will not take keeps the prompt open with the line intact, so a typo is @@ -7574,7 +8238,7 @@ approach"; ); // The message is about the line, so moving the cursor keeps it and an edit takes it. - board.prompt_key(typed(KeyCode::Left)); + board.prompt_key(typed(KeyCode::Left), SCREEN); assert!( refused(&board).is_some(), "moving the cursor cleared a message about a line that had not changed" @@ -7605,7 +8269,7 @@ approach"; screen.join("\n").contains("Alpha first"), "`{line}` printed over the board" ); - board.prompt_key(typed(KeyCode::Esc)); + board.prompt_key(typed(KeyCode::Esc), SCREEN); } board.open_prompt(); @@ -7624,8 +8288,7 @@ approach"; /// a sentence nobody finished is a complaint about the wrong thing. #[test] fn a_line_that_ends_inside_a_quote_is_never_handed_to_clap() { - let dir = searchable(); - let mut board = one_board(&dir); + let (_root, mut board) = runnable(); board.open_prompt(); type_line(&mut board, "comment 1111111 \"the offset"); @@ -7679,7 +8342,7 @@ approach"; ); // Home takes the window back to the front of the line. - board.prompt_key(typed(KeyCode::Home)); + board.prompt_key(typed(KeyCode::Home), SCREEN); let row = footer(&board, SCREEN.width, SCREEN.height); assert!( row.contains(" :mv aaa"), @@ -7751,7 +8414,7 @@ approach"; .join(" "); assert!( - source.contains("if board.prompt_key(key) { continue; }"), + source.contains("if board.prompt_key(key, screen) { continue; }"), "the prompt has to be offered every key before the action arms, or typing \ 'd' into a command toggles the done column" ); diff --git a/src/util.rs b/src/util.rs index b7fcb95..b8f393c 100644 --- a/src/util.rs +++ b/src/util.rs @@ -303,6 +303,42 @@ pub fn color_text(text: &str, color: Color) -> String { paint(text, color, should_use_colors()) } +/// `text` with every ANSI escape sequence taken out of it. +/// +/// The inverse of what [`paint`] writes, and the guard at the seam where a handler's +/// words become something the board draws: ratatui prints an escape as literal bytes +/// rather than obeying it, so a painted status reaches the screen as `\x1b[33m` and +/// the word after it. +/// +/// A [`Sink`] the board owns is plain, so this is not about a handler's ordinary +/// output. It is about the strings that never go through one: an error message is +/// built with `color_text`, which asks the *process* about its stdout, and under the +/// board that answers yes about a terminal the message is not going to. +pub fn without_escapes(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + + while let Some(c) = chars.next() { + if c != '\x1b' { + out.push(c); + continue; + } + + // A CSI sequence is `\x1b[`, then parameter bytes, closed by a final byte in + // `@` to `~`. That is every sequence `Color` writes. Anything else is a short + // escape whose one following character goes with it, which `next` has taken. + if chars.next() == Some('[') { + for c in chars.by_ref() { + if ('\x40'..='\x7e').contains(&c) { + break; + } + } + } + } + + out +} + /// A destination for a command's output, chosen by the caller. /// /// `main` hands a handler its own stdout and nothing about the CLI changes; the @@ -332,7 +368,10 @@ impl<'a> Sink<'a> { /// An in-memory buffer, plain, for a test or a caller that colours the text /// itself. - #[allow(dead_code)] + /// + /// What the board's command prompt passes: the handler's words come back as text + /// and the board styles them with ratatui, which is also why it must not be handed + /// a coloured one — a paragraph prints an escape rather than obeying it. pub fn buffer(target: &'a mut Vec) -> Sink<'a> { Sink { writer: Box::new(target),