use crate::util::markdown::iced_markdown_options;
const MAX_LINE_CHARS: usize = 200;
const MAX_SCAN_CHARS: usize = 2_000;
const MIN_SENTENCE_CHARS: usize = 20;
const CLOSERS: [char; 7] = ['"', '\'', '”', '’', '»', ')', ']'];
pub(crate) struct Line<'a> {
pub(crate) text: String,
pub(crate) hover: Option<&'a str>,
}
pub(crate) fn line_for_step<'a>(
narration: &'a str,
reasoning: Option<&'a str>,
) -> Option<Line<'a>> {
let hover = reasoning
.map(bounded_prefix)
.filter(|reasoning| !reasoning.trim().is_empty());
let text = match pick_line(bounded_prefix(narration)) {
Some(text) => text,
None => pick_line(hover?)?,
};
Some(Line { text, hover })
}
fn pick_line(text: &str) -> Option<String> {
let plain = plain_text(text);
let (sentences, fragment) = split_sentences(&plain);
let mut readable = sentences
.iter()
.copied()
.filter(|s| s.chars().count() >= MIN_SENTENCE_CHARS);
let line = match readable.next() {
Some(first) if first.chars().count() > MAX_LINE_CHARS => cut_at_word(first),
Some(first) => {
let mut line = first.to_string();
for next in readable {
if line.chars().count() + 1 + next.chars().count() > MAX_LINE_CHARS {
break;
}
line.push(' ');
line.push_str(next);
}
line
}
None => cut_at_word(sentences.last().copied().unwrap_or(fragment)),
};
(!line.is_empty() && line.chars().any(char::is_alphanumeric)).then_some(line)
}
fn bounded_prefix(text: &str) -> &str {
match text.char_indices().nth(MAX_SCAN_CHARS) {
Some((cut, _)) => &text[..cut],
None => text,
}
}
fn plain_text(text: &str) -> String {
use pulldown_cmark::{Event, Tag, TagEnd};
let mut out = String::with_capacity(text.len());
let mut boundary = false;
let mut code_block = false;
for (event, span) in
pulldown_cmark::Parser::new_ext(text, iced_markdown_options()).into_offset_iter()
{
match event {
Event::Start(Tag::CodeBlock(_)) => code_block = true,
Event::End(TagEnd::CodeBlock) => code_block = false,
_ if code_block => {}
Event::Text(text) | Event::Code(text) => {
push_separator(&mut out, &mut boundary);
out.push_str(&text);
}
Event::Start(Tag::Strong) | Event::End(TagEnd::Strong)
if dunder_markers(&text[span.clone()]) =>
{
push_separator(&mut out, &mut boundary);
out.push_str("__");
}
Event::Start(
Tag::Emphasis
| Tag::Strong
| Tag::Strikethrough
| Tag::Link { .. }
| Tag::Image { .. },
)
| Event::End(
TagEnd::Emphasis
| TagEnd::Strong
| TagEnd::Strikethrough
| TagEnd::Link
| TagEnd::Image,
) => {}
_ => boundary = true,
}
}
let mut plain = String::with_capacity(out.len());
for word in out.split(is_separator) {
let word = word.trim_start_matches(BULLETS);
if word.is_empty() {
continue;
}
if !plain.is_empty() {
plain.push(' ');
}
plain.push_str(word);
}
plain
}
fn dunder_markers(span: &str) -> bool {
span.strip_prefix("__")
.and_then(|body| body.strip_suffix("__"))
.is_some_and(|body| {
!body.is_empty() && !body.contains(|c: char| c.is_whitespace() || c == '`')
})
}
fn push_separator(out: &mut String, boundary: &mut bool) {
if std::mem::take(boundary) && !out.is_empty() {
out.push(' ');
}
}
const BULLETS: &[char] = &['•', '·', '‣', '∙', '▪', '●', '◦'];
fn is_separator(c: char) -> bool {
c.is_whitespace()
|| c.is_control()
|| matches!(
c,
'\u{00ad}' | '\u{200b}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{feff}'
)
}
fn is_terminator(c: char) -> bool {
matches!(c, '.' | '!' | '?' | '…')
}
fn split_sentences(text: &str) -> (Vec<&str>, &str) {
let chars: Vec<(usize, char)> = text.char_indices().collect();
let mut sentences = Vec::new();
let mut start = 0;
let mut i = 0;
while i < chars.len() {
if !is_terminator(chars[i].1) {
i += 1;
continue;
}
let mut end = i + 1;
while end < chars.len() && is_terminator(chars[end].1) {
end += 1;
}
while end < chars.len() && CLOSERS.contains(&chars[end].1) {
end += 1;
}
let ends_block = end == chars.len() || chars[end].1.is_whitespace();
if ends_block && ends_sentence(&chars, i) {
let sentence = &text[byte_at(&chars, text, start)..byte_at(&chars, text, end)];
sentences.push(sentence.trim());
start = end;
}
i = end;
}
(sentences, text[byte_at(&chars, text, start)..].trim())
}
fn byte_at(chars: &[(usize, char)], text: &str, index: usize) -> usize {
chars.get(index).map_or(text.len(), |&(byte, _)| byte)
}
fn ends_sentence(chars: &[(usize, char)], i: usize) -> bool {
if chars[i].1 != '.' {
return true;
}
let mut start = i;
while start > 0 && !chars[start - 1].1.is_whitespace() {
start -= 1;
}
let token: String = chars[start..i].iter().map(|&(_, c)| c).collect();
if is_dotted_abbreviation(&token) {
return false;
}
if !token.contains('.') {
return true;
}
let Some(next) = chars[i + 1..]
.iter()
.map(|&(_, c)| c)
.find(|c| !c.is_whitespace() && !CLOSERS.contains(c))
else {
return true;
};
!next.is_lowercase()
}
fn is_dotted_abbreviation(token: &str) -> bool {
let mut letters = 0;
let mut letter_next = true;
for c in token.chars() {
match (letter_next, c) {
(true, _) if c.is_alphabetic() => letters += 1,
(false, '.') => {}
_ => return false,
}
letter_next = !letter_next;
}
letters >= 2 && !letter_next
}
fn cut_at_word(text: &str) -> String {
let text = text.trim();
if text.chars().count() <= MAX_LINE_CHARS {
return text.to_string();
}
let room = MAX_LINE_CHARS - 1;
let mut boundary = None;
let mut hard = text.len();
for (index, (byte, c)) in text.char_indices().enumerate() {
if index == room {
hard = byte;
break;
}
if c.is_whitespace() {
boundary = Some(byte);
}
}
let head =
text[..boundary.unwrap_or(hard)].trim_end_matches([' ', ',', ';', ':', '…', '/', '_', '-']);
format!("{head}…")
}
#[cfg(test)]
mod tests {
use super::*;
const DRIFT: &str = "The parser struct is missing the offset field.";
const FIELD: &str = "The parser needs the field.";
const EDITING: &str = "Now editing the parser";
const SPLIT_HEAD: &str = "I edited src/gui/running/mod.rs and left e.g. the parser.";
const TAIL: &str = "Then I ran 0.5 of the tests.";
fn line(narration: &str, reasoning: Option<&str>) -> String {
line_for_step(narration, reasoning)
.expect("the step carries text")
.text
}
#[test]
fn lines_pack_whole_sentences_within_the_budget() {
let cases: &[(&str, &str, Option<&str>, &str)] = &[
(
"heading",
"Now the `Mem` struct:",
None,
"Now the Mem struct:",
),
(
"bare acknowledgement skipped",
"",
Some("Good. The parser struct is missing the offset field, so the columns drift."),
"The parser struct is missing the offset field, so the columns drift.",
),
(
"whole sentences packed",
"",
Some(
"The parser drifts on every column of the offset table. I will add the missing \
offset field to the struct definition. Then the whole test suite runs again to \
prove the columns line up. Finally the installer is rebuilt and shipped.",
),
"The parser drifts on every column of the offset table. I will add the missing \
offset field to the struct definition. Then the whole test suite runs again to prove \
the columns line up.",
),
(
"file name ends a sentence",
"",
Some("All good. See src/gui/running/label.rs."),
"See src/gui/running/label.rs.",
),
];
for &(name, narration, reasoning, expected) in cases {
assert_eq!(line(narration, reasoning), expected, "case {name}");
}
let exact = "a".repeat(MAX_LINE_CHARS);
assert_eq!(line("", Some(&exact)), exact, "case exactly the budget");
let over = "a".repeat(MAX_LINE_CHARS + 1);
let clipped = format!("{}…", "a".repeat(MAX_LINE_CHARS - 1));
assert_eq!(line("", Some(&over)), clipped, "case one over");
let text = "I'll restructure the installer so the archive is unpacked once and the binaries \
are proven before the swap, which keeps a failed attempt from leaving a half-installed copy \
behind, and the previous install stays intact until the new one is proven to run.";
let cut = line("", Some(text));
assert!(cut.ends_with('…'));
assert!(cut.chars().count() <= MAX_LINE_CHARS, "the ellipsis counts");
let kept = cut.trim_end_matches('…');
assert!(text.starts_with(kept), "kept prefix verbatim");
assert!(text[kept.len()..].starts_with(' '), "cut on a space");
}
#[test]
fn block_debris_is_stripped_from_the_text() {
let cases: &[(&str, &str, &str)] = &[
(
"bullet glyphs are debris",
"• read the table\n• patch the struct\n\nThen done.",
"read the table patch the struct Then done.",
),
(
"fenced code is source",
"```rust\nlet field_1 = value_1 + offset;\n```\nThe parser drifts.",
"The parser drifts.",
),
(
"indented code is source",
" let field = 1;\n\nThe parser drifts.",
"The parser drifts.",
),
(
"heading and list debris",
"## Next\n\n- **first** item\n- second item\n\n1. third",
"Next first item second item third",
),
(
"invisible format chars",
"The parser drifts.\u{feff} \u{200b}Then the tests.",
"The parser drifts. Then the tests.",
),
(
"block boundaries are spaces",
"# Fixing the parser\n\nThe struct is missing `offset`, so I'll add it.\n\n\
- read the table\n- patch the struct\n\nDone.",
"Fixing the parser The struct is missing offset, so I'll add it. \
read the table patch the struct Done.",
),
(
"punctuation keeps its word",
"Done.\n\n.env.example lists them.",
"Done. .env.example lists them.",
),
];
for &(name, input, expected) in cases {
assert_eq!(plain_text(input), expected, "case {name}");
}
}
type NarrationCase<'a> = (
&'a str,
&'a str,
Option<&'a str>,
Option<&'a str>,
Option<&'a str>,
);
#[test]
fn narration_leads_and_its_step_reasoning_is_the_hover_text() {
let cases: &[NarrationCase] = &[
(
"narration leads",
EDITING,
Some(FIELD),
Some(EDITING),
Some(FIELD),
),
(
"stripped narration falls through",
"---",
Some(DRIFT),
Some(DRIFT),
Some(DRIFT),
),
("no text at all", "", None, None, None),
("whitespace only", " \n\t", Some(" "), None, None),
];
for &(name, narration, reasoning, text, hover) in cases {
let step = line_for_step(narration, reasoning);
let shown = step.as_ref().map(|l| l.text.as_str());
assert_eq!(shown, text, "case {name}: text");
assert_eq!(
step.as_ref().and_then(|l| l.hover),
hover,
"case {name}: hover"
);
}
let long = DRIFT.to_string().repeat(1_000);
let step = line_for_step("", Some(&long)).expect("the step carries text");
assert!(step.hover.is_some_and(|t| t.len() <= MAX_SCAN_CHARS));
let text = format!("{SPLIT_HEAD} {TAIL}");
let (sentences, fragment) = split_sentences(&text);
assert_eq!(sentences, [SPLIT_HEAD, TAIL]);
assert_eq!(fragment, "");
}
}