Don’t use Option as selected index

This commit is contained in:
kageru 2020-01-24 11:40:16 +01:00
parent cc7b8beda9
commit 05ed013485
2 changed files with 20 additions and 24 deletions

@ -76,7 +76,7 @@ fn refresh(terminal: &mut tui::Terminal<impl Backend>, tracc: &Tracc) -> Result<
SelectableList::default()
.block(block)
.items(&tracc.printable_todos())
.select(tracc.selected)
.select(Some(tracc.selected))
.highlight_style(Style::default().fg(Color::LightGreen))
.highlight_symbol(">")
.render(&mut frame, size);

@ -9,7 +9,7 @@ use tui::Terminal;
pub struct Tracc {
// We use owned strings here because they’re easier to manipulate when editing.
pub todos: Vec<Todo>,
pub selected: Option<usize>,
pub selected: usize,
pub mode: Mode,
}
@ -41,7 +41,7 @@ impl Tracc {
pub fn open_or_create() -> Self {
Self {
todos: read_todos().unwrap_or(vec![Todo::new("This is a list entry")]),
selected: Some(0),
selected: 0,
mode: Mode::Normal,
}
}
@ -54,22 +54,20 @@ impl Tracc {
}
pub fn selection_down(&mut self) {
self.selected = self.selected.map(|i| (i + 1).min(self.todos.len() - 1));
self.selected = (self.selected + 1).min(self.todos.len().saturating_sub(1));
}
pub fn selection_up(&mut self) {
self.selected = self.selected.map(|i| i.saturating_sub(1));
self.selected = self.selected.saturating_sub(1);
}
pub fn insert(&mut self, todo: Todo) {
if let Some(position) = self.selected {
if position == self.todos.len().saturating_sub(1) {
self.todos.push(todo);
self.selected = Some(self.todos.len() - 1);
} else {
self.todos.insert(position + 1, todo);
self.selected = Some(position + 1);
}
if self.selected == self.todos.len().saturating_sub(1) {
self.todos.push(todo);
self.selected = self.todos.len() - 1;
} else {
self.todos.insert(self.selected + 1, todo);
self.selected += 1;
}
self.mode = Mode::Normal;
}
@ -78,19 +76,17 @@ impl Tracc {
if self.todos.is_empty() {
return None;
}
if let Some(n) = self.selected {
self.selected = Some(n.min(self.todos.len() - 1));
return Some(self.todos.remove(n));
}
None
let index = self.selected;
self.selected = index.min(self.todos.len() - 1);
return Some(self.todos.remove(index));
}
pub fn toggle_current(&mut self) {
self.current().done = !self.current().done;
self.todos[self.selected].done = !self.todos[self.selected].done;
}
fn current(&mut self) -> &mut Todo {
&mut self.todos[self.selected.unwrap()]
fn current(&self) -> &Todo {
&self.todos[self.selected]
}
pub fn set_mode(
@ -103,7 +99,7 @@ impl Tracc {
Mode::Normal => {
if self.current().text.is_empty() {
self.remove_current();
self.selected.as_mut().map(|n| *n = n.saturating_sub(1));
self.selected = self.selected.saturating_sub(1);
}
term.hide_cursor()?
}
@ -113,11 +109,11 @@ impl Tracc {
}
pub fn append_to_current(&mut self, chr: char) {
self.todos[self.selected.unwrap()].text.push(chr);
self.todos[self.selected].text.push(chr);
}
pub fn current_pop(&mut self) {
self.todos[self.selected.unwrap()].text.pop();
self.todos[self.selected].text.pop();
}
pub fn persist(self) {