Something went wrong. Try again.
A terminal UI for Libby libbui.vinnymac.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389//! Making server-supplied text safe to put on a terminal.//!//! Titles, descriptions and library explanations come from publishers and//! libraries. Rendered raw, an escape sequence in a description could move the//! cursor, retitle the terminal or worse, and bidi overrides could make text//! read differently from what it is. Everything from the server goes through//! here before the UI shows it.//!//! * [`sanitize`] turns the HTML `description` into plain text with paragraph//! breaks and bullets, decodes entities, and strips control characters.//! * [`sanitize_line`] is for single-line fields (titles, names): it strips//! control characters and folds all whitespace onto one line. It does not//! interpret HTML.//!//! This is a deliberately small tag stripper, not an HTML parser. It handles//! the markup publishers actually use in descriptions (`p`, `br`, `b`, `i`,//! lists, the odd `span`) and degrades to "text with the tags removed" for//! anything else.
/// Converts an HTML description to terminal-safe plain text.////// Block elements become line breaks, paragraphs are separated by one blank/// line, list items become `• ` bullets, `script`/`style` contents and/// comments are dropped, entities are decoded, and ANSI escape sequences,/// control characters and bidi overrides are removed.#[must_use]pub fn sanitize(html: &str) -> String { let text = html_to_text(html); let clean = strip_terminal_controls(&text, true); normalize_whitespace(&clean)}
/// Makes a single-line server string terminal-safe: removes ANSI escape/// sequences, control characters and bidi overrides, and collapses all/// whitespace (including newlines) to single spaces.#[must_use]pub fn sanitize_line(text: &str) -> String { let clean = strip_terminal_controls(text, false); let mut out = String::with_capacity(clean.len()); for word in clean.split_whitespace() { if !out.is_empty() { out.push(' '); } out.push_str(word); } out}
/// Tags that start a new line.const BLOCK_TAGS: &[&str] = &[ "address", "article", "aside", "blockquote", "br", "dd", "div", "dl", "dt", "figcaption", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "ol", "pre", "section", "table", "tr", "ul",];
/// Tags whose contents are never text.const SKIP_CONTENT_TAGS: &[&str] = &["script", "style", "head", "title", "template"];
/// Line-break markers. They survive control stripping and are turned into/// real newlines by [`normalize_whitespace`]; source newlines are ordinary/// whitespace in HTML and must not become line breaks.const LINE: char = '\u{E000}';const PARAGRAPH: char = '\u{E001}';
fn html_to_text(html: &str) -> String { let mut out = String::with_capacity(html.len()); let mut rest = html; while let Some(lt) = rest.find('<') { decode_entities_into(&rest[..lt], &mut out); let after = &rest[lt..];
if let Some(comment) = after.strip_prefix("<!--") { rest = comment.find("-->").map_or("", |end| &comment[end + 3..]); continue; } let Some(gt) = after.find('>') else { // A lone '<' is text ("a < b"), not the start of a tag. decode_entities_into(after, &mut out); rest = ""; break; }; let tag = &after[1..gt]; rest = &after[gt + 1..];
let closing = tag.starts_with('/'); let name: String = tag .trim_start_matches('/') .chars() .take_while(|c| c.is_ascii_alphanumeric()) .map(|c| c.to_ascii_lowercase()) .collect(); if name.is_empty() { // `<!DOCTYPE …>`, `< b`, `<>`: not a tag we render. if !tag.starts_with('!') { decode_entities_into(&after[..=gt], &mut out); } continue; }
if !closing && SKIP_CONTENT_TAGS.contains(&name.as_str()) { rest = skip_past_closing(rest, &name); continue; } match name.as_str() { "p" => out.push(PARAGRAPH), "li" if !closing => { out.push(LINE); out.push_str("• "); } "li" => out.push(LINE), other if BLOCK_TAGS.contains(&other) => out.push(LINE), "td" | "th" if closing => out.push(' '), _ => {} } } decode_entities_into(rest, &mut out); out}
/// Skips to just after `</name …>`, case-insensitively, or to the end.fn skip_past_closing<'a>(rest: &'a str, name: &str) -> &'a str { let needle = format!("</{name}"); let lower = rest.to_ascii_lowercase(); match lower.find(&needle) { Some(start) => rest[start..] .find('>') .map_or("", |gt| &rest[start + gt + 1..]), None => "", }}
fn decode_entities_into(text: &str, out: &mut String) { let mut rest = text; while let Some(amp) = rest.find('&') { out.push_str(&rest[..amp]); let after = &rest[amp + 1..]; // Entity names and numbers are short; anything longer is a bare '&'. let end = after.char_indices().take(12).find(|(_, c)| *c == ';'); match end.and_then(|(semi, _)| decode_entity(&after[..semi]).map(|c| (semi, c))) { Some((semi, decoded)) => { out.push(decoded); rest = &after[semi + 1..]; } None => { out.push('&'); rest = after; } } } out.push_str(rest);}
fn decode_entity(entity: &str) -> Option<char> { if let Some(number) = entity.strip_prefix('#') { let code = match number.strip_prefix(['x', 'X']) { Some(hex) => u32::from_str_radix(hex, 16).ok()?, None => number.parse().ok()?, }; // Invalid code points (0, surrogates, out of range) become U+FFFD as // browsers do, rather than disappearing. return Some( char::from_u32(code) .filter(|c| *c != '\0') .unwrap_or(char::REPLACEMENT_CHARACTER), ); } let decoded = match entity { "amp" => '&', "lt" => '<', "gt" => '>', "quot" => '"', "apos" => '\'', "nbsp" | "ensp" | "emsp" | "thinsp" => ' ', "ndash" => '–', "mdash" => '—', "hellip" => '…', "lsquo" => '‘', "rsquo" => '’', "sbquo" => '‚', "ldquo" => '“', "rdquo" => '”', "bdquo" => '„', "laquo" => '«', "raquo" => '»', "bull" => '•', "middot" => '·', "copy" => '©', "reg" => '®', "trade" => '™', "deg" => '°', "times" => '×', "eacute" => 'é', "egrave" => 'è', "ecirc" => 'ê', "aacute" => 'á', "agrave" => 'à', "iacute" => 'í', "oacute" => 'ó', "uacute" => 'ú', "ntilde" => 'ñ', "ccedil" => 'ç', "auml" => 'ä', "ouml" => 'ö', "uuml" => 'ü', "szlig" => 'ß', _ => return None, }; Some(decoded)}
/// Removes ANSI escape sequences (CSI, OSC, and two-byte escapes, in both/// 7-bit and 8-bit forms), C0/C1 control characters and bidi controls./// Tabs become spaces. Newlines are kept only when `keep_newlines`.fn strip_terminal_controls(text: &str, keep_newlines: bool) -> String { let mut out = String::with_capacity(text.len()); let mut chars = text.chars().peekable(); while let Some(c) = chars.next() { match c { '\u{1b}' => match chars.next() { Some('[') => skip_csi(&mut chars), Some(']' | 'P' | '_' | '^' | 'X') => skip_string_sequence(&mut chars), // A two-character escape (`ESC c`, `ESC 7`, …) or a lone ESC. _ => {} }, '\u{9b}' => skip_csi(&mut chars), '\u{9d}' | '\u{90}' | '\u{9e}' | '\u{9f}' | '\u{98}' => { skip_string_sequence(&mut chars); } '\n' if keep_newlines => out.push('\n'), '\n' | '\r' | '\t' => out.push(' '), c if c.is_control() || is_bidi_control(c) => {} c => out.push(c), } } out}
/// CSI: parameter and intermediate bytes, then one final byte `@`..`~`.fn skip_csi(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) { for c in chars.by_ref() { if ('\u{40}'..='\u{7e}').contains(&c) { break; } }}
/// OSC/DCS/APC/PM/SOS: everything up to BEL, ST (`ESC \`) or 8-bit ST.fn skip_string_sequence(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) { while let Some(c) = chars.next() { match c { '\u{7}' | '\u{9c}' => break, '\u{1b}' => { if chars.peek() == Some(&'\\') { chars.next(); } break; } _ => {} } }}
fn is_bidi_control(c: char) -> bool { matches!( c, '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{061c}' )}
/// Collapses runs of spaces, trims each line, turns the markers into line/// breaks, and allows at most one blank line in a row.fn normalize_whitespace(text: &str) -> String { fn flush(current: &mut String, lines: &mut Vec<String>, blank: bool) { let line = current.split_whitespace().collect::<Vec<_>>().join(" "); current.clear(); if !line.is_empty() { lines.push(line); } if blank && lines.last().is_some_and(|l| !l.is_empty()) { lines.push(String::new()); } }
let mut lines: Vec<String> = Vec::new(); let mut current = String::new(); for c in text.chars() { match c { LINE => flush(&mut current, &mut lines, false), PARAGRAPH => flush(&mut current, &mut lines, true), c => current.push(c), } } flush(&mut current, &mut lines, false); while lines.last().is_some_and(String::is_empty) { lines.pop(); } lines.join("\n")}
#[cfg(test)]mod tests { use pretty_assertions::assert_eq;
use super::*;
#[test] fn description_html_becomes_paragraphs() { let html = "<p><b>New York Times</b> bestseller.</p>\n<p>Set on the desert\nplanet Arrakis, <i>Dune</i> is…</p>"; assert_eq!( sanitize(html), "New York Times bestseller.\n\nSet on the desert planet Arrakis, Dune is…" ); }
#[test] fn breaks_and_lists() { let html = "Line one<br>Line two<br/>Line three<ul><li>First</li><li>Second & last</li></ul>Done"; assert_eq!( sanitize(html), "Line one\nLine two\nLine three\n• First\n• Second & last\nDone" ); }
#[test] fn scripts_styles_and_comments_vanish() { let html = "a<script>alert('x')</script>b<STYLE>p{}</STYLE>c<!-- hidden -->d"; assert_eq!(sanitize(html), "abcd"); }
#[test] fn entities_numeric_named_and_unknown() { assert_eq!( sanitize("“Hi” © &bogus; AT&T"), "“Hi” © &bogus; AT&T" ); assert_eq!(sanitize("��"), "\u{fffd}\u{fffd}"); }
#[test] fn lone_angle_brackets_are_text() { assert_eq!(sanitize("1 < 2 and 3 > 2"), "1 < 2 and 3 > 2"); assert_eq!(sanitize("a <b"), "a <b"); }
#[test] fn terminal_escapes_are_stripped_even_when_entity_encoded() { let nasty = "safe\u{1b}[2J\u{1b}]0;pwned\u{7}text[31mred\u{9b}1mbold\u{202e}evil\u{0}"; assert_eq!(sanitize(nasty), "safetextredboldevil"); }
#[test] fn sanitize_line_folds_everything_onto_one_line() { assert_eq!( sanitize_line(" Dune:\n\tthe\u{1b}[1m novel \u{2066}"), "Dune: the novel" ); // Not HTML: tags are shown, not interpreted. assert_eq!(sanitize_line("<b>x</b>"), "<b>x</b>"); }
#[test] fn empty_and_whitespace_only() { assert_eq!(sanitize(""), ""); assert_eq!(sanitize("<p></p><p> </p>"), ""); }}