pub struct ScrollBar { /* private fields */ }Expand description
A proportional scrollbar widget with fractional thumb rendering.
§Method map
§Construction
§Position and lengths
§Appearance
§Interaction
Self::handle_eventSelf::handle_mouse_event, when a crossterm feature is enabledSelf::track_click_behaviorSelf::scroll_step
§Important
content_lenandviewport_lenare in logical units.- Zero values are treated as 1.
- The scrollbar renders into a single row or column.
§Behavior
The thumb length is proportional to viewport_len / content_len and clamped to at least one
full cell for usability. When content_len <= viewport_len, the thumb fills the track. Areas
with zero width or height render nothing.
Arrow endcaps, when enabled, consume one cell at the start/end of the track. The thumb and
track render in the remaining inner area. Clicking an arrow steps the offset by scroll_step.
§Styling
Track glyphs use track_style. Thumb glyphs use thumb_style. Arrow endcaps use
arrow_style, which defaults to white on dark gray.
Scrollbar glyphs are terminal characters. For visible track glyphs, thumb blocks, and arrow
symbols, Style::fg colors the glyph itself and Style::bg colors the cell behind it. The
default GlyphSet::minimal track renders spaces, so only the track background is visible in
empty track cells. Visible track glyph sets, such as GlyphSet::box_drawing and
GlyphSet::unicode, can use foreground color for the track line. Thumb glyphs are block
characters, so Style::fg is usually the useful knob for thumb color; Style::bg still colors
the rest of the cell. With partial thumb glyphs, especially on a visible line track such as
GlyphSet::box_drawing, that background can show at the ends of the thumb. Match the thumb
background to the track background unless that contrast is intentional.
use ratatui_core::style::{Color, Style};
use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 30,
};
let scrollbar = ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::Both)
.track_style(Style::new().bg(Color::Black))
.thumb_style(Style::new().fg(Color::Rgb(255, 158, 100)))
.arrow_style(Style::new().fg(Color::Yellow).bg(Color::Black));§State
This widget is stateless. Pointer drag state lives in crate::ScrollBarInteraction.
§Examples
Minimal rendering only needs an area, lengths, an offset, and a buffer.
use ratatui_core::buffer::Buffer;
use ratatui_core::layout::Rect;
use ratatui_core::widgets::Widget;
use tui_scrollbar::{ScrollBar, ScrollLengths};
let area = Rect::new(0, 0, 1, 5);
let lengths = ScrollLengths {
content_len: 200,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).offset(60);
let mut buffer = Buffer::empty(area);
scrollbar.render(area, &mut buffer);§Updating offsets on input
This is the typical pattern for pointer handling: feed events to the scrollbar and apply the returned command to your stored offset.
use ratatui_core::layout::Rect;
use tui_scrollbar::{
PointerButton, PointerEvent, PointerEventKind, ScrollBar, ScrollBarInteraction,
ScrollCommand, ScrollEvent, ScrollLengths,
};
let area = Rect::new(0, 0, 1, 10);
let lengths = ScrollLengths {
content_len: 400,
viewport_len: 80,
};
let scrollbar = ScrollBar::vertical(lengths).offset(0);
let mut interaction = ScrollBarInteraction::new();
let mut offset = 0;
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 3,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
if let Some(ScrollCommand::SetOffset(next)) =
scrollbar.handle_event(area, event, &mut interaction)
{
offset = next;
}§Track click behavior
Choose between classic page jumps or jump-to-click behavior.
use tui_scrollbar::{ScrollBar, ScrollLengths, TrackClickBehavior};
let lengths = ScrollLengths {
content_len: 10,
viewport_len: 5,
};
let scrollbar =
ScrollBar::vertical(lengths).track_click_behavior(TrackClickBehavior::JumpToClick);§Arrow endcaps
Arrow endcaps are optional. When enabled, they reserve one cell at each end of the track.
use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 24,
};
let scrollbar = ScrollBar::vertical(lengths).arrows(ScrollBarArrows::Both);Implementations§
Source§impl ScrollBar
impl ScrollBar
Sourcepub fn handle_event(
&self,
area: Rect,
event: ScrollEvent,
interaction: &mut ScrollBarInteraction,
) -> Option<ScrollCommand>
pub fn handle_event( &self, area: Rect, event: ScrollEvent, interaction: &mut ScrollBarInteraction, ) -> Option<ScrollCommand>
Handles a backend-agnostic scrollbar event.
Returns a ScrollCommand when the event should update the caller-owned offset. This
method does not mutate your application state directly.
Pointer events outside the track are ignored. Scroll wheel events are ignored unless the axis matches the scrollbar orientation.
use ratatui_core::layout::Rect;
use tui_scrollbar::{
PointerButton, PointerEvent, PointerEventKind, ScrollBar, ScrollBarInteraction,
ScrollEvent, ScrollLengths,
};
let area = Rect::new(0, 0, 1, 6);
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 24,
};
let scrollbar = ScrollBar::vertical(lengths).offset(0);
let mut interaction = ScrollBarInteraction::new();
let event = ScrollEvent::Pointer(PointerEvent {
column: 0,
row: 2,
kind: PointerEventKind::Down,
button: PointerButton::Primary,
});
let _ = scrollbar.handle_event(area, event, &mut interaction);Sourcepub fn handle_mouse_event(
&self,
area: Rect,
event: MouseEvent,
interaction: &mut ScrollBarInteraction,
) -> Option<ScrollCommand>
pub fn handle_mouse_event( &self, area: Rect, event: MouseEvent, interaction: &mut ScrollBarInteraction, ) -> Option<ScrollCommand>
Handles crossterm mouse events for this scrollbar.
This helper converts crossterm events into ScrollEvent values before delegating to
Self::handle_event. See the scrollbar_mouse example for a complete terminal event
loop with mouse capture.
Examples found in repository?
255 fn handle_mouse_event(&mut self, event: event::MouseEvent) {
256 let Some(layout) = self.layout else {
257 return;
258 };
259 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
260 let horizontal = self.horizontal_scrollbar(h_metrics);
261 let vertical = self.vertical_scrollbar(v_metrics);
262
263 if let Some(command) = horizontal.handle_mouse_event(
264 layout.horizontal_bar,
265 event,
266 &mut self.horizontal_interaction,
267 ) {
268 self.apply_command(command, true);
269 }
270 if let Some(command) =
271 vertical.handle_mouse_event(layout.vertical_bar, event, &mut self.vertical_interaction)
272 {
273 self.apply_command(command, false);
274 }
275 }Source§impl ScrollBar
impl ScrollBar
Sourcepub fn new(orientation: ScrollBarOrientation, lengths: ScrollLengths) -> Self
pub fn new(orientation: ScrollBarOrientation, lengths: ScrollLengths) -> Self
Creates a scrollbar with the given orientation and lengths.
Use Self::vertical or Self::horizontal when the orientation is known at the call
site.
Zero lengths are treated as 1.
use tui_scrollbar::{ScrollBar, ScrollBarOrientation, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::new(ScrollBarOrientation::Vertical, lengths);Sourcepub fn vertical(lengths: ScrollLengths) -> Self
pub fn vertical(lengths: ScrollLengths) -> Self
Creates a vertical scrollbar with the given content and viewport lengths.
The track length is derived from the render area’s height.
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths);Examples found in repository?
156fn render_vertical_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
157 for (index, area) in cells.iter().enumerate() {
158 let [label_area, bar_area] = area.layout(&Layout::vertical([
159 Constraint::Length(1),
160 Constraint::Fill(1),
161 ]));
162 if bar_area.height == 0 {
163 continue;
164 }
165 let metrics = build_metrics(bar_area.height as usize, 3);
166 let (label, thumb_start) = step_entry(&metrics, index);
167 let label = (label % 8).to_string();
168 let offset = metrics.offset_for_thumb_start(thumb_start);
169 let lengths = ScrollLengths {
170 content_len: metrics.content_len(),
171 viewport_len: metrics.viewport_len(),
172 };
173 let scrollbar = ScrollBar::vertical(lengths)
174 .arrows(ScrollBarArrows::Both)
175 .offset(offset);
176 render_label(frame, label_area, &label);
177 frame.render_widget(&scrollbar, bar_area);
178 }
179}More examples
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }
219
220 /// Handles keyboard and mouse events, updating offsets as needed.
221 fn handle_events(&mut self) -> Result<()> {
222 match event::read()? {
223 Event::Key(key) => {
224 if key.kind == KeyEventKind::Press {
225 match key.code {
226 KeyCode::Char('q') | KeyCode::Esc => self.state = AppState::Quit,
227 KeyCode::Up => self.handle_key_scroll(0, -(KEY_STEP as isize)),
228 KeyCode::Down => self.handle_key_scroll(0, KEY_STEP as isize),
229 KeyCode::Left => self.handle_key_scroll(-(KEY_STEP as isize), 0),
230 KeyCode::Right => self.handle_key_scroll(KEY_STEP as isize, 0),
231 _ => {}
232 }
233 }
234 }
235 Event::Mouse(event) => {
236 self.handle_mouse_event(event);
237 }
238 _ => {}
239 }
240 Ok(())
241 }
242
243 /// Applies a keyboard delta to the scrollbar offsets.
244 fn handle_key_scroll(&mut self, dx: isize, dy: isize) {
245 let Some(layout) = self.layout else {
246 return;
247 };
248 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
249 self.horizontal_offset =
250 Self::apply_delta(self.horizontal_offset, dx, h_metrics.max_offset());
251 self.vertical_offset = Self::apply_delta(self.vertical_offset, dy, v_metrics.max_offset());
252 }
253
254 /// Handles crossterm mouse events using the scrollbar helpers.
255 fn handle_mouse_event(&mut self, event: event::MouseEvent) {
256 let Some(layout) = self.layout else {
257 return;
258 };
259 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
260 let horizontal = self.horizontal_scrollbar(h_metrics);
261 let vertical = self.vertical_scrollbar(v_metrics);
262
263 if let Some(command) = horizontal.handle_mouse_event(
264 layout.horizontal_bar,
265 event,
266 &mut self.horizontal_interaction,
267 ) {
268 self.apply_command(command, true);
269 }
270 if let Some(command) =
271 vertical.handle_mouse_event(layout.vertical_bar, event, &mut self.vertical_interaction)
272 {
273 self.apply_command(command, false);
274 }
275 }
276
277 /// Applies a scroll command to the current axis offset.
278 fn apply_command(&mut self, command: ScrollCommand, is_horizontal: bool) {
279 let ScrollCommand::SetOffset(offset) = command;
280 if is_horizontal {
281 self.horizontal_offset = offset;
282 } else {
283 self.vertical_offset = offset;
284 }
285 }
286
287 /// Builds a horizontal scrollbar from the current metrics.
288 fn horizontal_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
289 let lengths = ScrollLengths {
290 content_len: metrics.content_len(),
291 viewport_len: metrics.viewport_len(),
292 };
293 ScrollBar::horizontal(lengths)
294 .arrows(ScrollBarArrows::Both)
295 .offset(self.horizontal_offset)
296 .scroll_step(SUBCELL)
297 }
298
299 /// Builds a vertical scrollbar from the current metrics.
300 fn vertical_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
301 let lengths = ScrollLengths {
302 content_len: metrics.content_len(),
303 viewport_len: metrics.viewport_len(),
304 };
305 ScrollBar::vertical(lengths)
306 .arrows(ScrollBarArrows::Both)
307 .offset(self.vertical_offset)
308 .scroll_step(SUBCELL)
309 }Sourcepub fn horizontal(lengths: ScrollLengths) -> Self
pub fn horizontal(lengths: ScrollLengths) -> Self
Creates a horizontal scrollbar with the given content and viewport lengths.
The track length is derived from the render area’s width.
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::horizontal(lengths);Examples found in repository?
130fn render_horizontal_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
131 for (index, area) in cells.iter().enumerate() {
132 let [label_area, bar_area] = area.layout(&Layout::horizontal([
133 Constraint::Length(2),
134 Constraint::Fill(1),
135 ]));
136 if bar_area.width == 0 {
137 continue;
138 }
139 let metrics = build_metrics(bar_area.width as usize, 6);
140 let (label, thumb_start) = step_entry(&metrics, index);
141 let label = (label % 8).to_string();
142 let offset = metrics.offset_for_thumb_start(thumb_start);
143 let lengths = ScrollLengths {
144 content_len: metrics.content_len(),
145 viewport_len: metrics.viewport_len(),
146 };
147 let scrollbar = ScrollBar::horizontal(lengths)
148 .arrows(ScrollBarArrows::Both)
149 .offset(offset);
150 render_label(frame, label_area, &label);
151 frame.render_widget(&scrollbar, bar_area);
152 }
153}More examples
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }
219
220 /// Handles keyboard and mouse events, updating offsets as needed.
221 fn handle_events(&mut self) -> Result<()> {
222 match event::read()? {
223 Event::Key(key) => {
224 if key.kind == KeyEventKind::Press {
225 match key.code {
226 KeyCode::Char('q') | KeyCode::Esc => self.state = AppState::Quit,
227 KeyCode::Up => self.handle_key_scroll(0, -(KEY_STEP as isize)),
228 KeyCode::Down => self.handle_key_scroll(0, KEY_STEP as isize),
229 KeyCode::Left => self.handle_key_scroll(-(KEY_STEP as isize), 0),
230 KeyCode::Right => self.handle_key_scroll(KEY_STEP as isize, 0),
231 _ => {}
232 }
233 }
234 }
235 Event::Mouse(event) => {
236 self.handle_mouse_event(event);
237 }
238 _ => {}
239 }
240 Ok(())
241 }
242
243 /// Applies a keyboard delta to the scrollbar offsets.
244 fn handle_key_scroll(&mut self, dx: isize, dy: isize) {
245 let Some(layout) = self.layout else {
246 return;
247 };
248 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
249 self.horizontal_offset =
250 Self::apply_delta(self.horizontal_offset, dx, h_metrics.max_offset());
251 self.vertical_offset = Self::apply_delta(self.vertical_offset, dy, v_metrics.max_offset());
252 }
253
254 /// Handles crossterm mouse events using the scrollbar helpers.
255 fn handle_mouse_event(&mut self, event: event::MouseEvent) {
256 let Some(layout) = self.layout else {
257 return;
258 };
259 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
260 let horizontal = self.horizontal_scrollbar(h_metrics);
261 let vertical = self.vertical_scrollbar(v_metrics);
262
263 if let Some(command) = horizontal.handle_mouse_event(
264 layout.horizontal_bar,
265 event,
266 &mut self.horizontal_interaction,
267 ) {
268 self.apply_command(command, true);
269 }
270 if let Some(command) =
271 vertical.handle_mouse_event(layout.vertical_bar, event, &mut self.vertical_interaction)
272 {
273 self.apply_command(command, false);
274 }
275 }
276
277 /// Applies a scroll command to the current axis offset.
278 fn apply_command(&mut self, command: ScrollCommand, is_horizontal: bool) {
279 let ScrollCommand::SetOffset(offset) = command;
280 if is_horizontal {
281 self.horizontal_offset = offset;
282 } else {
283 self.vertical_offset = offset;
284 }
285 }
286
287 /// Builds a horizontal scrollbar from the current metrics.
288 fn horizontal_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
289 let lengths = ScrollLengths {
290 content_len: metrics.content_len(),
291 viewport_len: metrics.viewport_len(),
292 };
293 ScrollBar::horizontal(lengths)
294 .arrows(ScrollBarArrows::Both)
295 .offset(self.horizontal_offset)
296 .scroll_step(SUBCELL)
297 }Sourcepub const fn orientation(self, orientation: ScrollBarOrientation) -> Self
pub const fn orientation(self, orientation: ScrollBarOrientation) -> Self
Sets the scrollbar orientation.
This is mostly useful when sharing a builder chain and choosing the orientation later.
use tui_scrollbar::{ScrollBar, ScrollBarOrientation, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).orientation(ScrollBarOrientation::Horizontal);Sourcepub const fn content_len(self, content_len: usize) -> Self
pub const fn content_len(self, content_len: usize) -> Self
Sets the total scrollable content length in logical units.
Larger values shrink the thumb, while smaller values enlarge it.
Zero values are treated as 1.
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).content_len(240);Sourcepub const fn viewport_len(self, viewport_len: usize) -> Self
pub const fn viewport_len(self, viewport_len: usize) -> Self
Sets the visible viewport length in logical units.
When viewport_len >= content_len, the thumb fills the track.
Zero values are treated as 1.
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).viewport_len(60);Sourcepub const fn offset(self, offset: usize) -> Self
pub const fn offset(self, offset: usize) -> Self
Sets the current scroll offset in logical units.
Offsets are clamped to content_len - viewport_len during rendering and input handling,
not when this builder is called.
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).offset(30);Examples found in repository?
130fn render_horizontal_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
131 for (index, area) in cells.iter().enumerate() {
132 let [label_area, bar_area] = area.layout(&Layout::horizontal([
133 Constraint::Length(2),
134 Constraint::Fill(1),
135 ]));
136 if bar_area.width == 0 {
137 continue;
138 }
139 let metrics = build_metrics(bar_area.width as usize, 6);
140 let (label, thumb_start) = step_entry(&metrics, index);
141 let label = (label % 8).to_string();
142 let offset = metrics.offset_for_thumb_start(thumb_start);
143 let lengths = ScrollLengths {
144 content_len: metrics.content_len(),
145 viewport_len: metrics.viewport_len(),
146 };
147 let scrollbar = ScrollBar::horizontal(lengths)
148 .arrows(ScrollBarArrows::Both)
149 .offset(offset);
150 render_label(frame, label_area, &label);
151 frame.render_widget(&scrollbar, bar_area);
152 }
153}
154
155/// Draws vertical scrollbars that sweep every 1/8th thumb position, left to right.
156fn render_vertical_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
157 for (index, area) in cells.iter().enumerate() {
158 let [label_area, bar_area] = area.layout(&Layout::vertical([
159 Constraint::Length(1),
160 Constraint::Fill(1),
161 ]));
162 if bar_area.height == 0 {
163 continue;
164 }
165 let metrics = build_metrics(bar_area.height as usize, 3);
166 let (label, thumb_start) = step_entry(&metrics, index);
167 let label = (label % 8).to_string();
168 let offset = metrics.offset_for_thumb_start(thumb_start);
169 let lengths = ScrollLengths {
170 content_len: metrics.content_len(),
171 viewport_len: metrics.viewport_len(),
172 };
173 let scrollbar = ScrollBar::vertical(lengths)
174 .arrows(ScrollBarArrows::Both)
175 .offset(offset);
176 render_label(frame, label_area, &label);
177 frame.render_widget(&scrollbar, bar_area);
178 }
179}More examples
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }
219
220 /// Handles keyboard and mouse events, updating offsets as needed.
221 fn handle_events(&mut self) -> Result<()> {
222 match event::read()? {
223 Event::Key(key) => {
224 if key.kind == KeyEventKind::Press {
225 match key.code {
226 KeyCode::Char('q') | KeyCode::Esc => self.state = AppState::Quit,
227 KeyCode::Up => self.handle_key_scroll(0, -(KEY_STEP as isize)),
228 KeyCode::Down => self.handle_key_scroll(0, KEY_STEP as isize),
229 KeyCode::Left => self.handle_key_scroll(-(KEY_STEP as isize), 0),
230 KeyCode::Right => self.handle_key_scroll(KEY_STEP as isize, 0),
231 _ => {}
232 }
233 }
234 }
235 Event::Mouse(event) => {
236 self.handle_mouse_event(event);
237 }
238 _ => {}
239 }
240 Ok(())
241 }
242
243 /// Applies a keyboard delta to the scrollbar offsets.
244 fn handle_key_scroll(&mut self, dx: isize, dy: isize) {
245 let Some(layout) = self.layout else {
246 return;
247 };
248 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
249 self.horizontal_offset =
250 Self::apply_delta(self.horizontal_offset, dx, h_metrics.max_offset());
251 self.vertical_offset = Self::apply_delta(self.vertical_offset, dy, v_metrics.max_offset());
252 }
253
254 /// Handles crossterm mouse events using the scrollbar helpers.
255 fn handle_mouse_event(&mut self, event: event::MouseEvent) {
256 let Some(layout) = self.layout else {
257 return;
258 };
259 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
260 let horizontal = self.horizontal_scrollbar(h_metrics);
261 let vertical = self.vertical_scrollbar(v_metrics);
262
263 if let Some(command) = horizontal.handle_mouse_event(
264 layout.horizontal_bar,
265 event,
266 &mut self.horizontal_interaction,
267 ) {
268 self.apply_command(command, true);
269 }
270 if let Some(command) =
271 vertical.handle_mouse_event(layout.vertical_bar, event, &mut self.vertical_interaction)
272 {
273 self.apply_command(command, false);
274 }
275 }
276
277 /// Applies a scroll command to the current axis offset.
278 fn apply_command(&mut self, command: ScrollCommand, is_horizontal: bool) {
279 let ScrollCommand::SetOffset(offset) = command;
280 if is_horizontal {
281 self.horizontal_offset = offset;
282 } else {
283 self.vertical_offset = offset;
284 }
285 }
286
287 /// Builds a horizontal scrollbar from the current metrics.
288 fn horizontal_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
289 let lengths = ScrollLengths {
290 content_len: metrics.content_len(),
291 viewport_len: metrics.viewport_len(),
292 };
293 ScrollBar::horizontal(lengths)
294 .arrows(ScrollBarArrows::Both)
295 .offset(self.horizontal_offset)
296 .scroll_step(SUBCELL)
297 }
298
299 /// Builds a vertical scrollbar from the current metrics.
300 fn vertical_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
301 let lengths = ScrollLengths {
302 content_len: metrics.content_len(),
303 viewport_len: metrics.viewport_len(),
304 };
305 ScrollBar::vertical(lengths)
306 .arrows(ScrollBarArrows::Both)
307 .offset(self.vertical_offset)
308 .scroll_step(SUBCELL)
309 }Sourcepub const fn track_style(self, style: Style) -> Self
pub const fn track_style(self, style: Style) -> Self
Sets the style applied to track glyphs.
Track styling applies only to cells where the thumb is not rendered.
use ratatui_core::style::{Color, Style};
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).track_style(Style::new().bg(Color::Black));Examples found in repository?
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}More examples
121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }Sourcepub const fn thumb_style(self, style: Style) -> Self
pub const fn thumb_style(self, style: Style) -> Self
Sets the style applied to thumb glyphs.
Thumb styling applies to full and partial thumb cells. Thumb glyphs are block characters,
so Style::fg usually controls the visible thumb color. Use Style::bg only when the
cell behind the glyph should differ from the track. On partial thumb cells, the background
can show at the thumb ends.
use ratatui_core::style::{Color, Style};
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar =
ScrollBar::vertical(lengths).thumb_style(Style::new().fg(Color::Rgb(255, 158, 100)));Examples found in repository?
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}More examples
121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }Sourcepub const fn arrow_style(self, style: Style) -> Self
pub const fn arrow_style(self, style: Style) -> Self
Sets the style applied to arrow glyphs.
Arrow endcaps render only when enabled with Self::arrows. If no arrow style is
configured internally, arrows fall back to the track style.
use ratatui_core::style::{Color, Style};
use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths)
.arrows(ScrollBarArrows::Both)
.arrow_style(Style::new().fg(Color::Yellow).bg(Color::Black));Examples found in repository?
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}More examples
121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }Sourcepub const fn glyph_set(self, glyph_set: GlyphSet) -> Self
pub const fn glyph_set(self, glyph_set: GlyphSet) -> Self
Selects the glyph set used to render the track and thumb.
GlyphSet::symbols_for_legacy_computing uses Symbols for Legacy Computing for 1/8th
upper/right fills. Use GlyphSet::unicode if you want to avoid the legacy supplement, or
GlyphSet::box_drawing when you want a visible line track.
use tui_scrollbar::{GlyphSet, ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).glyph_set(GlyphSet::unicode());Examples found in repository?
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}Sourcepub const fn arrows(self, arrows: ScrollBarArrows) -> Self
pub const fn arrows(self, arrows: ScrollBarArrows) -> Self
Sets which arrow endcaps are rendered.
Each enabled arrow reserves one cell at the start or end of the track.
use tui_scrollbar::{ScrollBar, ScrollBarArrows, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).arrows(ScrollBarArrows::Both);Examples found in repository?
130fn render_horizontal_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
131 for (index, area) in cells.iter().enumerate() {
132 let [label_area, bar_area] = area.layout(&Layout::horizontal([
133 Constraint::Length(2),
134 Constraint::Fill(1),
135 ]));
136 if bar_area.width == 0 {
137 continue;
138 }
139 let metrics = build_metrics(bar_area.width as usize, 6);
140 let (label, thumb_start) = step_entry(&metrics, index);
141 let label = (label % 8).to_string();
142 let offset = metrics.offset_for_thumb_start(thumb_start);
143 let lengths = ScrollLengths {
144 content_len: metrics.content_len(),
145 viewport_len: metrics.viewport_len(),
146 };
147 let scrollbar = ScrollBar::horizontal(lengths)
148 .arrows(ScrollBarArrows::Both)
149 .offset(offset);
150 render_label(frame, label_area, &label);
151 frame.render_widget(&scrollbar, bar_area);
152 }
153}
154
155/// Draws vertical scrollbars that sweep every 1/8th thumb position, left to right.
156fn render_vertical_steps(frame: &mut ratatui::Frame, cells: Vec<Rect>) {
157 for (index, area) in cells.iter().enumerate() {
158 let [label_area, bar_area] = area.layout(&Layout::vertical([
159 Constraint::Length(1),
160 Constraint::Fill(1),
161 ]));
162 if bar_area.height == 0 {
163 continue;
164 }
165 let metrics = build_metrics(bar_area.height as usize, 3);
166 let (label, thumb_start) = step_entry(&metrics, index);
167 let label = (label % 8).to_string();
168 let offset = metrics.offset_for_thumb_start(thumb_start);
169 let lengths = ScrollLengths {
170 content_len: metrics.content_len(),
171 viewport_len: metrics.viewport_len(),
172 };
173 let scrollbar = ScrollBar::vertical(lengths)
174 .arrows(ScrollBarArrows::Both)
175 .offset(offset);
176 render_label(frame, label_area, &label);
177 frame.render_widget(&scrollbar, bar_area);
178 }
179}More examples
22fn render(area: Rect, frame: &mut ratatui::Frame) {
23 if area.width < 2 || area.height < 2 {
24 return;
25 }
26
27 let horizontal_bar = area
28 .rows()
29 .next_back()
30 .unwrap_or(area)
31 .inner(Margin::new(1, 0));
32 let vertical_bar = area
33 .columns()
34 .next_back()
35 .unwrap_or(area)
36 .inner(Margin::new(0, 1));
37
38 let block = Block::new()
39 .borders(Borders::ALL)
40 .title("styled scrollbars")
41 .border_style((Color::LightBlue, Color::Black))
42 .style((Color::Gray, Color::Black));
43 let content = block.inner(area).inner(Margin::new(2, 1));
44 frame.render_widget(block, area);
45
46 frame.render_widget(
47 Paragraph::new("track_style, thumb_style, and arrow_style can each use distinct colors")
48 .style((Color::Gray, Color::Black)),
49 content,
50 );
51
52 let lengths = ScrollLengths {
53 content_len: 160,
54 viewport_len: 40,
55 };
56 let horizontal = ScrollBar::horizontal(lengths)
57 .offset(48)
58 .arrows(ScrollBarArrows::Both)
59 .glyph_set(GlyphSet::box_drawing())
60 .track_style((Color::Blue, Color::Black).into())
61 .thumb_style((Color::Yellow, Modifier::BOLD).into())
62 .arrow_style((Color::LightGreen, Color::Black, Modifier::BOLD).into());
63 let vertical = ScrollBar::vertical(lengths)
64 .offset(80)
65 .arrows(ScrollBarArrows::Both)
66 .glyph_set(GlyphSet::box_drawing())
67 .track_style((Color::Magenta, Color::Black).into())
68 .thumb_style((Color::Cyan, Modifier::BOLD).into())
69 .arrow_style((Color::LightRed, Color::Black, Modifier::BOLD).into());
70
71 frame.render_widget(&horizontal, horizontal_bar);
72 frame.render_widget(&vertical, vertical_bar);
73}121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }
219
220 /// Handles keyboard and mouse events, updating offsets as needed.
221 fn handle_events(&mut self) -> Result<()> {
222 match event::read()? {
223 Event::Key(key) => {
224 if key.kind == KeyEventKind::Press {
225 match key.code {
226 KeyCode::Char('q') | KeyCode::Esc => self.state = AppState::Quit,
227 KeyCode::Up => self.handle_key_scroll(0, -(KEY_STEP as isize)),
228 KeyCode::Down => self.handle_key_scroll(0, KEY_STEP as isize),
229 KeyCode::Left => self.handle_key_scroll(-(KEY_STEP as isize), 0),
230 KeyCode::Right => self.handle_key_scroll(KEY_STEP as isize, 0),
231 _ => {}
232 }
233 }
234 }
235 Event::Mouse(event) => {
236 self.handle_mouse_event(event);
237 }
238 _ => {}
239 }
240 Ok(())
241 }
242
243 /// Applies a keyboard delta to the scrollbar offsets.
244 fn handle_key_scroll(&mut self, dx: isize, dy: isize) {
245 let Some(layout) = self.layout else {
246 return;
247 };
248 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
249 self.horizontal_offset =
250 Self::apply_delta(self.horizontal_offset, dx, h_metrics.max_offset());
251 self.vertical_offset = Self::apply_delta(self.vertical_offset, dy, v_metrics.max_offset());
252 }
253
254 /// Handles crossterm mouse events using the scrollbar helpers.
255 fn handle_mouse_event(&mut self, event: event::MouseEvent) {
256 let Some(layout) = self.layout else {
257 return;
258 };
259 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
260 let horizontal = self.horizontal_scrollbar(h_metrics);
261 let vertical = self.vertical_scrollbar(v_metrics);
262
263 if let Some(command) = horizontal.handle_mouse_event(
264 layout.horizontal_bar,
265 event,
266 &mut self.horizontal_interaction,
267 ) {
268 self.apply_command(command, true);
269 }
270 if let Some(command) =
271 vertical.handle_mouse_event(layout.vertical_bar, event, &mut self.vertical_interaction)
272 {
273 self.apply_command(command, false);
274 }
275 }
276
277 /// Applies a scroll command to the current axis offset.
278 fn apply_command(&mut self, command: ScrollCommand, is_horizontal: bool) {
279 let ScrollCommand::SetOffset(offset) = command;
280 if is_horizontal {
281 self.horizontal_offset = offset;
282 } else {
283 self.vertical_offset = offset;
284 }
285 }
286
287 /// Builds a horizontal scrollbar from the current metrics.
288 fn horizontal_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
289 let lengths = ScrollLengths {
290 content_len: metrics.content_len(),
291 viewport_len: metrics.viewport_len(),
292 };
293 ScrollBar::horizontal(lengths)
294 .arrows(ScrollBarArrows::Both)
295 .offset(self.horizontal_offset)
296 .scroll_step(SUBCELL)
297 }
298
299 /// Builds a vertical scrollbar from the current metrics.
300 fn vertical_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
301 let lengths = ScrollLengths {
302 content_len: metrics.content_len(),
303 viewport_len: metrics.viewport_len(),
304 };
305 ScrollBar::vertical(lengths)
306 .arrows(ScrollBarArrows::Both)
307 .offset(self.vertical_offset)
308 .scroll_step(SUBCELL)
309 }Sourcepub const fn track_click_behavior(self, behavior: TrackClickBehavior) -> Self
pub const fn track_click_behavior(self, behavior: TrackClickBehavior) -> Self
Sets behavior for clicks on the track outside the thumb.
Use TrackClickBehavior::Page for classic page-up/down behavior, or
TrackClickBehavior::JumpToClick to move the thumb toward the click.
This does not affect clicks on the thumb or arrow endcaps.
use tui_scrollbar::{ScrollBar, ScrollLengths, TrackClickBehavior};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar =
ScrollBar::vertical(lengths).track_click_behavior(TrackClickBehavior::JumpToClick);Sourcepub fn scroll_step(self, step: usize) -> Self
pub fn scroll_step(self, step: usize) -> Self
Sets the scroll step used for wheel events.
The wheel delta is multiplied by this value (in your logical units) and then clamped. A step of 0 is normalized to 1.
use tui_scrollbar::{ScrollBar, ScrollLengths};
let lengths = ScrollLengths {
content_len: 120,
viewport_len: 40,
};
let scrollbar = ScrollBar::vertical(lengths).scroll_step(8);Examples found in repository?
121 fn render(&mut self, frame: &mut ratatui::Frame) {
122 let area = frame.area();
123 if area.width < 2 || area.height < 2 {
124 return;
125 }
126
127 let title = "tui-scrollbar - mouse scroll demo";
128 let block = Block::new()
129 .borders(Borders::TOP)
130 .border_style(Style::new().fg(TITLE_FG).bg(TITLE_BG))
131 .style(Style::new().fg(BLOCK_FG).bg(BLOCK_BG))
132 .title(
133 Line::from(title)
134 .centered()
135 .fg(TITLE_FG)
136 .bg(TITLE_BG)
137 .bold(),
138 );
139 frame.render_widget(&block, area);
140
141 let content_area = Rect {
142 y: area.y.saturating_add(1),
143 height: area.height.saturating_sub(1),
144 ..area
145 };
146 let help = "Arrows: move | Wheel: scroll | Drag: thumb | q/Esc: quit";
147 let help_area = Rect {
148 x: content_area.x.saturating_add(1),
149 y: content_area.y,
150 width: content_area.width.saturating_sub(1),
151 height: 1,
152 };
153 if help_area.width > 0 {
154 frame.render_widget(
155 Paragraph::new(help).style(Style::new().fg(TITLE_FG)),
156 help_area,
157 );
158 }
159 let content_area = Rect {
160 y: content_area.y.saturating_add(1),
161 height: content_area.height.saturating_sub(1),
162 ..content_area
163 };
164
165 // Split out the bottom row and right column for the scrollbars.
166 let [content_row, bar_row] = content_area.layout(&Layout::vertical([
167 Constraint::Fill(1),
168 Constraint::Length(1),
169 ]));
170 let [content, vertical_bar] = content_row.layout(&Layout::horizontal([
171 Constraint::Fill(1),
172 Constraint::Length(1),
173 ]));
174 let [horizontal_bar, _corner] = bar_row.layout(&Layout::horizontal([
175 Constraint::Fill(1),
176 Constraint::Length(1),
177 ]));
178
179 self.layout = Some(LayoutState {
180 content,
181 vertical_bar,
182 horizontal_bar,
183 });
184
185 // Keep offsets valid when the terminal is resized.
186 let (h_metrics, v_metrics) = self.metrics_for_layout(content);
187 self.horizontal_offset = self.horizontal_offset.min(h_metrics.max_offset());
188 self.vertical_offset = self.vertical_offset.min(v_metrics.max_offset());
189
190 let horizontal_lengths = ScrollLengths {
191 content_len: h_metrics.content_len(),
192 viewport_len: h_metrics.viewport_len(),
193 };
194 let track_style = Style::new().bg(SCROLLBAR_TRACK_BG);
195 let thumb_style = Style::new().fg(SCROLLBAR_THUMB_FG).bg(SCROLLBAR_THUMB_BG);
196 let arrow_style = Style::new().fg(SCROLLBAR_ARROW_FG).bg(SCROLLBAR_TRACK_BG);
197 let horizontal = ScrollBar::horizontal(horizontal_lengths)
198 .arrows(ScrollBarArrows::Both)
199 .offset(self.horizontal_offset)
200 .scroll_step(SUBCELL)
201 .track_style(track_style)
202 .thumb_style(thumb_style)
203 .arrow_style(arrow_style);
204 let vertical_lengths = ScrollLengths {
205 content_len: v_metrics.content_len(),
206 viewport_len: v_metrics.viewport_len(),
207 };
208 let vertical = ScrollBar::vertical(vertical_lengths)
209 .arrows(ScrollBarArrows::Both)
210 .offset(self.vertical_offset)
211 .scroll_step(SUBCELL)
212 .track_style(track_style)
213 .thumb_style(thumb_style)
214 .arrow_style(arrow_style);
215
216 frame.render_widget(&horizontal, horizontal_bar);
217 frame.render_widget(&vertical, vertical_bar);
218 }
219
220 /// Handles keyboard and mouse events, updating offsets as needed.
221 fn handle_events(&mut self) -> Result<()> {
222 match event::read()? {
223 Event::Key(key) => {
224 if key.kind == KeyEventKind::Press {
225 match key.code {
226 KeyCode::Char('q') | KeyCode::Esc => self.state = AppState::Quit,
227 KeyCode::Up => self.handle_key_scroll(0, -(KEY_STEP as isize)),
228 KeyCode::Down => self.handle_key_scroll(0, KEY_STEP as isize),
229 KeyCode::Left => self.handle_key_scroll(-(KEY_STEP as isize), 0),
230 KeyCode::Right => self.handle_key_scroll(KEY_STEP as isize, 0),
231 _ => {}
232 }
233 }
234 }
235 Event::Mouse(event) => {
236 self.handle_mouse_event(event);
237 }
238 _ => {}
239 }
240 Ok(())
241 }
242
243 /// Applies a keyboard delta to the scrollbar offsets.
244 fn handle_key_scroll(&mut self, dx: isize, dy: isize) {
245 let Some(layout) = self.layout else {
246 return;
247 };
248 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
249 self.horizontal_offset =
250 Self::apply_delta(self.horizontal_offset, dx, h_metrics.max_offset());
251 self.vertical_offset = Self::apply_delta(self.vertical_offset, dy, v_metrics.max_offset());
252 }
253
254 /// Handles crossterm mouse events using the scrollbar helpers.
255 fn handle_mouse_event(&mut self, event: event::MouseEvent) {
256 let Some(layout) = self.layout else {
257 return;
258 };
259 let (h_metrics, v_metrics) = self.metrics_for_layout(layout.content);
260 let horizontal = self.horizontal_scrollbar(h_metrics);
261 let vertical = self.vertical_scrollbar(v_metrics);
262
263 if let Some(command) = horizontal.handle_mouse_event(
264 layout.horizontal_bar,
265 event,
266 &mut self.horizontal_interaction,
267 ) {
268 self.apply_command(command, true);
269 }
270 if let Some(command) =
271 vertical.handle_mouse_event(layout.vertical_bar, event, &mut self.vertical_interaction)
272 {
273 self.apply_command(command, false);
274 }
275 }
276
277 /// Applies a scroll command to the current axis offset.
278 fn apply_command(&mut self, command: ScrollCommand, is_horizontal: bool) {
279 let ScrollCommand::SetOffset(offset) = command;
280 if is_horizontal {
281 self.horizontal_offset = offset;
282 } else {
283 self.vertical_offset = offset;
284 }
285 }
286
287 /// Builds a horizontal scrollbar from the current metrics.
288 fn horizontal_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
289 let lengths = ScrollLengths {
290 content_len: metrics.content_len(),
291 viewport_len: metrics.viewport_len(),
292 };
293 ScrollBar::horizontal(lengths)
294 .arrows(ScrollBarArrows::Both)
295 .offset(self.horizontal_offset)
296 .scroll_step(SUBCELL)
297 }
298
299 /// Builds a vertical scrollbar from the current metrics.
300 fn vertical_scrollbar(&self, metrics: ScrollMetrics) -> ScrollBar {
301 let lengths = ScrollLengths {
302 content_len: metrics.content_len(),
303 viewport_len: metrics.viewport_len(),
304 };
305 ScrollBar::vertical(lengths)
306 .arrows(ScrollBarArrows::Both)
307 .offset(self.vertical_offset)
308 .scroll_step(SUBCELL)
309 }Trait Implementations§
impl Eq for ScrollBar
impl StructuralPartialEq for ScrollBar
Auto Trait Implementations§
impl Freeze for ScrollBar
impl RefUnwindSafe for ScrollBar
impl Send for ScrollBar
impl Sync for ScrollBar
impl Unpin for ScrollBar
impl UnsafeUnpin for ScrollBar
impl UnwindSafe for ScrollBar
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key and return true if they are equal.Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more