refactor: reduce duplication in handlers, templates, and view structs

- Replace inline redirect scripts with existing render_redirect_script()
  in 6 create handlers
- Add delete_button macro to detail_cards.html, used by 6 detail pages
- Unify 3 map_with_legend macros into 1 with LegendEntry iteration
This commit is contained in:
Jon Seager 2026-02-10 09:37:49 +00:00
parent 092bdce164
commit f6b51ccb38
No known key found for this signature in database
21 changed files with 115 additions and 202 deletions

View file

@ -10,7 +10,7 @@ use crate::application::routes::api::macros::{
define_delete_handler, define_get_handler, define_list_fragment_renderer,
};
use crate::application::routes::support::{
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request,
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request, render_redirect_script,
};
use crate::application::state::AppState;
use crate::domain::cafes::{Cafe, CafeSortKey, NewCafe, UpdateCafe};
@ -89,16 +89,7 @@ pub(crate) async fn create_cafe(
.await
.map_err(ApiError::from)
} else {
use axum::http::header::HeaderValue;
let script = format!("<script>window.location.href='{detail_url}'</script>");
let mut response = axum::response::Html(script).into_response();
response
.headers_mut()
.insert("datastar-selector", HeaderValue::from_static("body"));
response
.headers_mut()
.insert("datastar-mode", HeaderValue::from_static("append"));
Ok(response)
render_redirect_script(&detail_url).map_err(ApiError::from)
}
} else if matches!(source, PayloadSource::Form) {
Ok(Redirect::to(&detail_url).into_response())

View file

@ -6,7 +6,9 @@ use serde::Deserialize;
use crate::application::auth::AuthenticatedUser;
use crate::application::errors::{ApiError, AppError};
use crate::application::routes::support::{FlexiblePayload, PayloadSource, is_datastar_request};
use crate::application::routes::support::{
FlexiblePayload, PayloadSource, is_datastar_request, render_redirect_script,
};
use crate::application::state::AppState;
use crate::domain::cafes::NewCafe;
use crate::domain::cups::NewCup;
@ -92,16 +94,7 @@ pub(crate) async fn submit_checkin(
let detail_url = format!("/cups/{}", cup.id);
if is_datastar_request(&headers) {
use axum::http::header::HeaderValue;
let script = format!("<script>window.location.href='{detail_url}'</script>");
let mut response = axum::response::Html(script).into_response();
response
.headers_mut()
.insert("datastar-selector", HeaderValue::from_static("body"));
response
.headers_mut()
.insert("datastar-mode", HeaderValue::from_static("append"));
Ok(response)
render_redirect_script(&detail_url).map_err(ApiError::from)
} else if matches!(source, PayloadSource::Form) {
Ok(Redirect::to(&detail_url).into_response())
} else {

View file

@ -9,7 +9,7 @@ use crate::application::routes::api::macros::{
define_delete_handler, define_enriched_get_handler, define_list_fragment_renderer,
};
use crate::application::routes::support::{
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request,
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request, render_redirect_script,
};
use crate::application::state::AppState;
use crate::domain::cups::{CupFilter, CupSortKey, CupWithDetails, NewCup};
@ -67,16 +67,7 @@ pub(crate) async fn create_cup(
let detail_url = format!("/cups/{}", cup.id);
if is_datastar_request(&headers) {
use axum::http::header::HeaderValue;
let script = format!("<script>window.location.href='{detail_url}'</script>");
let mut response = axum::response::Html(script).into_response();
response
.headers_mut()
.insert("datastar-selector", HeaderValue::from_static("body"));
response
.headers_mut()
.insert("datastar-mode", HeaderValue::from_static("append"));
Ok(response)
render_redirect_script(&detail_url).map_err(ApiError::from)
} else if matches!(source, PayloadSource::Form) {
Ok(Redirect::to(&detail_url).into_response())
} else {

View file

@ -14,7 +14,7 @@ use crate::application::routes::api::macros::{
define_delete_handler, define_get_handler, define_list_fragment_renderer,
};
use crate::application::routes::support::{
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request,
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request, render_redirect_script,
};
use crate::application::state::AppState;
use crate::domain::gear::{Gear, GearCategory, GearFilter, GearSortKey, NewGear, UpdateGear};
@ -82,16 +82,7 @@ pub(crate) async fn create_gear(
.await
.map_err(ApiError::from)
} else {
use axum::http::header::HeaderValue;
let script = format!("<script>window.location.href='{detail_url}'</script>");
let mut response = axum::response::Html(script).into_response();
response
.headers_mut()
.insert("datastar-selector", HeaderValue::from_static("body"));
response
.headers_mut()
.insert("datastar-mode", HeaderValue::from_static("append"));
Ok(response)
render_redirect_script(&detail_url).map_err(ApiError::from)
}
} else if matches!(source, PayloadSource::Form) {
Ok(Redirect::to(&detail_url).into_response())

View file

@ -9,7 +9,7 @@ use crate::application::routes::api::macros::{
define_delete_handler, define_get_handler, define_list_fragment_renderer,
};
use crate::application::routes::support::{
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request,
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request, render_redirect_script,
};
use crate::application::state::AppState;
use crate::domain::ids::RoasterId;
@ -90,16 +90,7 @@ pub(crate) async fn create_roaster(
.await
.map_err(ApiError::from)
} else {
use axum::http::header::HeaderValue;
let script = format!("<script>window.location.href='{detail_url}'</script>");
let mut response = axum::response::Html(script).into_response();
response
.headers_mut()
.insert("datastar-selector", HeaderValue::from_static("body"));
response
.headers_mut()
.insert("datastar-mode", HeaderValue::from_static("append"));
Ok(response)
render_redirect_script(&detail_url).map_err(ApiError::from)
}
} else if matches!(source, PayloadSource::Form) {
Ok(Redirect::to(&detail_url).into_response())

View file

@ -11,7 +11,7 @@ use crate::application::routes::api::macros::{
define_delete_handler, define_enriched_get_handler, define_list_fragment_renderer,
};
use crate::application::routes::support::{
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request,
FlexiblePayload, ListQuery, PayloadSource, is_datastar_request, render_redirect_script,
};
use crate::application::state::AppState;
use crate::domain::ids::{RoastId, RoasterId};
@ -92,16 +92,7 @@ pub(crate) async fn create_roast(
.await
.map_err(ApiError::from)
} else {
use axum::http::header::HeaderValue;
let script = format!("<script>window.location.href='{detail_url}'</script>");
let mut response = axum::response::Html(script).into_response();
response
.headers_mut()
.insert("datastar-selector", HeaderValue::from_static("body"));
response
.headers_mut()
.insert("datastar-mode", HeaderValue::from_static("append"));
Ok(response)
render_redirect_script(&detail_url).map_err(ApiError::from)
}
} else if matches!(source, PayloadSource::Form) {
Ok(Redirect::to(&detail_url).into_response())

View file

@ -4,7 +4,7 @@ use crate::domain::roasters::Roaster;
use crate::domain::roasts::Roast;
use super::tasting_notes::TastingNoteView;
use super::{build_coffee_info, build_map_data, build_roaster_info};
use super::{LegendEntry, build_coffee_info, build_map_data, build_roaster_info};
#[derive(Debug, Clone)]
pub struct BagView {
@ -89,6 +89,7 @@ pub struct BagDetailView {
// Map
pub map_countries: String,
pub map_max: u32,
pub legend_entries: Vec<LegendEntry>,
// Slugs (for breadcrumbs)
pub roaster_slug: String,
pub roast_slug: String,
@ -143,6 +144,16 @@ impl BagDetailView {
.map(|d| d.format("%Y-%m-%d").to_string()),
map_countries,
map_max,
legend_entries: vec![
LegendEntry {
label: "Origin",
opacity: "",
},
LegendEntry {
label: "Roaster",
opacity: "opacity-50",
},
],
created_date: bag.bag.created_at.format("%Y-%m-%d").to_string(),
created_time: bag.bag.created_at.format("%H:%M").to_string(),
}

View file

@ -6,7 +6,7 @@ use crate::domain::roasters::Roaster;
use crate::domain::roasts::Roast;
use super::tasting_notes::TastingNoteView;
use super::{build_coffee_info, build_map_data, build_roaster_info, relative_date};
use super::{LegendEntry, build_coffee_info, build_map_data, build_roaster_info, relative_date};
#[derive(Clone)]
pub struct QuickNoteView {
@ -222,6 +222,7 @@ pub struct BrewDetailView {
// Map
pub map_countries: String,
pub map_max: u32,
pub legend_entries: Vec<LegendEntry>,
// Slugs (for breadcrumbs)
pub roaster_slug: String,
pub roast_slug: String,
@ -279,6 +280,16 @@ impl BrewDetailView {
filter_paper_name: brew.filter_paper_name,
map_countries,
map_max,
legend_entries: vec![
LegendEntry {
label: "Origin",
opacity: "",
},
LegendEntry {
label: "Roaster",
opacity: "opacity-50",
},
],
created_date: brew.brew.created_at.format("%Y-%m-%d").to_string(),
created_time: brew.brew.created_at.format("%H:%M").to_string(),
}

View file

@ -2,7 +2,7 @@ use crate::domain::cafes::Cafe;
use crate::domain::countries::{country_to_iso, iso_to_flag_emoji};
use crate::infrastructure::foursquare::NearbyCafe;
use super::build_map_data;
use super::{LegendEntry, build_map_data};
pub struct CafeDetailView {
pub id: String,
@ -13,6 +13,7 @@ pub struct CafeDetailView {
pub website: Option<String>,
pub map_countries: String,
pub map_max: u32,
pub legend_entries: Vec<LegendEntry>,
pub created_date: String,
pub created_time: String,
}
@ -33,6 +34,10 @@ impl CafeDetailView {
website: cafe.website,
map_countries,
map_max,
legend_entries: vec![LegendEntry {
label: "Cafe",
opacity: "",
}],
created_date: cafe.created_at.format("%Y-%m-%d").to_string(),
created_time: cafe.created_at.format("%H:%M").to_string(),
}

View file

@ -5,7 +5,7 @@ use crate::domain::roasters::Roaster;
use crate::domain::roasts::Roast;
use super::tasting_notes::TastingNoteView;
use super::{build_coffee_info, build_map_data, build_roaster_info};
use super::{LegendEntry, build_coffee_info, build_map_data, build_roaster_info};
#[derive(Clone)]
pub struct CupView {
@ -63,6 +63,7 @@ pub struct CupDetailView {
// Map
pub map_countries: String,
pub map_max: u32,
pub legend_entries: Vec<LegendEntry>,
// Slugs (for breadcrumbs)
pub roaster_slug: String,
pub roast_slug: String,
@ -115,6 +116,20 @@ impl CupDetailView {
cafe_slug: cafe.slug.clone(),
map_countries,
map_max,
legend_entries: vec![
LegendEntry {
label: "Cafe",
opacity: "",
},
LegendEntry {
label: "Origin",
opacity: "opacity-65",
},
LegendEntry {
label: "Roaster",
opacity: "opacity-35",
},
],
created_date: cup.cup.created_at.format("%Y-%m-%d").to_string(),
created_time: cup.cup.created_at.format("%H:%M").to_string(),
}

View file

@ -361,6 +361,12 @@ fn page_size_from_text(value: &str) -> PageSize {
}
}
/// A label + opacity pair for map legend entries on detail pages.
pub struct LegendEntry {
pub label: &'static str,
pub opacity: &'static str,
}
/// Shared coffee info fields extracted from a `Roast` for detail pages.
pub(crate) struct CoffeeInfo {
pub origin: String,

View file

@ -1,7 +1,7 @@
use crate::domain::countries::{country_to_iso, iso_to_flag_emoji};
use crate::domain::roasters::Roaster;
use super::build_map_data;
use super::{LegendEntry, build_map_data};
pub struct RoasterDetailView {
pub id: String,
@ -12,6 +12,7 @@ pub struct RoasterDetailView {
pub homepage: Option<String>,
pub map_countries: String,
pub map_max: u32,
pub legend_entries: Vec<LegendEntry>,
pub created_date: String,
pub created_time: String,
}
@ -32,6 +33,10 @@ impl RoasterDetailView {
homepage: roaster.homepage,
map_countries,
map_max,
legend_entries: vec![LegendEntry {
label: "Roaster",
opacity: "",
}],
created_date: roaster.created_at.format("%Y-%m-%d").to_string(),
created_time: roaster.created_at.format("%H:%M").to_string(),
}

View file

@ -3,7 +3,7 @@ use crate::domain::roasters::Roaster;
use crate::domain::roasts::{Roast, RoastWithRoaster};
use super::tasting_notes::{self, TastingNoteView};
use super::{build_coffee_info, build_map_data, build_roaster_info};
use super::{LegendEntry, build_coffee_info, build_map_data, build_roaster_info};
pub struct RoastView {
pub id: String,
@ -120,6 +120,7 @@ pub struct RoastDetailView {
// Map
pub map_countries: String,
pub map_max: u32,
pub legend_entries: Vec<LegendEntry>,
// Dates
pub created_date: String,
pub created_time: String,
@ -156,6 +157,16 @@ impl RoastDetailView {
roaster_homepage: roaster_info.homepage,
map_countries,
map_max,
legend_entries: vec![
LegendEntry {
label: "Origin",
opacity: "",
},
LegendEntry {
label: "Roaster",
opacity: "opacity-50",
},
],
created_date: roast.created_at.format("%Y-%m-%d").to_string(),
created_time: roast.created_at.format("%H:%M").to_string(),
}

View file

@ -32,7 +32,7 @@
{# ── Coffee + map ── #}
<div class="grid gap-6 md:grid-cols-2">
{{ detail::coffee_card(bag.roast_name, bag.roaster_name, bag.origin, bag.origin_flag, bag.region, bag.producer, bag.process, bag.tasting_notes, roaster_slug, roast_slug) }}
{{ detail::map_with_legend_2(bag.map_countries, bag.map_max, "Origin", "", "Roaster", "opacity-50") }}
{{ detail::map_with_legend(bag.map_countries, bag.map_max, bag.legend_entries) }}
</div>
{# ── Roaster & bag info ── #}

View file

@ -34,7 +34,7 @@
{# ── Coffee + map ── #}
<div class="grid gap-6 md:grid-cols-2">
{{ detail::coffee_card(brew.roast_name, brew.roaster_name, brew.origin, brew.origin_flag, brew.region, brew.producer, brew.process, brew.tasting_notes, roaster_slug, roast_slug) }}
{{ detail::map_with_legend_2(brew.map_countries, brew.map_max, "Origin", "", "Roaster", "opacity-50") }}
{{ detail::map_with_legend(brew.map_countries, brew.map_max, brew.legend_entries) }}
</div>
{# ── Roaster & gear ── #}
@ -100,14 +100,6 @@
</div>
{% if is_authenticated %}
<div class="rounded-lg border bg-surface p-5 flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium text-error transition hover:bg-surface-alt"
data-on:click="confirm('Delete this brew? This cannot be undone.') && @delete('/api/v1/brews/{{ brew.id }}')"
>
{{ icons::delete("h-4 w-4") }} Delete
</button>
</div>
{{ detail::delete_button("brew", "/api/v1/brews", brew.id) }}
{% endif %}
{% endblock %}

View file

@ -56,18 +56,10 @@
</dl>
</div>
{{ detail::map_with_legend_1(cafe.map_countries, cafe.map_max, "Cafe", "") }}
{{ detail::map_with_legend(cafe.map_countries, cafe.map_max, cafe.legend_entries) }}
</div>
{% if is_authenticated %}
<div class="rounded-lg border bg-surface p-5 flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium text-error transition hover:bg-surface-alt"
data-on:click="confirm('Delete this cafe? This cannot be undone.') && @delete('/api/v1/cafes/{{ cafe.id }}')"
>
{{ icons::delete("h-4 w-4") }} Delete
</button>
</div>
{{ detail::delete_button("cafe", "/api/v1/cafes", cafe.id) }}
{% endif %}
{% endblock %}

View file

@ -32,7 +32,7 @@
{# ── Coffee + map ── #}
<div class="grid gap-6 md:grid-cols-2">
{{ detail::coffee_card(cup.roast_name, cup.roaster_name, cup.origin, cup.origin_flag, cup.region, cup.producer, cup.process, cup.tasting_notes, roaster_slug, roast_slug) }}
{{ detail::map_with_legend_3(cup.map_countries, cup.map_max, "Cafe", "", "Origin", "opacity-65", "Roaster", "opacity-35") }}
{{ detail::map_with_legend(cup.map_countries, cup.map_max, cup.legend_entries) }}
</div>
{# ── Roaster & cafe ── #}
@ -81,14 +81,6 @@
</div>
{% if is_authenticated %}
<div class="rounded-lg border bg-surface p-5 flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium text-error transition hover:bg-surface-alt"
data-on:click="confirm('Delete this cup? This cannot be undone.') && @delete('/api/v1/cups/{{ cup.id }}')"
>
{{ icons::delete("h-4 w-4") }} Delete
</button>
</div>
{{ detail::delete_button("cup", "/api/v1/cups", cup.id) }}
{% endif %}
{% endblock %}

View file

@ -1,4 +1,5 @@
{% extends "base.html" %}
{% import "partials/detail_cards.html" as detail %}
{% import "partials/icons.html" as icons %}
{% block title %}Brewlog · {{ gear.make }} {{ gear.model }}{% endblock %}
{% block og_title %}{{ gear.make }} {{ gear.model }} — Brewlog{% endblock %}
@ -44,14 +45,6 @@
</div>
{% if is_authenticated %}
<div class="rounded-lg border bg-surface p-5 flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium text-error transition hover:bg-surface-alt"
data-on:click="confirm('Delete this gear? This cannot be undone.') && @delete('/api/v1/gear/{{ gear.id }}')"
>
{{ icons::delete("h-4 w-4") }} Delete
</button>
</div>
{{ detail::delete_button("gear", "/api/v1/gear", gear.id) }}
{% endif %}
{% endblock %}

View file

@ -27,7 +27,7 @@
<div class="grid gap-6 md:grid-cols-2">
{{ detail::coffee_card(roast.name, roast.roaster_name, roast.origin, roast.origin_flag, roast.region, roast.producer, roast.process, roast.tasting_notes, roaster_slug, "") }}
{{ detail::map_with_legend_2(roast.map_countries, roast.map_max, "Origin", "", "Roaster", "opacity-50") }}
{{ detail::map_with_legend(roast.map_countries, roast.map_max, roast.legend_entries) }}
</div>
<div class="grid gap-6 md:grid-cols-2">
@ -35,14 +35,6 @@
</div>
{% if is_authenticated %}
<div class="rounded-lg border bg-surface p-5 flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium text-error transition hover:bg-surface-alt"
data-on:click="confirm('Delete this roast? This cannot be undone.') && @delete('/api/v1/roasts/{{ roast.id }}')"
>
{{ icons::delete("h-4 w-4") }} Delete
</button>
</div>
{{ detail::delete_button("roast", "/api/v1/roasts", roast.id) }}
{% endif %}
{% endblock %}

View file

@ -63,18 +63,10 @@
</dl>
</div>
{{ detail::map_with_legend_1(roaster.map_countries, roaster.map_max, "Roaster", "") }}
{{ detail::map_with_legend(roaster.map_countries, roaster.map_max, roaster.legend_entries) }}
</div>
{% if is_authenticated %}
<div class="rounded-lg border bg-surface p-5 flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium text-error transition hover:bg-surface-alt"
data-on:click="confirm('Delete this roaster? This cannot be undone.') && @delete('/api/v1/roasters/{{ roaster.id }}')"
>
{{ icons::delete("h-4 w-4") }} Delete
</button>
</div>
{{ detail::delete_button("roaster", "/api/v1/roasters", roaster.id) }}
{% endif %}
{% endblock %}

View file

@ -99,7 +99,7 @@
</div>
{% endmacro %}
{% macro map_with_legend_1(map_countries, map_max, label1, opacity1) %}
{% macro map_with_legend(map_countries, map_max, legends) %}
{% if !map_countries.is_empty() %}
<div
class="relative rounded-lg border bg-surface overflow-hidden flex items-center"
@ -112,81 +112,29 @@
<div
class="absolute top-2 right-2 flex flex-col gap-1 text-2xs text-text-muted"
>
{% for entry in legends %}
<span class="inline-flex items-center gap-1">
<span
class="inline-block h-2.5 w-2.5 rounded-sm bg-accent {{ opacity1 }}"
class="inline-block h-2.5 w-2.5 rounded-sm bg-accent {{ entry.opacity }}"
></span>
{{ label1 }}
{{ entry.label }}
</span>
{% endfor %}
</div>
</div>
{% endif %}
{% endmacro %}
{% macro map_with_legend_2(map_countries, map_max, label1, opacity1, label2, opacity2) %}
{% if !map_countries.is_empty() %}
<div
class="relative rounded-lg border bg-surface overflow-hidden flex items-center"
{% macro delete_button(entity_label, api_path, id) %}
<div class="rounded-lg border bg-surface p-5 flex items-center gap-2">
<button
type="button"
class="inline-flex items-center gap-2 rounded-md border px-4 py-2 text-sm font-medium text-error transition hover:bg-surface-alt"
data-on:click="confirm('Delete this {{ entity_label }}? This cannot be undone.') && @delete('{{ api_path }}/{{ id }}')"
>
<world-map
class="block w-full"
data-countries="{{ map_countries }}"
data-max="{{ map_max }}"
></world-map>
<div
class="absolute top-2 right-2 flex flex-col gap-1 text-2xs text-text-muted"
>
<span class="inline-flex items-center gap-1">
<span
class="inline-block h-2.5 w-2.5 rounded-sm bg-accent {{ opacity1 }}"
></span>
{{ label1 }}
</span>
<span class="inline-flex items-center gap-1">
<span
class="inline-block h-2.5 w-2.5 rounded-sm bg-accent {{ opacity2 }}"
></span>
{{ label2 }}
</span>
{{ icons::delete("h-4 w-4") }} Delete
</button>
</div>
</div>
{% endif %}
{% endmacro %}
{% macro map_with_legend_3(map_countries, map_max, label1, opacity1, label2, opacity2, label3, opacity3) %}
{% if !map_countries.is_empty() %}
<div
class="relative rounded-lg border bg-surface overflow-hidden flex items-center"
>
<world-map
class="block w-full"
data-countries="{{ map_countries }}"
data-max="{{ map_max }}"
></world-map>
<div
class="absolute top-2 right-2 flex flex-col gap-1 text-2xs text-text-muted"
>
<span class="inline-flex items-center gap-1">
<span
class="inline-block h-2.5 w-2.5 rounded-sm bg-accent {{ opacity1 }}"
></span>
{{ label1 }}
</span>
<span class="inline-flex items-center gap-1">
<span
class="inline-block h-2.5 w-2.5 rounded-sm bg-accent {{ opacity2 }}"
></span>
{{ label2 }}
</span>
<span class="inline-flex items-center gap-1">
<span
class="inline-block h-2.5 w-2.5 rounded-sm bg-accent {{ opacity3 }}"
></span>
{{ label3 }}
</span>
</div>
</div>
{% endif %}
{% endmacro %}
{% macro roaster_card(name, country, country_flag, city, homepage, roaster_slug) %}