Compare commits

..

3 Commits

Author SHA1 Message Date
Alphonse Paix
b1e315921e Load more button on Posts page
Some checks failed
Rust / Test (push) Has been cancelled
Rust / Rustfmt (push) Has been cancelled
Rust / Clippy (push) Has been cancelled
Rust / Code coverage (push) Has been cancelled
2025-09-23 18:24:12 +02:00
Alphonse Paix
5c5e3b0e4c post card fragment 2025-09-23 16:09:25 +02:00
Alphonse Paix
03ca17fdb5 favicon 2025-09-23 16:09:15 +02:00
8 changed files with 161 additions and 68 deletions

File diff suppressed because one or more lines are too long

BIN
assets/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 874 B

View File

@@ -2,31 +2,42 @@ use crate::{
domain::PostEntry,
routes::AppError,
startup::AppState,
templates::{PostTemplate, PostsTemplate},
templates::{PostListTemplate, PostTemplate, PostsTemplate},
};
use anyhow::Context;
use askama::Template;
use axum::{
extract::{Path, State},
extract::{Path, Query, State},
response::{Html, IntoResponse, Response},
};
use sqlx::PgPool;
use uuid::Uuid;
const NUM_PER_PAGE: i64 = 3;
pub async fn list_posts(
State(AppState {
connection_pool, ..
}): State<AppState>,
) -> Result<Response, AppError> {
let posts = get_latest_posts(&connection_pool, 5)
let count = get_posts_table_size(&connection_pool)
.await
.context("Could not fetch posts table size.")
.map_err(AppError::unexpected_page)?;
let next_page = if count > NUM_PER_PAGE { Some(2) } else { None };
let posts = get_posts(&connection_pool, NUM_PER_PAGE, None)
.await
.context("Could not fetch latest posts")
.map_err(AppError::unexpected_page)?;
let template = PostsTemplate { posts };
let template = PostsTemplate { posts, next_page };
Ok(Html(template.render().unwrap()).into_response())
}
async fn get_latest_posts(connection_pool: &PgPool, n: i64) -> Result<Vec<PostEntry>, sqlx::Error> {
async fn get_posts(
connection_pool: &PgPool,
n: i64,
offset: Option<i64>,
) -> Result<Vec<PostEntry>, sqlx::Error> {
sqlx::query_as!(
PostEntry,
r#"
@@ -35,20 +46,29 @@ async fn get_latest_posts(connection_pool: &PgPool, n: i64) -> Result<Vec<PostEn
LEFT JOIN users u ON p.author_id = u.user_id
ORDER BY p.published_at DESC
LIMIT $1
OFFSET $2
"#,
n
n,
offset
)
.fetch_all(connection_pool)
.await
}
async fn get_posts_table_size(connection_pool: &PgPool) -> Result<i64, sqlx::Error> {
sqlx::query!("SELECT count(*) FROM posts")
.fetch_one(connection_pool)
.await
.map(|r| r.count.unwrap())
}
pub async fn see_post(
State(AppState {
connection_pool, ..
}): State<AppState>,
Path(post_id): Path<Uuid>,
) -> Result<Response, AppError> {
let post = get_post(&connection_pool, post_id)
let post = get_post_data(&connection_pool, post_id)
.await
.context(format!("Failed to fetch post #{}", post_id))
.map_err(AppError::unexpected_page)?
@@ -58,7 +78,7 @@ pub async fn see_post(
Ok(Html(template.render().unwrap()).into_response())
}
async fn get_post(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry, sqlx::Error> {
async fn get_post_data(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry, sqlx::Error> {
sqlx::query_as!(
PostEntry,
r#"
@@ -72,3 +92,34 @@ async fn get_post(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEntry,
.fetch_one(connection_pool)
.await
}
#[derive(serde::Deserialize)]
pub struct LoadMoreParams {
page: i64,
}
pub async fn load_more(
State(AppState {
connection_pool, ..
}): State<AppState>,
Query(LoadMoreParams { page }): Query<LoadMoreParams>,
) -> Result<Response, AppError> {
let offset = (page - 1) * NUM_PER_PAGE;
let posts = get_posts(&connection_pool, NUM_PER_PAGE, Some(offset))
.await
.context("Could not fetch posts from database.")?;
let count = posts.len();
Ok(Html(
PostListTemplate {
posts,
next_page: if count as i64 == NUM_PER_PAGE {
Some(page + 1)
} else {
None
},
}
.render()
.unwrap(),
)
.into_response())
}

View File

@@ -1,12 +1,15 @@
use crate::{configuration::Settings, email_client::EmailClient, routes::require_auth, routes::*};
use axum::{
Router,
body::Bytes,
extract::MatchedPath,
http::Request,
middleware,
response::{IntoResponse, Response},
routing::{get, post},
};
use axum_server::tls_rustls::RustlsConfig;
use reqwest::{StatusCode, header};
use secrecy::ExposeSecret;
use sqlx::{PgPool, postgres::PgPoolOptions};
use std::{net::TcpListener, sync::Arc, time::Duration};
@@ -124,7 +127,6 @@ pub fn app(
.route("/logout", post(logout))
.layer(middleware::from_fn(require_auth));
Router::new()
.nest_service("/assets", ServeDir::new("assets"))
.route("/", get(home))
.route("/login", get(get_login).post(post_login))
.route("/health_check", get(health_check))
@@ -133,8 +135,11 @@ pub fn app(
.route("/unsubscribe", get(get_unsubscribe).post(post_unsubscribe))
.route("/unsubscribe/confirm", get(unsubscribe_confirm))
.route("/posts", get(list_posts))
.route("/posts/load_more", get(load_more))
.route("/posts/{post_id}", get(see_post))
.route("/favicon.ico", get(favicon))
.nest("/admin", admin_routes)
.nest_service("/assets", ServeDir::new("assets"))
.layer(
TraceLayer::new_for_http().make_span_with(|request: &Request<_>| {
let matched_path = request
@@ -156,3 +161,22 @@ pub fn app(
.fallback(not_found)
.with_state(app_state)
}
pub async fn favicon() -> Response {
match tokio::fs::read("assets/favicon.png").await {
Ok(content) => {
let bytes = Bytes::from(content);
let body = bytes.into();
Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "image/x-icon")
.header(header::CACHE_CONTROL, "public, max-age=86400")
.body(body)
.unwrap()
}
Err(e) => {
tracing::error!("Error while reading favicon.ico: {}", e);
StatusCode::NOT_FOUND.into_response()
}
}
}

View File

@@ -27,39 +27,47 @@ pub struct DashboardTemplate {
}
#[derive(Template)]
#[template(path = "../templates/home.html")]
#[template(path = "home.html")]
pub struct HomeTemplate;
#[derive(Template)]
#[template(path = "../templates/posts.html")]
#[template(path = "posts.html")]
pub struct PostsTemplate {
pub posts: Vec<PostEntry>,
pub next_page: Option<i64>,
}
#[derive(Template)]
#[template(path = "../templates/post.html")]
#[template(path = "posts.html", block = "posts")]
pub struct PostListTemplate {
pub posts: Vec<PostEntry>,
pub next_page: Option<i64>,
}
#[derive(Template)]
#[template(path = "post.html")]
pub struct PostTemplate {
pub post: PostEntry,
}
#[derive(Template)]
#[template(path = "../templates/confirm.html")]
#[template(path = "confirm.html")]
pub struct ConfirmTemplate;
#[derive(Template)]
#[template(path = "../templates/404.html")]
#[template(path = "404.html")]
pub struct NotFoundTemplate;
#[derive(Template)]
#[template(path = "../templates/unsubscribe_confirm.html")]
#[template(path = "unsubscribe_confirm.html")]
pub struct UnsubscribeConfirmTemplate;
#[derive(Template)]
#[template(path = "../templates/unsubscribe.html")]
#[template(path = "unsubscribe.html")]
pub struct UnsubscribeTemplate;
#[derive(Template)]
#[template(path = "../templates/email/new_post.html")]
#[template(path = "email/new_post.html")]
pub struct NewPostEmailTemplate<'a> {
pub base_url: &'a str,
pub post_title: &'a str,
@@ -68,7 +76,7 @@ pub struct NewPostEmailTemplate<'a> {
}
#[derive(Template)]
#[template(path = "../templates/email/standalone.html")]
#[template(path = "email/standalone.html")]
pub struct StandaloneEmailTemplate<'a> {
pub base_url: &'a str,
pub html_content: &'a str,

View File

@@ -0,0 +1,41 @@
<article class="bg-white rounded-lg shadow-md border border-gray-200 hover:shadow-lg transition-shadow duration-200">
<a href="/posts/{{ post.post_id }}"
class="block p-6 hover:bg-gray-50 transition-colors duration-200">
<div class="flex items-start justify-between">
<div class="flex-1 min-w-0">
<h2 class="text-xl font-semibold text-gray-900 mb-3 hover:text-blue-600 transition-colors">{{ post.title }}</h2>
<div class="flex items-center text-sm text-gray-500">
<div class="flex items-center">
<svg class="w-4 h-4 mr-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<time datetime="{{ post.published_at }}">
{{ post.formatted_date() }}
</time>
</div>
<span class="mx-2"></span>
<div class="flex items-center">
<svg class="w-4 h-4 mr-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
<span>{{ post.author.as_deref().unwrap_or("Unknown") }}</span>
</div>
</div>
</div>
<div class="flex-shrink-0 ml-4">
<svg class="w-5 h-5 text-gray-400 group-hover:text-blue-600 transition-colors"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</div>
</div>
</a>
</article>

View File

@@ -21,54 +21,23 @@
</div>
{% else %}
<div class="space-y-6">
{% block posts %}
{% for post in posts %}
<article class="bg-white rounded-lg shadow-md border border-gray-200 hover:shadow-lg transition-shadow duration-200">
<a href="/posts/{{ post.post_id }}"
class="block p-6 hover:bg-gray-50 transition-colors duration-200">
<div class="flex items-start justify-between">
<div class="flex-1 min-w-0">
<h2 class="text-xl font-semibold text-gray-900 mb-3 hover:text-blue-600 transition-colors">{{ post.title }}</h2>
<div class="flex items-center text-sm text-gray-500">
<div class="flex items-center">
<svg class="w-4 h-4 mr-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<time datetime="{{ post.published_at }}">
{{ post.formatted_date() }}
</time>
</div>
<span class="mx-2"></span>
<div class="flex items-center">
<svg class="w-4 h-4 mr-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
<span>{{ post.author.as_deref().unwrap_or("Unknown") }}</span>
</div>
</div>
</div>
<div class="flex-shrink-0 ml-4">
<svg class="w-5 h-5 text-gray-400 group-hover:text-blue-600 transition-colors"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</div>
</div>
</a>
</article>
{% include "post_card_fragment.html" %}
{% endfor %}
</div>
<div class="mt-8 text-center">
<button class="bg-blue-600 text-white hover:bg-blue-700 font-medium py-3 px-6 rounded-md transition-colors">
<div id="load-more" class="text-center">
{% if let Some(n) = next_page %}
<button hx-get="/posts/load_more?page={{ n }}"
hx-target="#load-more"
hx-swap="outerHTML"
class="text-center bg-blue-600 text-white hover:bg-blue-700 font-medium py-3 px-6 rounded-md transition-colors">
Load more
</button>
{% else %}
<p class="text-gray-600">No more posts. Check back later for more!</p>
{% endif %}
</div>
{% endblock %}
</div>
{% endif %}
</div>

View File

@@ -39,7 +39,7 @@
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<div class="text-sm text-amber-800">
<p>You will receive an email with an unsubscribe link.</p>
<p>You will receive an email with an confirmation link.</p>
</div>
</div>
</div>