rustom 0.1.0

A library for building rich, stateful terminal user interfaces and dashboards.
Documentation
use crate::buffer::Buffer;
use crate::layout::Rect;
use crate::style::Style;
use crate::widgets::StatefulWidget;

/// Which edge of the area a `Scrollbar` is drawn along.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScrollbarOrientation {
    VerticalRight,
    VerticalLeft,
    HorizontalBottom,
    HorizontalTop,
}

/// Tracks the scrollable content's total length, the caller's current
/// scroll position, and how much of it fits on screen at once, so
/// `Scrollbar` can size and place its thumb.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ScrollbarState {
    content_length: usize,
    position: usize,
    viewport_length: usize,
}

impl ScrollbarState {
    pub fn new(content_length: usize) -> ScrollbarState {
        ScrollbarState {
            content_length,
            position: 0,
            viewport_length: 0,
        }
    }

    pub fn viewport_length(mut self, viewport_length: usize) -> ScrollbarState {
        self.viewport_length = viewport_length;
        self
    }

    pub fn position(mut self, position: usize) -> ScrollbarState {
        self.position = position;
        self
    }

    pub fn set_position(&mut self, position: usize) {
        self.position = position.min(self.content_length.saturating_sub(1));
    }

    pub fn set_content_length(&mut self, content_length: usize) {
        self.content_length = content_length;
    }
}

/// A track-and-thumb indicator showing where the current viewport sits
/// within a larger scrollable area. Pair this with a `ScrollbarState` kept
/// alongside whatever content it is scrolling (a `Paragraph`'s scroll
/// offset, for example).
#[derive(Debug, Clone)]
pub struct Scrollbar {
    orientation: ScrollbarOrientation,
    track_style: Style,
    thumb_style: Style,
    track_symbol: char,
    thumb_symbol: char,
}

impl Default for Scrollbar {
    fn default() -> Scrollbar {
        Scrollbar {
            orientation: ScrollbarOrientation::VerticalRight,
            track_style: Style::default(),
            thumb_style: Style::default(),
            track_symbol: '│',
            thumb_symbol: '█',
        }
    }
}

impl Scrollbar {
    pub fn new(orientation: ScrollbarOrientation) -> Scrollbar {
        let (track_symbol, thumb_symbol) = match orientation {
            ScrollbarOrientation::VerticalRight | ScrollbarOrientation::VerticalLeft => {
                ('│', '█')
            }
            ScrollbarOrientation::HorizontalBottom | ScrollbarOrientation::HorizontalTop => {
                ('─', '█')
            }
        };
        Scrollbar {
            orientation,
            track_symbol,
            thumb_symbol,
            ..Scrollbar::default()
        }
    }

    pub fn track_style(mut self, style: Style) -> Scrollbar {
        self.track_style = style;
        self
    }

    pub fn thumb_style(mut self, style: Style) -> Scrollbar {
        self.thumb_style = style;
        self
    }

    pub fn symbols(mut self, track: char, thumb: char) -> Scrollbar {
        self.track_symbol = track;
        self.thumb_symbol = thumb;
        self
    }
}

/// Given the pixel/cell length of the track and the current scroll state,
/// returns the `(start, len)` of the thumb in track-relative coordinates.
fn thumb_geometry(track_len: u16, state: &ScrollbarState) -> (u16, u16) {
    if track_len == 0 || state.content_length == 0 {
        return (0, 0);
    }
    let viewport = state.viewport_length.max(1).min(state.content_length);
    let thumb_len = ((track_len as u64 * viewport as u64) / state.content_length as u64)
        .max(1)
        .min(track_len as u64) as u16;

    let scrollable = state.content_length.saturating_sub(viewport);
    let start = if scrollable == 0 {
        0
    } else {
        let max_start = track_len.saturating_sub(thumb_len) as u64;
        (max_start * state.position as u64 / scrollable as u64).min(max_start) as u16
    };
    (start, thumb_len)
}

impl StatefulWidget for Scrollbar {
    type State = ScrollbarState;

    fn render(self, area: Rect, buf: &mut Buffer, state: &mut ScrollbarState) {
        if area.area() == 0 {
            return;
        }
        let vertical = matches!(
            self.orientation,
            ScrollbarOrientation::VerticalLeft | ScrollbarOrientation::VerticalRight
        );

        let track_len = if vertical { area.height } else { area.width };
        let (thumb_start, thumb_len) = thumb_geometry(track_len, state);

        let (x, y) = match self.orientation {
            ScrollbarOrientation::VerticalRight => (area.right() - 1, area.y),
            ScrollbarOrientation::VerticalLeft => (area.x, area.y),
            ScrollbarOrientation::HorizontalBottom => (area.x, area.bottom() - 1),
            ScrollbarOrientation::HorizontalTop => (area.x, area.y),
        };

        for i in 0..track_len {
            let is_thumb = i >= thumb_start && i < thumb_start + thumb_len;
            let (cx, cy) = if vertical { (x, y + i) } else { (x + i, y) };
            let cell = buf.get_mut(cx, cy);
            if is_thumb {
                cell.set_char(self.thumb_symbol).set_style(self.thumb_style);
            } else {
                cell.set_char(self.track_symbol).set_style(self.track_style);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn thumb_centers_for_full_content() {
        let state = ScrollbarState::new(10).viewport_length(10).position(0);
        assert_eq!(thumb_geometry(10, &state), (0, 10));
    }

    #[test]
    fn thumb_shrinks_for_large_content() {
        let state = ScrollbarState::new(100).viewport_length(10).position(0);
        let (start, len) = thumb_geometry(20, &state);
        assert_eq!(start, 0);
        assert_eq!(len, 2);
    }

    #[test]
    fn thumb_moves_to_end() {
        let state = ScrollbarState::new(100).viewport_length(10).position(90);
        let (start, len) = thumb_geometry(20, &state);
        assert_eq!(start + len, 20);
    }
}