From 08d858927d8d3696b16c4c899f1177a4e4a5aa2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ond=C5=99ej=20Hru=C5=A1ka?= Date: Mon, 30 Dec 2019 13:27:44 +0100 Subject: [PATCH] scroll to the right page in redirects to card list --- src/main.rs | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index bbd629a..921e7e6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,18 +34,30 @@ pub struct ListContext<'a> { pub pages: usize, } +const per_page: usize = 20; + +fn find_page_with_card(store : &Store, card_id : usize) -> Option { + if let Some((n, _)) = store.data.cards.iter().enumerate().find(|(_n, (id, _card))| **id == card_id) { + Some(n / per_page) + } else { + None + } +} + #[get("/?&")] fn route_index(store: State>, page: Option, card: Option) -> Template { let rg = store.read(); - let per_page: usize = 20; + let mut page = page.unwrap_or_default(); let n_pages = (rg.data.cards.len() as f64 / per_page as f64).ceil() as usize; if let Some(card_id) = card { - if let Some((n, _)) = rg.data.cards.iter().enumerate().find(|(_n, (id, _card))| **id == card_id) { - page = n / per_page; - } + page = find_page_with_card(&rg, card_id).unwrap_or(page); + } + + if page >= n_pages { + page = n_pages - 1; } let context = ListContext { @@ -250,9 +262,11 @@ fn route_edit_save(id: usize, form: Form, store: State>) -> Redirect { let mut rg = store.write(); + let page = find_page_with_card(&rg, id).unwrap_or(0); + rg.delete_card(id); - Redirect::found(uri!(route_index: page=_, card=_)) + Redirect::found(uri!(route_index: page=page, card=_)) } fn main() {