Replace the task list with new data, preserving the current selection if the previously selected task still exists in the new list.
(&mut self, tasks: Vec<Task>)
| 235 | /// Replace the task list with new data, preserving the current selection |
| 236 | /// if the previously selected task still exists in the new list. |
| 237 | pub fn update_tasks(&mut self, tasks: Vec<Task>) { |
| 238 | let prev_selected = self |
| 239 | .task_list_state |
| 240 | .selected() |
| 241 | .and_then(|idx| self.tasks.get(idx).map(|t| (idx, t.id.clone()))); |
| 242 | |
| 243 | self.tasks = tasks; |
| 244 | |
| 245 | if let Some((prev_idx, prev_id)) = prev_selected { |
| 246 | let new_idx = self.tasks.iter().position(|t| t.id == prev_id); |
| 247 | match new_idx { |
| 248 | Some(idx) => self.task_list_state.select(Some(idx)), |
| 249 | None if !self.tasks.is_empty() => { |
| 250 | self.task_list_state |
| 251 | .select(Some(prev_idx.min(self.tasks.len() - 1))); |
| 252 | } |
| 253 | None => self.task_list_state.select(None), |
| 254 | } |
| 255 | } else if !self.tasks.is_empty() { |
| 256 | self.task_list_state.select(Some(0)); |
| 257 | } |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | #[cfg(test)] |
no outgoing calls