use anyhow::Result;
use plannotator_tui_schema::{DocumentSource, Provenance};
use unicode_width::UnicodeWidthChar;
use crate::app::App;
use crate::delivery::Delivery;
pub(crate) const DEFAULT_LINES: u32 = 200;
pub(crate) fn clean(raw: &str) -> String {
let plain = strip_escapes(raw);
let lines: Vec<&str> = plain.lines().map(str::trim_end).collect();
let first = lines.iter().position(|line| !line.is_empty());
let last = lines.iter().rposition(|line| !line.is_empty());
match (first, last) {
(Some(first), Some(last)) => lines.get(first..=last).unwrap_or_default().join("\n"),
_ => String::new(),
}
}
fn strip_escapes(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut chars = raw.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'\u{1b}' => match chars.next() {
Some('[') => {
for c in chars.by_ref() {
if ('@'..='~').contains(&c) {
break;
}
}
}
Some(']') => {
while let Some(c) = chars.next() {
if c == '\u{7}' || (c == '\u{1b}' && chars.next_if_eq(&'\\').is_some()) {
break;
}
}
}
_ => {}
},
'\n' | '\t' => out.push(ch),
c if c.is_control() => {}
c => out.push(c),
}
}
out
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Wrapped {
pub(crate) text: String,
pub(crate) breaks: Vec<usize>,
}
pub(crate) fn wrap(text: &str, width: usize) -> Wrapped {
let width = width.max(1);
let mut out = String::with_capacity(text.len());
let mut breaks = Vec::new();
for (i, line) in text.lines().enumerate() {
if i > 0 {
out.push('\n');
}
let mut rest = line;
while let Some(cut) = overflow(rest, width) {
let head = rest.get(..cut).unwrap_or(rest);
let indent = head.len() - head.trim_start_matches(' ').len();
if let Some(space) = head.rfind(' ').filter(|&space| space > indent) {
out.push_str(head.get(..space).unwrap_or(head));
rest = rest.get(space + 1..).unwrap_or_default();
} else {
out.push_str(head);
breaks.push(out.len());
rest = rest.get(cut..).unwrap_or_default();
}
out.push('\n');
}
out.push_str(rest);
}
Wrapped { text: out, breaks }
}
fn overflow(line: &str, width: usize) -> Option<usize> {
let mut used = 0;
for (offset, ch) in line.char_indices() {
used += UnicodeWidthChar::width(ch).unwrap_or(0);
if used > width && offset > 0 {
return Some(offset);
}
}
None
}
pub(crate) fn document(text: &str) -> String {
let longest = text.split(|c| c != '`').map(str::len).max().unwrap_or(0);
let fence = "`".repeat(longest.max(2) + 1);
format!("{fence}text\n{text}\n{fence}\n")
}
pub(crate) fn title(pane: &str, agent: Option<&str>) -> String {
match agent {
Some(agent) => format!("terminal · {agent} in {pane}"),
None => format!("terminal · {pane}"),
}
}
pub(crate) fn source(text: &str, title: String) -> DocumentSource {
DocumentSource::new(document(text), title, true, Provenance::Stdin)
}
pub(crate) fn open(text: &str, title: String, width: usize, delivery: Box<dyn Delivery>) -> Result<App> {
let wrapped = wrap(text, width);
let source = source(&wrapped.text, title);
let start = source.content.find('\n').map_or(0, |newline| newline + 1);
let mut app = App::open(source, width, delivery)?;
app.set_terminal_breaks(wrapped.breaks.iter().map(|offset| start + offset).collect());
Ok(app)
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::*;
#[test]
fn cleaning_removes_escapes_controls_and_surrounding_blank_lines() {
let raw = "\n \n\u{1b}[1;32m$ cargo test\u{1b}[0m \r\n\u{1b}]8;;file:///x\u{7}link\u{1b}]8;;\u{1b}\\ ok\u{7}\n\t indented\n\n\n";
assert_eq!(clean(raw), "$ cargo test\nlink ok\n\t indented");
}
#[test]
fn output_with_nothing_visible_cleans_to_empty() {
assert_eq!(clean(""), "");
assert_eq!(clean("\n \n\u{1b}[2J\n"), "");
}
#[test]
fn blank_lines_inside_the_output_are_kept() {
assert_eq!(clean("one\n\n\ntwo\n"), "one\n\n\ntwo");
}
#[test]
fn long_lines_break_at_a_space_and_short_lines_are_untouched() {
let text = |input: &str, width| wrap(input, width).text;
assert_eq!(
wrap("the quick brown fox", 10),
Wrapped { text: "the quick\nbrown fox".into(), breaks: vec![] }
);
assert_eq!(text("short\n indented", 10), "short\n indented");
assert_eq!(wrap("abcdefghijkl", 5), Wrapped { text: "abcde\nfghij\nkl".into(), breaks: vec![5, 11] });
assert_eq!(text(" abcdefghi", 6), " abc\ndefghi");
assert_eq!(text("한글한글", 4), "한글\n한글");
}
#[test]
fn the_fence_outlasts_any_backticks_in_the_output() {
assert_eq!(document("ls"), "```text\nls\n```\n");
let doc = document("echo ```` done");
assert!(doc.starts_with("`````text\n") && doc.ends_with("\n`````\n"), "{doc}");
}
#[test]
fn the_document_renders_the_output_as_one_code_block() {
let doc = crate::doc::Document::parse(document("# not a heading\n* not a list"));
let kinds: Vec<_> = doc.blocks.iter().map(|block| block.kind).collect();
assert_eq!(kinds, [crate::doc::BlockKind::CodeBlock]);
}
#[test]
fn the_review_is_transient_and_titled_by_its_pane() {
let source = source("ok", title("w1:p2", Some("claude")));
assert!(source.transient);
assert_eq!(source.name, "terminal · claude in w1:p2");
assert_eq!(title("w1:p2", None), "terminal · w1:p2");
}
#[test]
fn a_quote_across_a_broken_path_reads_as_printed() {
let path = "/home/user/projects/herdr/src/deeply/nested/module/source.rs";
assert_eq!(path.len(), 60);
let text = format!("error in {path}\nok");
let wrapped = wrap(&text, 24);
assert_eq!(wrapped.text.lines().count(), 5, "{}", wrapped.text);
assert_eq!(wrapped.breaks.len(), 2);
let across: Vec<&str> = wrapped.text.lines().take(4).collect();
let mut app =
open(&text, title("w1:p1", None), 24, Box::new(crate::delivery::Discard)).expect("opens");
app.add_quote_annotation_at(
&across.join("\n"),
1,
plannotator_tui_schema::Kind::Comment,
"fix".into(),
)
.expect("annotated");
assert_eq!(
app.feedback(),
format!(
"# Annotations on terminal · w1:p1\n\n## Annotation 1\nComment on: \"error in {path}\"\n> fix\n\n"
)
);
}
}