ratatui_kit/components/scroll_view/
state.rs1use crossterm::event::{Event, KeyCode, KeyEventKind, MouseEventKind};
14use ratatui::layout::{Position, Size};
15
16#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
17pub struct ScrollViewState {
19 pub(crate) offset: Position,
21 pub(crate) size: Option<Size>,
23 pub(crate) page_size: Option<Size>,
25}
26
27impl ScrollViewState {
28 pub fn new() -> Self {
30 Self::default()
31 }
32
33 pub fn with_offset(offset: Position) -> Self {
35 Self {
36 offset,
37 ..Default::default()
38 }
39 }
40
41 pub const fn set_offset(&mut self, offset: Position) {
43 self.offset = offset;
44 }
45
46 pub const fn offset(&self) -> Position {
48 self.offset
49 }
50
51 pub const fn scroll_up(&mut self) {
53 self.offset.y = self.offset.y.saturating_sub(1);
54 }
55
56 pub const fn scroll_down(&mut self) {
58 self.offset.y = self.offset.y.saturating_add(1);
59 }
60
61 pub fn scroll_page_down(&mut self) {
63 let page_size = self.page_size.map_or(1, |size| size.height);
64 self.offset.y = self.offset.y.saturating_add(page_size).saturating_sub(1);
66 }
67
68 pub fn scroll_page_up(&mut self) {
70 let page_size = self.page_size.map_or(1, |size| size.height);
71 self.offset.y = self.offset.y.saturating_add(1).saturating_sub(page_size);
73 }
74
75 pub const fn scroll_left(&mut self) {
77 self.offset.x = self.offset.x.saturating_sub(1);
78 }
79
80 pub const fn scroll_right(&mut self) {
82 self.offset.x = self.offset.x.saturating_add(1);
83 }
84
85 pub const fn scroll_to_top(&mut self) {
87 self.offset = Position::ORIGIN;
88 }
89
90 pub fn scroll_to_bottom(&mut self) {
92 let bottom = self
94 .size
95 .map_or(u16::MAX, |size| size.height.saturating_sub(1));
96 self.offset.y = bottom;
97 }
98
99 pub fn handle_event(&mut self, event: &Event) {
100 match event {
101 Event::Key(key) if key.kind == KeyEventKind::Press => match key.code {
102 KeyCode::Up | KeyCode::Char('k') => {
103 self.scroll_up();
104 }
105 KeyCode::Down | KeyCode::Char('j') => {
106 self.scroll_down();
107 }
108 KeyCode::Left | KeyCode::Char('h') => {
109 self.scroll_left();
110 }
111 KeyCode::Right | KeyCode::Char('l') => {
112 self.scroll_right();
113 }
114 KeyCode::PageUp => {
115 self.scroll_page_up();
116 }
117 KeyCode::PageDown => {
118 self.scroll_page_down();
119 }
120 KeyCode::Home => {
121 self.scroll_to_top();
122 }
123 KeyCode::End => {
124 self.scroll_to_bottom();
125 }
126 _ => {}
127 },
128 Event::Mouse(event) => match event.kind {
129 MouseEventKind::ScrollDown => {
130 self.scroll_down();
131 }
132 MouseEventKind::ScrollUp => {
133 self.scroll_up();
134 }
135 MouseEventKind::ScrollLeft => {
136 self.scroll_left();
137 }
138 MouseEventKind::ScrollRight => {
139 self.scroll_right();
140 }
141 _ => {}
142 },
143 _ => {}
144 }
145 }
146}