croft-software 0.2.232

VSCode-style TUI written in Rust
//! A message shown whole, in a card centred on the screen: the home for
//! anything too long for the status line, an error above all. The text is
//! wrapped to the card, never cut, and scrolls when it outgrows the screen.

use std::cell::Cell;

use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

#[derive(Clone, Debug)]
pub struct MessageCard {
    pub title: String,
    pub text: String,
    /// The first visible wrapped row.
    pub scroll: usize,
    /// (visible rows, wrapped rows) as of the last paint, so keys can clamp.
    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)),
        }
    }

    /// The furthest the text can scroll.
    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());
    }
}

/// `text` wrapped to `width` columns: words kept whole where they fit, a
/// word longer than a row broken at the row's end, newlines kept. Nothing
/// is dropped.
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;
            }
            // Longer than a row: break it where the row ends.
            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);
    }
}