Skip to main content

web/pages/report/
bookmark.rs

1//! Report URLs that keep their settings: the shell loads its content with its
2//! own query, and Generate pushes the query it ran.
3
4use axum::{
5    body::Body,
6    extract::Request,
7    http::{HeaderMap, HeaderValue, Uri},
8    middleware::Next,
9    response::Response,
10};
11
12const PAGES: [&str; 3] = [
13    "/report/balance",
14    "/report/activity",
15    "/report/category-breakdown",
16];
17
18/// The API URL a report shell loads its content from: `api` with the shell's own query.
19#[must_use]
20pub fn content_url(api: &str, query: Option<&str>) -> String {
21    match query {
22        Some(query) if !query.is_empty() => format!("{api}?{query}"),
23        _ => api.to_string(),
24    }
25}
26
27fn pairs(query: &str) -> Vec<(String, String)> {
28    let mut pairs: Vec<(String, String)> = serde_urlencoded::from_str(query).unwrap_or_default();
29    pairs.sort();
30    pairs
31}
32
33fn browser_query(headers: &HeaderMap) -> Option<String> {
34    let current: Uri = headers.get("hx-current-url")?.to_str().ok()?.parse().ok()?;
35    Some(current.query().unwrap_or_default().to_string())
36}
37
38fn push_target(request: &Request<Body>) -> Option<String> {
39    let headers = request.headers();
40    headers.contains_key("hx-request").then_some(())?;
41    let path = request.uri().path();
42    let page = PAGES.into_iter().find(|page| path.ends_with(page))?;
43    let query = request.uri().query().unwrap_or_default();
44    if pairs(&browser_query(headers)?) == pairs(query) {
45        return None;
46    }
47    Some(content_url(page, Some(query)))
48}
49
50/// Answers a Generate or Clear whose settings differ from the address bar
51/// with the page URL to push; the shell's own content load pushes nothing.
52pub async fn push_report_url(request: Request<Body>, next: Next) -> Response {
53    let target = push_target(&request);
54    let mut response = next.run(request).await;
55    if response.status().is_success()
56        && let Some(value) = target.and_then(|target| HeaderValue::from_str(&target).ok())
57    {
58        response.headers_mut().insert("hx-push-url", value);
59    }
60    response
61}
62
63#[cfg(test)]
64#[path = "bookmark_tests.rs"]
65mod tests;