1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use ratatui::{style::Style, widgets::Widget};

pub struct Scrollbar {
    pub scrolled_amount: usize,
    pub total_amount: usize,
    pub style: Style,
}

impl Scrollbar {
    pub fn new(scrolled_amount: usize, total_amount: usize, style: Style) -> Self {
        Self {
            scrolled_amount,
            total_amount,
            style,
        }
    }
}

impl Widget for Scrollbar {
    fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
    where
        Self: Sized,
    {
        if area.height == 0 {
            return;
        }
        let total_amount = self.total_amount.max(1);
        let handle_size = ((area.height as usize) / total_amount).clamp(1, area.height as usize);
        let handle_start =
            (self.scrolled_amount as isize * area.height as isize / total_amount as isize
                - handle_size as isize / 2)
                .clamp(0, area.height as isize - handle_size as isize) as usize;
        for y in area.top()..area.bottom() {
            if (y as usize) >= handle_start && (y as usize) < handle_start + handle_size {
                buf.get_mut(area.left(), y).set_char('█');
                buf.get_mut(area.left(), y).set_style(self.style);
            } else {
                buf.get_mut(area.left(), y).set_char(' ');
                buf.get_mut(area.left(), y).set_style(self.style);
            }
        }
    }
}