Struct ListState

Source
pub struct ListState { /* private fields */ }
Expand description

State of the List widget

This state can be used to scroll through items and select one. When the list is rendered as a stateful widget, the selected item will be highlighted and the list will be shifted to ensure that the selected item is visible. This will modify the ListState object passed to the Frame::render_stateful_widget method.

The state consists of two fields:

  • offset: the index of the first item to be displayed
  • selected: the index of the selected item, which can be None if no item is selected

See the list in the Examples directory for a more in depth example of the various configuration options and for how to handle state.

§Example

use ratatui::{
    layout::Rect,
    widgets::{List, ListState},
    Frame,
};

let items = ["Item 1"];
let list = List::new(items);

// This should be stored outside of the function in your application state.
let mut state = ListState::default();

*state.offset_mut() = 1; // display the second item and onwards
state.select(Some(3)); // select the forth item (0-indexed)

frame.render_stateful_widget(list, area, &mut state);

Implementations§

Source§

impl ListState

Source

pub const fn with_offset(self, offset: usize) -> Self

Sets the index of the first item to be displayed

This is a fluent setter method which must be chained or used as it consumes self

§Examples
use ratatui::widgets::ListState;

let state = ListState::default().with_offset(1);
Source

pub const fn with_selected(self, selected: Option<usize>) -> Self

Sets the index of the selected item

This is a fluent setter method which must be chained or used as it consumes self

§Examples
use ratatui::widgets::ListState;

let state = ListState::default().with_selected(Some(1));
Examples found in repository?
examples/demo2/tabs/email.rs (line 103)
82fn render_inbox(selected_index: usize, area: Rect, buf: &mut Buffer) {
83    let vertical = Layout::vertical([Constraint::Length(1), Constraint::Min(0)]);
84    let [tabs, inbox] = vertical.areas(area);
85    let theme = THEME.email;
86    Tabs::new(vec![" Inbox ", " Sent ", " Drafts "])
87        .style(theme.tabs)
88        .highlight_style(theme.tabs_selected)
89        .select(0)
90        .divider("")
91        .render(tabs, buf);
92
93    let highlight_symbol = ">>";
94    let from_width = EMAILS
95        .iter()
96        .map(|e| e.from.width())
97        .max()
98        .unwrap_or_default();
99    let items = EMAILS.iter().map(|e| {
100        let from = format!("{:width$}", e.from, width = from_width).into();
101        ListItem::new(Line::from(vec![from, " ".into(), e.subject.into()]))
102    });
103    let mut state = ListState::default().with_selected(Some(selected_index));
104    StatefulWidget::render(
105        List::new(items)
106            .style(theme.inbox)
107            .highlight_style(theme.selected_item)
108            .highlight_symbol(highlight_symbol),
109        inbox,
110        buf,
111        &mut state,
112    );
113    let mut scrollbar_state = ScrollbarState::default()
114        .content_length(EMAILS.len())
115        .position(selected_index);
116    Scrollbar::default()
117        .begin_symbol(None)
118        .end_symbol(None)
119        .track_symbol(None)
120        .thumb_symbol("▐")
121        .render(inbox, buf, &mut scrollbar_state);
122}
Source

pub const fn offset(&self) -> usize

Index of the first item to be displayed

§Examples
use ratatui::widgets::ListState;

let state = ListState::default();
assert_eq!(state.offset(), 0);
Source

pub fn offset_mut(&mut self) -> &mut usize

Mutable reference to the index of the first item to be displayed

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
*state.offset_mut() = 1;
Source

pub const fn selected(&self) -> Option<usize>

Index of the selected item

Returns None if no item is selected

§Examples
use ratatui::widgets::ListState;

