rustlings/src/list/state.rs

390 lines
12 KiB
Rust
Raw Normal View History

use anyhow::{Context, Result};
2024-08-24 01:14:12 +03:00
use crossterm::{
2024-08-24 18:17:56 +03:00
cursor::{MoveTo, MoveToNextLine},
2024-08-24 18:45:02 +03:00
style::{Attribute, Color, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor},
2024-08-24 18:17:56 +03:00
terminal::{self, BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
2024-08-24 01:14:12 +03:00
QueueableCommand,
2024-04-07 20:05:29 +03:00
};
2024-08-24 01:14:12 +03:00
use std::{
fmt::Write as _,
2024-08-24 18:17:56 +03:00
io::{self, StdoutLock, Write},
2024-08-24 01:14:12 +03:00
};
2024-08-26 01:49:56 +03:00
use crate::{
app_state::AppState,
exercise::Exercise,
2024-09-04 03:19:45 +03:00
term::{progress_bar, CountedWrite, MaxLenWriter},
2024-08-26 01:49:56 +03:00
};
2024-08-24 20:18:13 +03:00
2024-08-27 01:03:50 +03:00
use super::scroll_state::ScrollState;
2024-08-28 01:56:22 +03:00
const COL_SPACING: usize = 2;
2024-04-07 20:05:29 +03:00
2024-08-25 20:24:12 +03:00
fn next_ln(stdout: &mut StdoutLock) -> io::Result<()> {
2024-08-24 18:17:56 +03:00
stdout
.queue(Clear(ClearType::UntilNewLine))?
.queue(MoveToNextLine(1))?;
Ok(())
}
2024-04-07 20:05:29 +03:00
2024-04-08 03:41:48 +03:00
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Filter {
Done,
Pending,
None,
}
2024-08-24 01:14:12 +03:00
pub struct ListState<'a> {
2024-08-25 20:24:12 +03:00
/// Footer message to be displayed if not empty.
2024-04-08 02:33:11 +03:00
pub message: String,
2024-09-04 02:05:30 +03:00
pub search_query: String,
app_state: &'a mut AppState,
2024-08-27 01:03:50 +03:00
scroll_state: ScrollState,
2024-08-28 01:56:22 +03:00
name_col_padding: Vec<u8>,
2024-08-25 20:24:12 +03:00
filter: Filter,
2024-08-24 18:17:56 +03:00
term_width: u16,
term_height: u16,
2024-08-25 20:24:12 +03:00
show_footer: bool,
2024-04-07 20:05:29 +03:00
}
2024-08-24 01:14:12 +03:00
impl<'a> ListState<'a> {
pub fn build(app_state: &'a mut AppState, stdout: &mut StdoutLock) -> Result<Self> {
2024-08-24 18:17:56 +03:00
stdout.queue(Clear(ClearType::All))?;
2024-08-25 20:24:12 +03:00
let name_col_title_len = 4;
2024-08-24 01:14:12 +03:00
let name_col_width = app_state
.exercises()
2024-04-07 20:05:29 +03:00
.iter()
.map(|exercise| exercise.name.len())
.max()
2024-08-25 20:24:12 +03:00
.map_or(name_col_title_len, |max| max.max(name_col_title_len));
2024-08-28 01:56:22 +03:00
let name_col_padding = vec![b' '; name_col_width + COL_SPACING];
2024-04-07 20:05:29 +03:00
2024-08-25 20:24:12 +03:00
let filter = Filter::None;
2024-08-24 01:14:12 +03:00
let n_rows_with_filter = app_state.exercises().len();
2024-08-25 21:29:54 +03:00
let selected = app_state.current_exercise_ind();
2024-04-11 15:35:30 +03:00
let (width, height) = terminal::size().context("Failed to get the terminal size")?;
2024-08-27 01:03:50 +03:00
let scroll_state = ScrollState::new(n_rows_with_filter, Some(selected), 5);
2024-08-24 01:14:12 +03:00
let mut slf = Self {
2024-04-08 03:41:48 +03:00
message: String::with_capacity(128),
2024-09-04 02:05:30 +03:00
search_query: String::new(),
app_state,
2024-08-27 01:03:50 +03:00
scroll_state,
2024-08-28 01:56:22 +03:00
name_col_padding,
2024-08-25 20:24:12 +03:00
filter,
// Set by `set_term_size`
term_width: 0,
term_height: 0,
show_footer: true,
2024-08-24 01:14:12 +03:00
};
2024-08-25 20:24:12 +03:00
slf.set_term_size(width, height);
2024-08-24 20:18:13 +03:00
slf.draw(stdout)?;
2024-08-24 01:14:12 +03:00
Ok(slf)
}
2024-08-25 21:29:54 +03:00
pub fn set_term_size(&mut self, width: u16, height: u16) {
self.term_width = width;
self.term_height = height;
if height == 0 {
return;
}
let header_height = 1;
2024-09-01 23:02:07 +03:00
// 1 progress bar, 2 footer message lines.
let footer_height = 3;
2024-08-25 21:29:54 +03:00
self.show_footer = height > header_height + footer_height;
2024-08-27 01:03:50 +03:00
self.scroll_state.set_max_n_rows_to_display(
height.saturating_sub(header_height + u16::from(self.show_footer) * footer_height)
as usize,
);
2024-08-25 21:29:54 +03:00
}
2024-08-24 20:18:13 +03:00
fn draw_rows(
&self,
stdout: &mut StdoutLock,
filtered_exercises: impl Iterator<Item = (usize, &'a Exercise)>,
) -> io::Result<usize> {
2024-08-24 18:17:56 +03:00
let current_exercise_ind = self.app_state.current_exercise_ind();
2024-08-27 01:03:50 +03:00
let row_offset = self.scroll_state.offset();
2024-08-24 18:17:56 +03:00
let mut n_displayed_rows = 0;
2024-08-24 20:18:13 +03:00
for (exercise_ind, exercise) in filtered_exercises
2024-08-27 01:03:50 +03:00
.skip(row_offset)
.take(self.scroll_state.max_n_rows_to_display())
2024-08-24 20:18:13 +03:00
{
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
2024-08-27 01:03:50 +03:00
if self.scroll_state.selected() == Some(row_offset + n_displayed_rows) {
writer.stdout.queue(SetBackgroundColor(Color::Rgb {
2024-08-26 01:53:42 +03:00
r: 40,
g: 40,
b: 40,
2024-08-24 18:45:02 +03:00
}))?;
// The crab emoji has the width of two ascii chars.
writer.add_to_len(2);
writer.stdout.write_all("🦀".as_bytes())?;
2024-08-24 18:17:56 +03:00
} else {
writer.write_ascii(b" ")?;
2024-08-24 18:17:56 +03:00
}
if exercise_ind == current_exercise_ind {
writer.stdout.queue(SetForegroundColor(Color::Red))?;
writer.write_ascii(b">>>>>>> ")?;
2024-08-24 18:17:56 +03:00
} else {
writer.write_ascii(b" ")?;
2024-08-24 18:17:56 +03:00
}
if exercise.done {
writer.stdout.queue(SetForegroundColor(Color::Green))?;
writer.write_ascii(b"DONE ")?;
2024-08-24 18:17:56 +03:00
} else {
writer.stdout.queue(SetForegroundColor(Color::Yellow))?;
writer.write_ascii(b"PENDING ")?;
2024-08-24 18:17:56 +03:00
}
writer.stdout.queue(SetForegroundColor(Color::Reset))?;
2024-08-24 18:17:56 +03:00
writer.write_str(exercise.name)?;
2024-08-28 01:56:22 +03:00
writer.write_ascii(&self.name_col_padding[exercise.name.len()..])?;
2024-08-24 18:17:56 +03:00
// The list links aren't shown correctly in VS Code on Windows.
// But VS Code shows its own links anyway.
if self.app_state.vs_code() {
writer.write_str(exercise.path)?;
} else {
2024-09-04 03:19:45 +03:00
exercise.terminal_file_link(&mut writer)?;
}
2024-08-24 18:17:56 +03:00
next_ln(stdout)?;
2024-08-24 18:45:02 +03:00
stdout.queue(ResetColor)?;
2024-08-24 18:17:56 +03:00
n_displayed_rows += 1;
}
2024-08-24 20:18:13 +03:00
Ok(n_displayed_rows)
}
pub fn draw(&mut self, stdout: &mut StdoutLock) -> io::Result<()> {
if self.term_height == 0 {
return Ok(());
}
stdout.queue(BeginSynchronizedUpdate)?.queue(MoveTo(0, 0))?;
// Header
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
writer.write_ascii(b" Current State Name")?;
2024-08-29 17:01:41 +03:00
writer.write_ascii(&self.name_col_padding[4..])?;
writer.write_ascii(b"Path")?;
next_ln(stdout)?;
2024-08-24 20:18:13 +03:00
// Rows
let iter = self.app_state.exercises().iter().enumerate();
let n_displayed_rows = match self.filter {
2024-08-25 20:24:12 +03:00
Filter::Done => self.draw_rows(stdout, iter.filter(|(_, exercise)| exercise.done))?,
Filter::Pending => {
self.draw_rows(stdout, iter.filter(|(_, exercise)| !exercise.done))?
}
Filter::None => self.draw_rows(stdout, iter)?,
2024-08-24 20:18:13 +03:00
};
2024-08-27 01:03:50 +03:00
for _ in 0..self.scroll_state.max_n_rows_to_display() - n_displayed_rows {
2024-08-25 20:24:12 +03:00
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
}
2024-08-25 20:24:12 +03:00
if self.show_footer {
2024-08-24 18:17:56 +03:00
progress_bar(
&mut MaxLenWriter::new(stdout, self.term_width as usize),
2024-08-24 18:17:56 +03:00
self.app_state.n_done(),
self.app_state.exercises().len() as u16,
self.term_width,
)?;
2024-08-25 20:24:12 +03:00
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
let mut writer = MaxLenWriter::new(stdout, self.term_width as usize);
2024-08-24 18:17:56 +03:00
if self.message.is_empty() {
2024-08-25 21:29:54 +03:00
// Help footer message
2024-08-27 01:03:50 +03:00
if self.scroll_state.selected().is_some() {
writer.write_str("↓/j ↑/k home/g end/G | <c>ontinue at | <r>eset exercise")?;
2024-09-01 21:44:19 +03:00
next_ln(stdout)?;
writer = MaxLenWriter::new(stdout, self.term_width as usize);
2024-09-01 21:44:19 +03:00
writer.write_ascii(b"<s>earch | filter ")?;
2024-08-24 18:17:56 +03:00
} else {
2024-08-25 21:29:54 +03:00
// Nothing selected (and nothing shown), so only display filter and quit.
writer.write_ascii(b"filter ")?;
2024-08-24 18:17:56 +03:00
}
match self.filter {
Filter::Done => {
writer
.stdout
2024-08-24 18:17:56 +03:00
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<d>one")?;
writer.stdout.queue(ResetColor)?;
writer.write_ascii(b"/<p>ending")?;
2024-08-24 18:17:56 +03:00
}
Filter::Pending => {
writer.write_ascii(b"<d>one/")?;
writer
.stdout
2024-08-24 18:17:56 +03:00
.queue(SetForegroundColor(Color::Magenta))?
.queue(SetAttribute(Attribute::Underlined))?;
writer.write_ascii(b"<p>ending")?;
writer.stdout.queue(ResetColor)?;
2024-08-24 18:17:56 +03:00
}
Filter::None => writer.write_ascii(b"<d>one/<p>ending")?,
2024-08-24 18:17:56 +03:00
}
2024-08-25 21:29:54 +03:00
writer.write_ascii(b" | <q>uit list")?;
2024-08-24 18:17:56 +03:00
} else {
writer.stdout.queue(SetForegroundColor(Color::Magenta))?;
writer.write_str(&self.message)?;
2024-08-24 18:17:56 +03:00
stdout.queue(ResetColor)?;
next_ln(stdout)?;
}
2024-09-01 21:44:19 +03:00
next_ln(stdout)?;
2024-08-24 18:17:56 +03:00
}
stdout.queue(EndSynchronizedUpdate)?.flush()
}
2024-08-25 20:24:12 +03:00
fn update_rows(&mut self) {
2024-08-27 01:03:50 +03:00
let n_rows = match self.filter {
2024-08-24 01:14:12 +03:00
Filter::Done => self
.app_state
.exercises()
.iter()
2024-08-24 18:17:56 +03:00
.filter(|exercise| exercise.done)
2024-08-24 01:14:12 +03:00
.count(),
Filter::Pending => self
.app_state
.exercises()
.iter()
2024-08-24 18:17:56 +03:00
.filter(|exercise| !exercise.done)
2024-08-24 01:14:12 +03:00
.count(),
Filter::None => self.app_state.exercises().len(),
};
2024-08-27 01:03:50 +03:00
self.scroll_state.set_n_rows(n_rows);
2024-04-07 20:05:29 +03:00
}
2024-08-25 20:24:12 +03:00
#[inline]
pub fn filter(&self) -> Filter {
self.filter
}
pub fn set_filter(&mut self, filter: Filter) {
self.filter = filter;
self.update_rows();
}
2024-08-27 01:03:50 +03:00
#[inline]
2024-04-07 20:05:29 +03:00
pub fn select_next(&mut self) {
2024-08-27 01:03:50 +03:00
self.scroll_state.select_next();
2024-04-07 20:05:29 +03:00
}
2024-08-27 01:03:50 +03:00
#[inline]
2024-04-07 20:05:29 +03:00
pub fn select_previous(&mut self) {
2024-08-27 01:03:50 +03:00
self.scroll_state.select_previous();
2024-04-07 20:05:29 +03:00
}
2024-08-27 01:03:50 +03:00
#[inline]
2024-04-07 20:05:29 +03:00
pub fn select_first(&mut self) {
2024-08-27 01:03:50 +03:00
self.scroll_state.select_first();
2024-04-07 20:05:29 +03:00
}
2024-08-27 01:03:50 +03:00
#[inline]
2024-04-07 20:05:29 +03:00
pub fn select_last(&mut self) {
2024-08-27 01:03:50 +03:00
self.scroll_state.select_last();
2024-04-07 20:05:29 +03:00
}
2024-08-24 18:17:56 +03:00
fn selected_to_exercise_ind(&self, selected: usize) -> Result<usize> {
match self.filter {
Filter::Done => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::Pending => self
.app_state
.exercises()
.iter()
.enumerate()
.filter(|(_, exercise)| !exercise.done)
.nth(selected)
.context("Invalid selection index")
.map(|(ind, _)| ind),
Filter::None => Ok(selected),
2024-08-24 01:14:12 +03:00
}
2024-04-07 20:05:29 +03:00
}
2024-08-24 01:14:12 +03:00
pub fn reset_selected(&mut self) -> Result<()> {
2024-08-27 01:03:50 +03:00
let Some(selected) = self.scroll_state.selected() else {
2024-08-24 18:17:56 +03:00
self.message.push_str("Nothing selected to reset!");
2024-08-24 01:14:12 +03:00
return Ok(());
2024-04-11 15:35:30 +03:00
};
2024-08-24 18:17:56 +03:00
let exercise_ind = self.selected_to_exercise_ind(selected)?;
2024-08-25 21:29:54 +03:00
let exercise_name = self.app_state.reset_exercise_by_ind(exercise_ind)?;
2024-08-25 20:24:12 +03:00
self.update_rows();
2024-08-25 21:29:54 +03:00
write!(
self.message,
"The exercise `{exercise_name}` has been reset",
)?;
2024-08-24 01:14:12 +03:00
Ok(())
}
2024-09-02 04:05:23 +03:00
pub fn apply_search_query(&mut self) {
self.message.push_str("search:");
self.message.push_str(&self.search_query);
self.message.push('|');
if self.search_query.is_empty() {
return;
}
2024-09-04 02:20:48 +03:00
let is_search_result = |exercise: &Exercise| exercise.name.contains(&self.search_query);
let mut iter = self.app_state.exercises().iter();
let ind = match self.filter {
Filter::None => iter.position(is_search_result),
Filter::Done => iter
.filter(|exercise| exercise.done)
.position(is_search_result),
Filter::Pending => iter
.filter(|exercise| !exercise.done)
.position(is_search_result),
};
2024-09-04 02:05:30 +03:00
match ind {
Some(exercise_ind) => self.scroll_state.set_selected(exercise_ind),
None => self.message.push_str(" (not found)"),
}
}
// Return `true` if there was something to select.
pub fn selected_to_current_exercise(&mut self) -> Result<bool> {
2024-08-27 01:03:50 +03:00
let Some(selected) = self.scroll_state.selected() else {
self.message.push_str("Nothing selected to continue at!");
return Ok(false);
2024-04-11 15:35:30 +03:00
};
2024-08-24 18:17:56 +03:00
let exercise_ind = self.selected_to_exercise_ind(selected)?;
self.app_state.set_current_exercise_ind(exercise_ind)?;
2024-08-25 20:24:12 +03:00
Ok(true)
}
2024-04-07 20:05:29 +03:00
}