use crate::io::PosMetadata; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TextWrapStyle { Normal, Heading1, Heading2, } /// Character columns available for a text style on the target printer. pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize { let base = metadata.chars_per_line().max(1) as usize; match style { TextWrapStyle::Heading1 => (base / 2).max(1), TextWrapStyle::Normal | TextWrapStyle::Heading2 => base, } } /// ASCII top-level bullet — universally supported on ESC/POS printers. pub const BULLET_FIRST_PREFIX: &str = "* "; /// Indent for wrapped continuation lines at depth 0 (same width as [`BULLET_FIRST_PREFIX`]). pub const BULLET_NEXT_PREFIX: &str = " "; /// Word-wrap a top-level bullet list item with hanging indentation (`* `). pub fn wrap_bullet_item(text: &str, max_cols: usize) -> Vec { wrap_bullet_item_at_depth(text, max_cols, 0) } /// Word-wrap a bullet at nesting `depth` (0 = `* `, nested = indented `- `). pub fn wrap_bullet_item_at_depth(text: &str, max_cols: usize, depth: u8) -> Vec { let (first, next) = bullet_prefixes(depth); wrap_hanging(text, max_cols, &first, &next) } fn bullet_prefixes(depth: u8) -> (String, String) { let indent = " ".repeat(usize::from(depth)); if depth == 0 { (BULLET_FIRST_PREFIX.to_string(), BULLET_NEXT_PREFIX.to_string()) } else { let first = format!("{indent}- "); let next = " ".repeat(first.chars().count()); (first, next) } } /// Word-wrap `text` with different budgets for the first and subsequent lines. pub fn wrap_hanging( text: &str, max_cols: usize, first_prefix: &str, next_prefix: &str, ) -> Vec { let first_budget = max_cols.saturating_sub(first_prefix.chars().count()); let next_budget = max_cols.saturating_sub(next_prefix.chars().count()); let content_lines = wrap_content_var_budget(text, first_budget, next_budget); content_lines .into_iter() .enumerate() .map(|(idx, line)| { if idx == 0 { format!("{first_prefix}{line}") } else { format!("{next_prefix}{line}") } }) .collect() } fn wrap_content_var_budget(text: &str, first_budget: usize, next_budget: usize) -> Vec { if first_budget == 0 && next_budget == 0 { return vec![text.to_string()]; } let words: Vec<&str> = text.split_whitespace().collect(); if words.is_empty() { return vec![String::new()]; } let mut lines = Vec::new(); let mut current = String::new(); let mut budget = first_budget.max(1); let mut word_idx = 0usize; while word_idx < words.len() { let word = words[word_idx]; let word_len = word.chars().count(); if current.is_empty() { if word_len <= budget { current.push_str(word); word_idx += 1; } else { // Hard-break overlong tokens (URLs, etc.). Must advance word_idx // or this loop never terminates. let mut remaining = word; while !remaining.is_empty() { let chunk = take_char_prefix(remaining, budget); let consumed = chunk.chars().count(); if chunk.is_empty() { break; } lines.push(chunk); remaining = &remaining[remaining .char_indices() .nth(consumed) .map(|(idx, _)| idx) .unwrap_or(remaining.len())..]; budget = next_budget.max(1); } word_idx += 1; } } else { let current_len = current.chars().count(); if current_len + 1 + word_len <= budget { current.push(' '); current.push_str(word); word_idx += 1; } else { lines.push(std::mem::take(&mut current)); budget = next_budget.max(1); } } } if !current.is_empty() { lines.push(current); } if lines.is_empty() { lines.push(String::new()); } lines } fn take_char_prefix(text: &str, max_chars: usize) -> String { text.chars().take(max_chars).collect() } /// Word-wrap `text` to at most `max_cols` characters per line. /// Explicit newlines in `text` start a new wrapped paragraph. pub fn wrap_text(text: &str, max_cols: usize) -> Vec { if max_cols == 0 { return vec![text.to_string()]; } let mut lines = Vec::new(); for paragraph in text.split('\n') { lines.extend(wrap_line(paragraph, max_cols)); } if lines.is_empty() { lines.push(String::new()); } lines } fn wrap_line(line: &str, max_cols: usize) -> Vec { if line.is_empty() { return vec![String::new()]; } let mut lines = Vec::new(); let mut current = String::new(); for word in line.split_whitespace() { let word_len = word.chars().count(); if current.is_empty() { if word_len <= max_cols { current.push_str(word); } else { lines.extend(split_long_word(word, max_cols)); } } else { let current_len = current.chars().count(); if current_len + 1 + word_len <= max_cols { current.push(' '); current.push_str(word); } else { lines.push(std::mem::take(&mut current)); if word_len <= max_cols { current.push_str(word); } else { lines.extend(split_long_word(word, max_cols)); } } } } if !current.is_empty() { lines.push(current); } if lines.is_empty() { lines.push(String::new()); } lines } fn split_long_word(word: &str, max_cols: usize) -> Vec { let mut chunks = Vec::new(); let mut chunk = String::new(); for ch in word.chars() { if chunk.chars().count() >= max_cols { chunks.push(std::mem::take(&mut chunk)); } chunk.push(ch); } if !chunk.is_empty() { chunks.push(chunk); } chunks } #[cfg(test)] mod tests { use super::*; fn meta_53mm() -> PosMetadata { PosMetadata { page_width_mm: 53.0, ..Default::default() } } #[test] fn heading1_wraps_at_half_line_width() { let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Heading1); assert_eq!(cols, 16); let lines = wrap_text("Proof of Transfer", cols); assert_eq!(lines, vec!["Proof of", "Transfer"]); } #[test] fn preserves_explicit_newlines() { let lines = wrap_text("Line one\nLine two", 32); assert_eq!(lines, vec!["Line one", "Line two"]); } #[test] fn normal_text_wraps_at_full_width() { let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal); assert_eq!(cols, 32); } #[test] fn bullet_wrap_uses_hanging_indent() { let lines = wrap_bullet_item("this is a long line", 15); assert_eq!(lines, vec!["* this is a", " long line"]); } #[test] fn nested_bullet_uses_dash_and_indent() { let lines = wrap_bullet_item_at_depth("this is a long line", 16, 1); assert_eq!(lines, vec![" - this is a", " long line"]); } #[test] fn hanging_wrap_hard_breaks_url_without_hanging() { let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88"; let lines = wrap_bullet_item(url, 32); assert!(lines.len() >= 2, "expected hard-break into multiple lines: {lines:?}"); assert!(lines[0].starts_with("* https://")); let joined: String = lines .iter() .map(|l| { l.strip_prefix("* ") .or_else(|| l.strip_prefix(" ")) .unwrap_or(l) }) .collect(); assert_eq!(joined, url); } #[test] fn plain_wrap_hard_breaks_url() { let url = "https://www.youtube.com/watch?v=9gIMZ0WyY88"; let lines = wrap_text(url, 32); assert!(lines.len() >= 2); assert_eq!(lines.concat(), url); } }