let state = ListState::default();
assert_eq!(state.selected(), None);
Examples found in repository?
examples/list.rs (line 165)
164    fn toggle_status(&mut self) {
165        if let Some(i) = self.todo_list.state.selected() {
166            self.todo_list.items[i].status = match self.todo_list.items[i].status {
167                Status::Completed => Status::Todo,
168                Status::Todo => Status::Completed,
169            }
170        }
171    }
172}
173
174impl Widget for &mut App {
175    fn render(self, area: Rect, buf: &mut Buffer) {
176        let [header_area, main_area, footer_area] = Layout::vertical([
177            Constraint::Length(2),
178            Constraint::Fill(1),
179            Constraint::Length(1),
180        ])
181        .areas(area);
182
183        let [list_area, item_area] =
184            Layout::vertical([Constraint::Fill(1), Constraint::Fill(1)]).areas(main_area);
185
186        App::render_header(header_area, buf);
187        App::render_footer(footer_area, buf);
188        self.render_list(list_area, buf);
189        self.render_selected_item(item_area, buf);
190    }
191}
192
193/// Rendering logic for the app
194impl App {
195    fn render_header(area: Rect, buf: &mut Buffer) {
196        Paragraph::new("Ratatui List Example")
197            .bold()
198            .centered()
199            .render(area, buf);
200    }
201
202    fn render_footer(area: Rect, buf: &mut Buffer) {
203        Paragraph::new("Use ↓↑ to move, ← to unselect, → to change status, g/G to go top/bottom.")
204            .centered()
205            .render(area, buf);
206    }
207
208    fn render_list(&mut self, area: Rect, buf: &mut Buffer) {
209        let block = Block::new()
210            .title(Line::raw("TODO List").centered())
211            .borders(Borders::TOP)
212            .border_set(symbols::border::EMPTY)
213            .border_style(TODO_HEADER_STYLE)
214            .bg(NORMAL_ROW_BG);
215
216        // Iterate through all elements in the `items` and stylize them.
217        let items: Vec<ListItem> = self
218            .todo_list
219            .items
220            .iter()
221            .enumerate()
222            .map(|(i, todo_item)| {
223                let color = alternate_colors(i);
224                ListItem::from(todo_item).bg(color)
225            })
226            .collect();
227
228        // Create a List from all list items and highlight the currently selected one
229        let list = List::new(items)
230            .block(block)
231            .highlight_style(SELECTED_STYLE)
232            .highlight_symbol(">")
233            .highlight_spacing(HighlightSpacing::Always);
234
235        // We need to disambiguate this trait method as both `Widget` and `StatefulWidget` share the
236        // same method name `render`.
237        StatefulWidget::render(list, area, buf, &mut self.todo_list.state);
238    }
239
240    fn render_selected_item(&self, area: Rect, buf: &mut Buffer) {
241        // We get the info depending on the item's state.
242        let info = if let Some(i) = self.todo_list.state.selected() {
243            match self.todo_list.items[i].status {
244                Status::Completed => format!("✓ DONE: {}", self.todo_list.items[i].info),
245                Status::Todo => format!("☐ TODO: {}", self.todo_list.items[i].info),
246            }
247        } else {
248            "Nothing selected...".to_string()
249        };
250
251        // We show the list item's info under the list in this paragraph
252        let block = Block::new()
253            .title(Line::raw("TODO Info").centered())
254            .borders(Borders::TOP)
255            .border_set(symbols::border::EMPTY)
256            .border_style(TODO_HEADER_STYLE)
257            .bg(NORMAL_ROW_BG)
258            .padding(Padding::horizontal(1));
259
260        // We can now render the item info
261        Paragraph::new(info)
262            .block(block)
263            .fg(TEXT_FG_COLOR)
264            .wrap(Wrap { trim: false })
265            .render(area, buf);
266    }
Source

pub fn selected_mut(&mut self) -> &mut Option<usize>

Mutable reference to the index of the selected item

Returns None if no item is selected

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
*state.selected_mut() = Some(1);
Source

pub fn select(&mut self, index: Option<usize>)

Sets the index of the selected item

Set to None if no item is selected. This will also reset the offset to 0.

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
state.select(Some(1));
Examples found in repository?
examples/list.rs (line 145)
144    fn select_none(&mut self) {
145        self.todo_list.state.select(None);
146    }
Source

pub fn select_next(&mut self)

Selects the next item or the first one if no item is selected

Note: until the list is rendered, the number of items is not known, so the index is set to 0 and will be corrected when the list is rendered

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
state.select_next();
Examples found in repository?
examples/list.rs (line 149)
148    fn select_next(&mut self) {
149        self.todo_list.state.select_next();
150    }
Source

pub fn select_previous(&mut self)

Selects the previous item or the last one if no item is selected

Note: until the list is rendered, the number of items is not known, so the index is set to usize::MAX and will be corrected when the list is rendered

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
state.select_previous();
Examples found in repository?
examples/list.rs (line 152)
151    fn select_previous(&mut self) {
152        self.todo_list.state.select_previous();
153    }
Source

pub fn select_first(&mut self)

Selects the first item

Note: until the list is rendered, the number of items is not known, so the index is set to 0 and will be corrected when the list is rendered

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
state.select_first();
Examples found in repository?
examples/list.rs (line 156)
155    fn select_first(&mut self) {
156        self.todo_list.state.select_first();
157    }
Source

pub fn select_last(&mut self)

Selects the last item

Note: until the list is rendered, the number of items is not known, so the index is set to usize::MAX and will be corrected when the list is rendered

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
state.select_last();
Examples found in repository?
examples/list.rs (line 160)
159    fn select_last(&mut self) {
160        self.todo_list.state.select_last();
161    }
Source

pub fn scroll_down_by(&mut self, amount: u16)

Scrolls down by a specified amount in the list.

This method updates the selected index by moving it down by the given amount. If the amount causes the index to go out of bounds (i.e., if the index is greater than the length of the list), the last item in the list will be selected.

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
state.scroll_down_by(4);
Source

pub fn scroll_up_by(&mut self, amount: u16)

Scrolls up by a specified amount in the list.

This method updates the selected index by moving it up by the given amount. If the amount causes the index to go out of bounds (i.e., less than zero), the first item in the list will be selected.

§Examples
use ratatui::widgets::ListState;

let mut state = ListState::default();
state.scroll_up_by(4);

Trait Implementations§

Source§

impl Clone for ListState

Source§

fn clone(&self) -> ListState

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ListState

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ListState

Source§

fn default() -> ListState

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ListState

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Hash for ListState

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for ListState

Source§

fn eq(&self, other: &ListState) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for ListState

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for ListState

Source§

impl StructuralPartialEq for ListState

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<S, D, Swp, Dwp, T> AdaptInto<D, Swp, Dwp, T> for S
where T: Real + Zero + Arithmetics + Clone, Swp: WhitePoint<T>, Dwp: WhitePoint<T>, D: AdaptFrom<S, Swp, Dwp, T>,

Source§

fn adapt_into_using<M>(self, method: M) -> D
where M: TransformMatrix<T>,

Convert the source color to the destination color using the specified method.
Source§

fn adapt_into(self) -> D

Convert the source color to the destination color using the bradford method by default.
Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, C> ArraysFrom<C> for T
where C: IntoArrays<T>,

Source§

fn arrays_from(colors: C) -> T

Cast a collection of colors into a collection of arrays.
Source§

impl<T, C> ArraysInto<C> for T
where C: FromArrays<T>,

Source§

fn arrays_into(self) -> C

Cast this collection of arrays into a collection of colors.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<WpParam, T, U> Cam16IntoUnclamped<WpParam, T> for U
where T: FromCam16Unclamped<WpParam, U>,

Source§

type Scalar = <T as FromCam16Unclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn cam16_into_unclamped( self, parameters: BakedParameters<WpParam, <U as Cam16IntoUnclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T, C> ComponentsFrom<C> for T
where C: IntoComponents<T>,

Source§

fn components_from(colors: C) -> T

Cast a collection of colors into a collection of color components.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromAngle<T> for T

Source§

fn from_angle(angle: T) -> T

Performs a conversion from angle.
Source§

impl<T, U> FromStimulus<U> for T
where U: IntoStimulus<T>,

Source§

fn from_stimulus(other: U) -> T

Converts other into Self, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> IntoAngle<U> for T
where U: FromAngle<T>,

Source§

fn into_angle(self) -> U

Performs a conversion into T.
Source§

impl<WpParam, T, U> IntoCam16Unclamped<WpParam, T> for U
where T: Cam16FromUnclamped<WpParam, U>,

Source§

type Scalar = <T as Cam16FromUnclamped<WpParam, U>>::Scalar

The number type that’s used in parameters when converting.
Source§

fn into_cam16_unclamped( self, parameters: BakedParameters<WpParam, <U as IntoCam16Unclamped<WpParam, T>>::Scalar>, ) -> T

Converts self into C, using the provided parameters.
Source§

impl<T, U> IntoColor<U> for T
where U: FromColor<T>,

Source§

fn into_color(self) -> U

Convert into T with values clamped to the color defined bounds Read more
Source§

impl<T, U> IntoColorUnclamped<U> for T
where U: FromColorUnclamped<T>,

Source§

fn into_color_unclamped(self) -> U

Convert into T. The resulting color might be invalid in its color space Read more
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> IntoStimulus<T> for T

Source§

fn into_stimulus(self) -> T

Converts self into T, while performing the appropriate scaling, rounding and clamping.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, C> TryComponentsInto<C> for T
where C: TryFromComponents<T>,

Source§

type Error = <C as TryFromComponents<T>>::Error

The error for when try_into_colors fails to cast.
Source§

fn try_components_into(self) -> Result<C, <T as TryComponentsInto<C>>::Error>

Try to cast this collection of color components into a collection of colors. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T, U> TryIntoColor<U> for T
where U: TryFromColor<T>,

Source§

fn try_into_color(self) -> Result<U, OutOfBounds<U>>

Convert into T, returning ok if the color is inside of its defined range, otherwise an OutOfBounds error is returned which contains the unclamped color. Read more
Source§

impl<C, U> UintsFrom<C> for U
where C: IntoUints<U>,

Source§

fn uints_from(colors: C) -> U

Cast a collection of colors into a collection of unsigned integers.
Source§

impl<C, U> UintsInto<C> for U
where C: FromUints<U>,

Source§

fn uints_into(self) -> C

Cast this collection of unsigned integers into a collection of colors.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,