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

            
4
use axum::{
5
    body::Body,
6
    extract::Request,
7
    http::{HeaderMap, HeaderValue, Uri},
8
    middleware::Next,
9
    response::Response,
10
};
11

            
12
const 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]
20
25
pub fn content_url(api: &str, query: Option<&str>) -> String {
21
25
    match query {
22
17
        Some(query) if !query.is_empty() => format!("{api}?{query}"),
23
12
        _ => api.to_string(),
24
    }
25
25
}
26

            
27
28
fn pairs(query: &str) -> Vec<(String, String)> {
28
28
    let mut pairs: Vec<(String, String)> = serde_urlencoded::from_str(query).unwrap_or_default();
29
28
    pairs.sort();
30
28
    pairs
31
28
}
32

            
33
16
fn browser_query(headers: &HeaderMap) -> Option<String> {
34
16
    let current: Uri = headers.get("hx-current-url")?.to_str().ok()?.parse().ok()?;
35
14
    Some(current.query().unwrap_or_default().to_string())
36
16
}
37

            
38
45
fn push_target(request: &Request<Body>) -> Option<String> {
39
45
    let headers = request.headers();
40
45
    headers.contains_key("hx-request").then_some(())?;
41
20
    let path = request.uri().path();
42
40
    let page = PAGES.into_iter().find(|page| path.ends_with(page))?;
43
16
    let query = request.uri().query().unwrap_or_default();
44
16
    if pairs(&browser_query(headers)?) == pairs(query) {
45
7
        return None;
46
7
    }
47
7
    Some(content_url(page, Some(query)))
48
45
}
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.
52
29
pub async fn push_report_url(request: Request<Body>, next: Next) -> Response {
53
29
    let target = push_target(&request);
54
29
    let mut response = next.run(request).await;
55
29
    if response.status().is_success()
56
27
        && let Some(value) = target.and_then(|target| HeaderValue::from_str(&target).ok())
57
    {
58
3
        response.headers_mut().insert("hx-push-url", value);
59
26
    }
60
29
    response
61
29
}
62

            
63
#[cfg(test)]
64
#[path = "bookmark_tests.rs"]
65
mod tests;