Lines
100 %
Functions
56.25 %
Branches
//! Report URLs that keep their settings: the shell loads its content with its
//! own query, and Generate pushes the query it ran.
use axum::{
body::Body,
extract::Request,
http::{HeaderMap, HeaderValue, Uri},
middleware::Next,
response::Response,
};
const PAGES: [&str; 3] = [
"/report/balance",
"/report/activity",
"/report/category-breakdown",
];
/// The API URL a report shell loads its content from: `api` with the shell's own query.
#[must_use]
pub fn content_url(api: &str, query: Option<&str>) -> String {
match query {
Some(query) if !query.is_empty() => format!("{api}?{query}"),
_ => api.to_string(),
}
fn pairs(query: &str) -> Vec<(String, String)> {
let mut pairs: Vec<(String, String)> = serde_urlencoded::from_str(query).unwrap_or_default();
pairs.sort();
pairs
fn browser_query(headers: &HeaderMap) -> Option<String> {
let current: Uri = headers.get("hx-current-url")?.to_str().ok()?.parse().ok()?;
Some(current.query().unwrap_or_default().to_string())
fn push_target(request: &Request<Body>) -> Option<String> {
let headers = request.headers();
headers.contains_key("hx-request").then_some(())?;
let path = request.uri().path();
let page = PAGES.into_iter().find(|page| path.ends_with(page))?;
let query = request.uri().query().unwrap_or_default();
if pairs(&browser_query(headers)?) == pairs(query) {
return None;
Some(content_url(page, Some(query)))
/// Answers a Generate or Clear whose settings differ from the address bar
/// with the page URL to push; the shell's own content load pushes nothing.
pub async fn push_report_url(request: Request<Body>, next: Next) -> Response {
let target = push_target(&request);
let mut response = next.run(request).await;
if response.status().is_success()
&& let Some(value) = target.and_then(|target| HeaderValue::from_str(&target).ok())
{
response.headers_mut().insert("hx-push-url", value);
response
#[cfg(test)]
#[path = "bookmark_tests.rs"]
mod tests;