chore: added delete to snippet
bc355051
2 file(s) · +39 −1
| 105 | 105 | } |
|
| 106 | 106 | } |
|
| 107 | 107 | ||
| 108 | + | fn delete_selected(&mut self, db: &sipp_rust::db::Db) { |
|
| 109 | + | if let Some(selected_index) = self.list_state.selected() { |
|
| 110 | + | if let Some(snippet) = self.snippets.get(selected_index) { |
|
| 111 | + | // Delete from database |
|
| 112 | + | if sipp_rust::db::delete_snippet_by_short_id(db, &snippet.short_id) { |
|
| 113 | + | // Remove from local vector |
|
| 114 | + | self.snippets.remove(selected_index); |
|
| 115 | + | ||
| 116 | + | // Adjust selection after deletion |
|
| 117 | + | if self.snippets.is_empty() { |
|
| 118 | + | self.list_state.select(None); |
|
| 119 | + | } else if selected_index >= self.snippets.len() { |
|
| 120 | + | self.list_state.select(Some(self.snippets.len() - 1)); |
|
| 121 | + | } else { |
|
| 122 | + | self.list_state.select(Some(selected_index)); |
|
| 123 | + | } |
|
| 124 | + | ||
| 125 | + | self.status_message = Some(("Deleted!".to_string(), Instant::now())); |
|
| 126 | + | } else { |
|
| 127 | + | self.status_message = Some(("Failed to delete!".to_string(), Instant::now())); |
|
| 128 | + | } |
|
| 129 | + | } |
|
| 130 | + | } |
|
| 131 | + | } |
|
| 132 | + | ||
| 108 | 133 | fn clear_expired_status(&mut self) { |
|
| 109 | 134 | if let Some((_, time)) = &self.status_message { |
|
| 110 | 135 | if time.elapsed() > Duration::from_secs(2) { |
|
| 153 | 178 | let db = db::init_db(); |
|
| 154 | 179 | let snippets = db::get_all_snippets(&db); |
|
| 155 | 180 | ||
| 156 | - | ratatui::run(|terminal| run_app(terminal, App::new(snippets))) |
|
| 181 | + | ratatui::run(|terminal| run_app(terminal, App::new(snippets), &db)) |
|
| 157 | 182 | } |
|
| 158 | 183 | ||
| 159 | 184 | fn run_app( |
|
| 160 | 185 | terminal: &mut DefaultTerminal, |
|
| 161 | 186 | mut app: App, |
|
| 187 | + | db: &sipp_rust::db::Db, |
|
| 162 | 188 | ) -> Result<(), Box<dyn std::error::Error>> { |
|
| 163 | 189 | while !app.should_quit { |
|
| 164 | 190 | app.clear_expired_status(); |
|
| 304 | 330 | KeyCode::Char('j') | KeyCode::Down => app.move_down(), |
|
| 305 | 331 | KeyCode::Char('k') | KeyCode::Up => app.move_up(), |
|
| 306 | 332 | KeyCode::Char('y') => app.copy_selected(), |
|
| 333 | + | KeyCode::Char('d') => app.delete_selected(db), |
|
| 307 | 334 | KeyCode::Char('?') => app.show_help = true, |
|
| 308 | 335 | KeyCode::Enter => { |
|
| 309 | 336 | if app.selected_snippet().is_some() { |
|
| 87 | 87 | .filter_map(|r| r.ok()) |
|
| 88 | 88 | .collect() |
|
| 89 | 89 | } |
|
| 90 | + | ||
| 91 | + | pub fn delete_snippet_by_short_id(db: &Db, short_id: &str) -> bool { |
|
| 92 | + | let conn = db.lock().unwrap(); |
|
| 93 | + | match conn.execute( |
|
| 94 | + | "DELETE FROM snippets WHERE short_id = ?1", |
|
| 95 | + | params![short_id], |
|
| 96 | + | ) { |
|
| 97 | + | Ok(rows_affected) => rows_affected > 0, |
|
| 98 | + | Err(_) => false, |
|
| 99 | + | } |
|
| 100 | + | } |