Lines
97.24 %
Functions
48.53 %
Branches
100 %
//! Dropdown / list select widget.
//!
//! Holds an ordered list of options and a focused index. Navigation wraps
//! around within the type-ahead filtered set. The widget submits the focused
//! option's `id` (usually a UUID), not its display label.
use std::cell::Cell;
use tvui::{RowWindow, Viewport};
/// A single entry in a [`SelectWidget`] option list.
#[derive(Debug, Clone)]
pub struct SelectOption {
pub id: String,
pub label: String,
}
/// `options` led by `(none)`, which keeps an unchosen select empty.
pub fn with_none(options: Vec<SelectOption>) -> Vec<SelectOption> {
let none = SelectOption {
id: String::new(),
label: "(none)".to_string(),
};
std::iter::once(none).chain(options).collect()
/// A scrollable pick-list widget with type-ahead filtering.
///
/// `focused` indexes the **filtered** set returned by [`Self::matches`], not
/// `options` directly. When the filter matches nothing, `value()`/`display()`
/// return `""` and `next()`/`prev()` are no-ops.
pub struct SelectWidget {
options: Vec<SelectOption>,
focused: usize,
pub open: bool,
query: String,
/// The option focused when the list opened; Esc and typing back to empty return to it.
opened_at: usize,
/// An id chosen before its option existed; applied by the next `set_options`.
wanted: Option<String>,
/// The first option on screen in the open list, kept between frames by the draw.
window: RowWindow,
/// Where the field showing the filter is scrolled to, kept by the draw.
scroll: Cell<Viewport>,
impl SelectWidget {
#[must_use]
pub fn new() -> Self {
Self {
options: Vec::new(),
focused: 0,
open: false,
query: String::new(),
opened_at: 0,
wanted: None,
window: RowWindow::default(),
scroll: Cell::default(),
/// The cell the draw of the field showing this select keeps its scroll in.
pub fn scroll(&self) -> &Cell<Viewport> {
&self.scroll
/// A select over a choice field's `(id, label)` options, on `default` when given.
pub fn choice(options: &[(&str, &str)], default: Option<&str>) -> Self {
let mut select = Self::new();
select.set_options(
options
.iter()
.map(|&(id, label)| SelectOption {
id: id.to_string(),
label: label.to_string(),
})
.collect(),
);
if let Some(default) = default {
select.select_id(default);
select
/// Replace the option list, focus the option chosen earlier by id (else
/// the first), and clear any query.
pub fn set_options(&mut self, options: Vec<SelectOption>) {
self.options = options;
self.focused = 0;
self.query.clear();
if let Some(id) = self.wanted.take() {
self.select_id(&id);
/// Indices into `options` whose label contains `query` case-insensitively.
/// An empty query returns all indices.
pub fn matches(&self) -> Vec<usize> {
if self.query.is_empty() {
return (0..self.options.len()).collect();
let q = self.query.to_lowercase();
self.options
.enumerate()
.filter(|(_, o)| o.label.to_lowercase().contains(&q))
.map(|(i, _)| i)
.collect()
/// The `id` of the focused filtered option, or `""` when no match exists.
/// An id chosen before any option was loaded is returned until they arrive.
pub fn value(&self) -> &str {
if let Some(wanted) = self.wanted.as_deref().filter(|_| self.options.is_empty()) {
return wanted;
let m = self.matches();
m.get(self.focused)
.map(|&idx| self.options[idx].id.as_str())
.unwrap_or("")
/// The display label of the focused filtered option, or `""` when no match.
pub fn display(&self) -> &str {
.map(|&idx| self.options[idx].label.as_str())
/// Focus the option with this `id`, clearing the query; an unknown id
/// leaves the selection unchanged and is remembered for the next option list.
pub fn select_id(&mut self, id: &str) {
match self.options.iter().position(|o| o.id == id) {
Some(idx) => {
self.focused = idx;
self.wanted = None;
None => self.wanted = Some(id.to_string()),
/// Where the open list's window starts, written by the draw.
pub fn window(&self) -> &RowWindow {
&self.window
/// The raw option list, for rendering.
pub fn options(&self) -> &[SelectOption] {
&self.options
/// The typed filter while there is one, else the selected label.
pub fn shown(&self) -> &str {
match self.query() {
"" => self.display(),
query => query,
/// The active type-ahead query string.
pub fn query(&self) -> &str {
&self.query
/// Index of the focused entry within the filtered set (i.e. `matches()`).
pub fn focused_in_filtered(&self) -> usize {
self.focused
/// Advance focus by one step within the filtered set, wrapping around.
pub fn next(&mut self) {
let n = self.matches().len();
if n == 0 {
return;
self.focused = (self.focused + 1) % n;
/// Retreat focus by one step within the filtered set, wrapping around.
pub fn prev(&mut self) {
self.focused = (self.focused + n - 1) % n;
/// Open the option list, remembering the option to go back to on Esc.
pub fn open_list(&mut self) {
if !self.open {
self.opened_at = self.focused;
self.window.reset();
self.open = true;
/// Close the list on the option it was opened with, dropping the query.
pub fn cancel(&mut self) {
self.focused = self.opened_at;
self.open = false;
/// Append a character to the type-ahead query and reset focus to 0.
pub fn filter_push(&mut self, c: char) {
self.open_list();
self.query.push(c);
/// Remove the last character from the type-ahead query and reset focus to 0.
pub fn filter_pop(&mut self) {
if self.query.pop().is_none() {
self.focused = if self.query.is_empty() {
self.opened_at
} else {
0
/// Close the list on the highlighted option; an unmatched query is dropped first.
pub fn close(&mut self) {
if self.matches().get(self.focused).is_none() {
self.confirm();
/// Closes the list on the filtered option `index`; an index past the options changes nothing.
pub fn pick(&mut self, index: usize) {
if index < self.matches().len() {
self.focused = index;
/// Moves the focus a page of the open list down or up, stopping at its ends.
pub fn page(&mut self, down: bool) {
let last = self.matches().len().saturating_sub(1);
let page = self.window.page();
self.focused = if down {
self.focused.saturating_add(page).min(last)
self.focused.saturating_sub(page)
/// Resolve the current filtered selection to the raw options index, clear
/// the query, and close the dropdown. Call this on SelectConfirm so the
/// selection survives query removal.
pub fn confirm(&mut self) {
let Some(&raw_idx) = m.get(self.focused) else {
// Nothing matches the query — keep the filter open so the user can
// correct it rather than silently committing the first option.
self.focused = raw_idx;
/// Replace the option list, keeping the previously selected id focused if
/// it exists in the new list; falls back to index 0 otherwise. Clears query.
pub fn set_options_preserving_id(&mut self, options: Vec<SelectOption>) {
let current_id = self
.wanted
.take()
.unwrap_or_else(|| self.value().to_string());
self.focused = self
.options
.position(|o| o.id == current_id)
.unwrap_or(0);
impl Default for SelectWidget {
fn default() -> Self {
Self::new()
#[cfg(test)]
#[path = "select_tests.rs"]
mod tests;