use std::cell::Cell;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
#[derive(Clone, Debug)]
pub struct MessageCard {
pub title: String,
pub text: String,
pub scroll: usize,
pub view: Cell<(usize, usize)>,
}
impl MessageCard {
pub fn new(title: impl Into<String>, text: impl Into<String>) -> Self {
Self {
title: title.into(),
text: text.into(),
scroll: 0,
view: Cell::new((0, 0)),
}
}
pub fn max_scroll(&self) -> usize {
let (rows, total) = self.view.get();
total.saturating_sub(rows.max(1))
}
pub fn scroll_by(&mut self, delta: isize) {
let next = self.scroll.saturating_add_signed(delta);
self.scroll = next.min(self.max_scroll());
}
pub fn scroll_to(&mut self, row: usize) {
self.scroll = row.min(self.max_scroll());
}
}
pub fn wrap(text: &str, width: usize) -> Vec<String> {
let width = width.max(1);
let mut rows = Vec::new();
for raw in text.lines() {
let raw = raw.replace('\t', " ");
if raw.trim().is_empty() {
rows.push(String::new());
continue;
}
let mut row = String::new();
let mut used = 0usize;
for word in raw.split(' ') {
let w = UnicodeWidthStr::width(word);
let gap = usize::from(used > 0);
if used > 0 && used + 1 + w > width {
rows.push(std::mem::take(&mut row));
used = 0;
}
if w <= width {
if used > 0 {
row.push(' ');
used += 1;
}
row.push_str(word);
used += w;
continue;
}
let _ = gap;
if used > 0 {
row.push(' ');
used += 1;
}
for c in word.chars() {
let cw = c.width().unwrap_or(0);
if used + cw > width {
rows.push(std::mem::take(&mut row));
used = 0;
}
row.push(c);
used += cw;
}
}
rows.push(row);
}
if rows.is_empty() {
rows.push(String::new());
}
rows
}
#[cfg(test)]
mod tests {
use super::*;
fn joined(rows: &[String]) -> String {
rows.concat().replace(' ', "")
}
#[test]
fn wrapping_keeps_every_character() {
let text = "local endpoint http://127.0.0.1:52625/v1: turn exceeded the 10 minute ceiling (raise it with `croft pair --timeout <seconds>`)";
for width in [10, 20, 37, 80] {
let rows = wrap(text, width);
assert_eq!(joined(&rows), text.replace(' ', ""), "width {width}");
assert!(
rows.iter()
.all(|r| UnicodeWidthStr::width(r.as_str()) <= width)
);
}
}
#[test]
fn a_long_word_is_broken_and_wide_chars_fit() {
let rows = wrap(&"x".repeat(25), 10);
assert_eq!(rows.len(), 3);
let rows = wrap("日本語日本語日本語", 7);
assert!(rows.iter().all(|r| UnicodeWidthStr::width(r.as_str()) <= 7));
assert_eq!(rows.concat(), "日本語日本語日本語");
}
#[test]
fn newlines_are_kept() {
assert_eq!(wrap("a\n\nb", 10), vec!["a", "", "b"]);
}
#[test]
fn scroll_is_clamped() {
let mut c = MessageCard::new("t", "x");
c.view.set((5, 8));
c.scroll_by(100);
assert_eq!(c.scroll, 3);
c.scroll_by(-100);
assert_eq!(c.scroll, 0);
}
}