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_tokens_var_budget(&tokenize(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() } /// Word-wrap `text` to at most `max_cols` characters per line. /// Explicit newlines in `text` start a new wrapped paragraph. /// Consecutive spaces are preserved (not collapsed). 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()]; } wrap_tokens_var_budget(&tokenize(line), max_cols, max_cols) } /// Split into alternating word / whitespace runs so multi-space gaps stay intact. fn tokenize(text: &str) -> Vec> { let mut tokens = Vec::new(); let mut rest = text; while !rest.is_empty() { let first = rest.chars().next().unwrap(); if is_wrap_space(first) { let end = rest .char_indices() .find(|(_, c)| !is_wrap_space(*c)) .map(|(i, _)| i) .unwrap_or(rest.len()); tokens.push(Token::Spaces(&rest[..end])); rest = &rest[end..]; } else { let end = rest .char_indices() .find(|(_, c)| is_wrap_space(*c)) .map(|(i, _)| i) .unwrap_or(rest.len()); tokens.push(Token::Word(&rest[..end])); rest = &rest[end..]; } } tokens } fn is_wrap_space(c: char) -> bool { c == ' ' || c == '\t' } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Token<'a> { Word(&'a str), Spaces(&'a str), } impl<'a> Token<'a> { fn as_str(self) -> &'a str { match self { Token::Word(s) | Token::Spaces(s) => s, } } fn len_chars(self) -> usize { self.as_str().chars().count() } fn is_spaces(self) -> bool { matches!(self, Token::Spaces(_)) } } fn wrap_tokens_var_budget( tokens: &[Token<'_>], first_budget: usize, next_budget: usize, ) -> Vec { if tokens.is_empty() { return vec![String::new()]; } if first_budget == 0 && next_budget == 0 { return vec![tokens.iter().map(|t| t.as_str()).collect()]; } let mut lines = Vec::new(); let mut current = String::new(); let mut budget = first_budget.max(1); let mut idx = 0usize; // After wrapping mid-line, skip the whitespace that sat between words. let mut skip_leading_spaces = false; while idx < tokens.len() { let tok = tokens[idx]; if tok.is_spaces() { if current.is_empty() { if skip_leading_spaces { idx += 1; continue; } // Leading spaces of the original line (or a space-only line). let spaces = tok.as_str(); let space_len = tok.len_chars(); if space_len <= budget { current.push_str(spaces); idx += 1; } else { let mut remaining = spaces; 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 = char_slice_from(remaining, consumed); budget = next_budget.max(1); } idx += 1; skip_leading_spaces = false; } continue; } let cur_len = current.chars().count(); let space_len = tok.len_chars(); if cur_len + space_len <= budget { current.push_str(tok.as_str()); idx += 1; } else { // Spaces don't fit: end the line (trim trailing pad) and skip // this space run on the continuation. flush_line(&mut lines, &mut current); budget = next_budget.max(1); skip_leading_spaces = true; } continue; } // Word token let word = tok.as_str(); let word_len = tok.len_chars(); if current.is_empty() { if word_len <= budget { current.push_str(word); idx += 1; skip_leading_spaces = false; } else { 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 = char_slice_from(remaining, consumed); budget = next_budget.max(1); } idx += 1; skip_leading_spaces = true; } continue; } let cur_len = current.chars().count(); if cur_len + word_len <= budget { current.push_str(word); idx += 1; skip_leading_spaces = false; } else { flush_line(&mut lines, &mut current); budget = next_budget.max(1); skip_leading_spaces = true; // Retry the same word on the new line. } } if !current.is_empty() { lines.push(current); } if lines.is_empty() { lines.push(String::new()); } lines } fn flush_line(lines: &mut Vec, current: &mut String) { // Drop trailing spaces that only existed as padding before a wrapped word. let trimmed = current.trim_end_matches(is_wrap_space).to_string(); if !trimmed.is_empty() { lines.push(trimmed); } current.clear(); } fn take_char_prefix(text: &str, max_chars: usize) -> String { text.chars().take(max_chars).collect() } fn char_slice_from(text: &str, skip_chars: usize) -> &str { match text.char_indices().nth(skip_chars) { Some((idx, _)) => &text[idx..], None => "", } } #[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); } #[test] fn preserves_multiple_spaces_within_line() { let lines = wrap_text("Item 12.00", 32); assert_eq!(lines, vec!["Item 12.00"]); } #[test] fn preserves_multiple_spaces_when_wrapping() { // "aa" + 4 spaces + "bb" = 8; budget 6 wraps before bb, spaces not leading next line. let lines = wrap_text("aa bb", 6); assert_eq!(lines, vec!["aa", "bb"]); } #[test] fn preserves_leading_spaces() { let lines = wrap_text(" hello", 32); assert_eq!(lines, vec![" hello"]); } #[test] fn space_only_line_is_preserved() { let lines = wrap_text(" ", 32); assert_eq!(lines, vec![" "]); } #[test] fn bullet_preserves_multiple_spaces() { let lines = wrap_bullet_item("A B", 32); assert_eq!(lines, vec!["* A B"]); } }