Page abstraction
This commit is contained in:
@@ -15,8 +15,10 @@ assetserver = { workspace = true }
|
||||
|
||||
axum = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
utoipa = { workspace = true }
|
||||
maud = { workspace = true }
|
||||
markdown-it = { workspace = true }
|
||||
emojis = { workspace = true }
|
||||
strum = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
lru = { workspace = true }
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
use assetserver::Asset;
|
||||
use maud::{DOCTYPE, Markup, PreEscaped, Render, html};
|
||||
|
||||
use crate::{components::misc::FarLink, routes::assets::Styles_Main};
|
||||
|
||||
pub struct PageMetadata {
|
||||
pub title: String,
|
||||
pub author: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub image: Option<String>,
|
||||
}
|
||||
|
||||
impl Render for PageMetadata {
|
||||
fn render(&self) -> Markup {
|
||||
let empty = String::new();
|
||||
let title = &self.title;
|
||||
let author = &self.author.as_ref().unwrap_or(&empty);
|
||||
let description = &self.description.as_ref().unwrap_or(&empty);
|
||||
let image = &self.image.as_ref().unwrap_or(&empty);
|
||||
|
||||
html!(
|
||||
meta property="og:site_name" content=(title) {}
|
||||
meta name="title" content=(title) {}
|
||||
meta property="og:title" content=(title) {}
|
||||
meta property="twitter:title" content=(title) {}
|
||||
|
||||
meta name="author" content=(author) {}
|
||||
|
||||
meta name="description" content=(description) {}
|
||||
meta property="og:description" content=(description) {}
|
||||
meta property="twitter:description" content=(description) {}
|
||||
|
||||
meta content=(image) property="og:image" {}
|
||||
link rel="shortcut icon" href=(image) type="image/x-icon" {}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BasePage<T: Render>(pub PageMetadata, pub T);
|
||||
|
||||
impl<T: Render> Render for BasePage<T> {
|
||||
fn render(&self) -> Markup {
|
||||
let meta = &self.0;
|
||||
|
||||
html! {
|
||||
(DOCTYPE)
|
||||
html {
|
||||
head {
|
||||
meta charset="UTF" {}
|
||||
meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" {}
|
||||
meta content="text/html; charset=UTF-8" http-equiv="content-type" {}
|
||||
meta property="og:type" content="website" {}
|
||||
|
||||
link rel="stylesheet" href=(Styles_Main::URL) {}
|
||||
|
||||
|
||||
(meta)
|
||||
title { (PreEscaped(meta.title.clone())) }
|
||||
}
|
||||
|
||||
body {
|
||||
div class="wrapper" {
|
||||
main { (self.1) }
|
||||
|
||||
footer {
|
||||
hr class = "footline" {}
|
||||
div class = "footContainer" {
|
||||
p {
|
||||
"This site was built by hand using "
|
||||
(FarLink("https://rust-lang.org", "Rust"))
|
||||
", "
|
||||
(FarLink("https://maud.lambda.xyz", "Maud"))
|
||||
", "
|
||||
(FarLink("https://github.com/connorskees/grass", "Grass"))
|
||||
", and "
|
||||
(FarLink("https://docs.rs/axum/latest/axum", "Axum"))
|
||||
"."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,9 @@ impl<T: Render> Render for FarLink<'_, T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Backlinks(
|
||||
pub &'static [(&'static str, &'static str)],
|
||||
pub &'static str,
|
||||
);
|
||||
pub struct Backlinks<'a>(pub &'a [(&'a str, &'a str)], pub &'a str);
|
||||
|
||||
impl Render for Backlinks {
|
||||
impl Render for Backlinks<'_> {
|
||||
fn render(&self) -> Markup {
|
||||
html! {
|
||||
div {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
pub mod base;
|
||||
pub mod fa;
|
||||
pub mod mangle;
|
||||
pub mod md;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use axum::Router;
|
||||
use libservice::ToService;
|
||||
use utoipa::OpenApi;
|
||||
|
||||
mod components;
|
||||
mod page;
|
||||
mod pages;
|
||||
mod routes;
|
||||
|
||||
pub struct WebpageService {}
|
||||
@@ -20,11 +21,6 @@ impl ToService for WebpageService {
|
||||
Some(routes::router())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn make_openapi(&self) -> utoipa::openapi::OpenApi {
|
||||
routes::Api::openapi()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn service_name(&self) -> Option<String> {
|
||||
Some("webpage".to_owned())
|
||||
|
||||
216
crates/service/service-webpage/src/page/mod.rs
Normal file
216
crates/service/service-webpage/src/page/mod.rs
Normal file
@@ -0,0 +1,216 @@
|
||||
//
|
||||
// MARK: metadata
|
||||
//
|
||||
|
||||
use axum::{
|
||||
Router,
|
||||
extract::{ConnectInfo, Path, State},
|
||||
http::{HeaderValue, StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use libservice::ServiceConnectInfo;
|
||||
use lru::LruCache;
|
||||
use maud::{Markup, Render, html};
|
||||
use parking_lot::Mutex;
|
||||
use std::{collections::HashMap, num::NonZero, sync::Arc, time::Duration};
|
||||
use tracing::{debug, trace};
|
||||
|
||||
use crate::components::{md::Markdown, misc::Backlinks};
|
||||
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||
pub struct PageMetadata {
|
||||
pub title: String,
|
||||
pub author: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub image: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for PageMetadata {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
title: "Untitled page".into(),
|
||||
author: None,
|
||||
description: None,
|
||||
image: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for PageMetadata {
|
||||
fn render(&self) -> Markup {
|
||||
let empty = String::new();
|
||||
let title = &self.title;
|
||||
let author = &self.author.as_ref().unwrap_or(&empty);
|
||||
let description = &self.description.as_ref().unwrap_or(&empty);
|
||||
let image = &self.image.as_ref().unwrap_or(&empty);
|
||||
|
||||
html !(
|
||||
meta property="og:site_name" content=(title) {}
|
||||
meta name="title" content=(title) {}
|
||||
meta property="og:title" content=(title) {}
|
||||
meta property="twitter:title" content=(title) {}
|
||||
|
||||
meta name="author" content=(author) {}
|
||||
|
||||
meta name="description" content=(description) {}
|
||||
meta property="og:description" content=(description) {}
|
||||
meta property="twitter:description" content=(description) {}
|
||||
|
||||
meta content=(image) property="og:image" {}
|
||||
link rel="shortcut icon" href=(image) type="image/x-icon" {}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: page
|
||||
//
|
||||
|
||||
// Some HTML
|
||||
pub struct Page {
|
||||
pub meta: PageMetadata,
|
||||
|
||||
/// How long this page's html may be cached.
|
||||
///
|
||||
/// If `None`, this page is always rendered from scratch.
|
||||
pub html_ttl: Option<Duration>,
|
||||
|
||||
/// A function that generates this page's html.
|
||||
///
|
||||
/// This should return the contents of this page's <body> tag,
|
||||
/// or the contents of a wrapper element (defined in the page server struct).
|
||||
///
|
||||
/// This closure must never return `<html>` or `<head>`.
|
||||
pub generate_html: Box<dyn Send + Sync + Fn(&Self) -> Markup>,
|
||||
}
|
||||
|
||||
impl Default for Page {
|
||||
fn default() -> Self {
|
||||
Page {
|
||||
meta: Default::default(),
|
||||
html_ttl: Some(Duration::from_secs(60 * 24 * 30)),
|
||||
//css_ttl: Duration::from_secs(60 * 24 * 30),
|
||||
//generate_css: None,
|
||||
generate_html: Box::new(|_| html!()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub fn generate_html(&self) -> Markup {
|
||||
(self.generate_html)(self)
|
||||
}
|
||||
|
||||
pub fn from_markdown(meta: PageMetadata, md: impl Into<String>) -> Self {
|
||||
let md: String = md.into();
|
||||
|
||||
// TODO: define metadata and backlinks in markdown
|
||||
Page {
|
||||
meta,
|
||||
generate_html: Box::new(move |page| {
|
||||
html! {
|
||||
(Backlinks(&[("/", "home")], &page.meta.title))
|
||||
(Markdown(&md))
|
||||
}
|
||||
}),
|
||||
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: server
|
||||
//
|
||||
|
||||
pub struct PageServer {
|
||||
/// Map of `{ route: page }`
|
||||
pages: HashMap<String, Page>,
|
||||
|
||||
/// Map of `{ route: (page data, expire time) }`
|
||||
///
|
||||
/// We use an LruCache for bounded memory usage.
|
||||
html_cache: Mutex<LruCache<String, (String, DateTime<Utc>)>>,
|
||||
|
||||
/// Called whenever we need to render a page.
|
||||
/// - this method should call `page.generate_html()`,
|
||||
/// - wrap the result in `<html><body>`,
|
||||
/// - and add `<head>`
|
||||
/// ```
|
||||
render_page: Box<dyn Send + Sync + Fn(&Page) -> Markup>,
|
||||
}
|
||||
|
||||
impl PageServer {
|
||||
pub fn new(page_wrapper: Box<dyn Send + Sync + Fn(&Page) -> Markup>) -> Self {
|
||||
#[expect(clippy::unwrap_used)]
|
||||
let cache_size = LruCache::new(NonZero::new(128).unwrap());
|
||||
|
||||
Self {
|
||||
pages: HashMap::new(),
|
||||
html_cache: Mutex::new(cache_size),
|
||||
render_page: Box::new(page_wrapper),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_page(mut self, route: impl Into<String>, page: Page) -> Self {
|
||||
#[expect(clippy::expect_used)]
|
||||
let route = route
|
||||
.into()
|
||||
.strip_prefix("/")
|
||||
.expect("page route must start with /")
|
||||
.to_owned();
|
||||
|
||||
self.pages.insert(route, page);
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
async fn handler(
|
||||
Path(path): Path<String>,
|
||||
State(state): State<Arc<Self>>,
|
||||
ConnectInfo(addr): ConnectInfo<ServiceConnectInfo>,
|
||||
) -> Response {
|
||||
trace!("Serving {path} to {}", addr.addr);
|
||||
|
||||
let page = match state.pages.get(&path) {
|
||||
Some(x) => x,
|
||||
|
||||
// TODO: 404 page
|
||||
None => return (StatusCode::NOT_FOUND, "page doesn't exist").into_response(),
|
||||
};
|
||||
|
||||
let now = Utc::now();
|
||||
let headers = [(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/html; charset=utf-8"),
|
||||
)];
|
||||
|
||||
if let Some((html, expires)) = state.html_cache.lock().get(&path)
|
||||
&& *expires > now
|
||||
{
|
||||
// TODO: no clone?
|
||||
return (headers, html.clone()).into_response();
|
||||
};
|
||||
|
||||
debug!("Rendering {path}");
|
||||
let html = (state.render_page)(page).0;
|
||||
|
||||
if let Some(ttl) = page.html_ttl {
|
||||
state.html_cache.lock().put(path, (html.clone(), now + ttl));
|
||||
}
|
||||
|
||||
return (headers, html.clone()).into_response();
|
||||
}
|
||||
|
||||
pub fn into_router(self) -> Router<()> {
|
||||
Router::new()
|
||||
.route(
|
||||
"/",
|
||||
get(|state, conn| async { Self::handler(Path(String::new()), state, conn).await }),
|
||||
)
|
||||
.route("/{*path}", get(Self::handler))
|
||||
.with_state(Arc::new(self))
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,30 @@
|
||||
use assetserver::Asset;
|
||||
use maud::{Markup, html};
|
||||
use maud::html;
|
||||
|
||||
use crate::{
|
||||
components::{
|
||||
base::{BasePage, PageMetadata},
|
||||
md::Markdown,
|
||||
misc::Backlinks,
|
||||
},
|
||||
components::{md::Markdown, misc::Backlinks},
|
||||
page::{Page, PageMetadata},
|
||||
routes::assets::{Image_Betalupi, Image_Icon},
|
||||
};
|
||||
|
||||
pub async fn betalupi() -> Markup {
|
||||
let meta = PageMetadata {
|
||||
title: "What's a \"betalupi?\"".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: None,
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
};
|
||||
pub fn page() -> Page {
|
||||
Page {
|
||||
meta: PageMetadata {
|
||||
title: "What's a \"betalupi?\"".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: None,
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
},
|
||||
|
||||
html! {
|
||||
(BasePage(
|
||||
meta,
|
||||
html!(
|
||||
generate_html: Box::new(|_page| {
|
||||
html! {
|
||||
(Backlinks(&[("/", "home")], "whats-a-betalupi"))
|
||||
|
||||
(Markdown(MD))
|
||||
|
||||
img alt="betalupi map" class="image" src=(Image_Betalupi::URL) {}
|
||||
)
|
||||
))
|
||||
}
|
||||
}),
|
||||
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +1,29 @@
|
||||
use assetserver::Asset;
|
||||
use maud::{Markup, html};
|
||||
use maud::html;
|
||||
|
||||
use crate::{
|
||||
components::{
|
||||
base::{BasePage, PageMetadata},
|
||||
md::Markdown,
|
||||
misc::Backlinks,
|
||||
},
|
||||
components::{md::Markdown, misc::Backlinks},
|
||||
page::{Page, PageMetadata},
|
||||
routes::assets::Image_Icon,
|
||||
};
|
||||
|
||||
pub async fn handouts() -> Markup {
|
||||
let meta = PageMetadata {
|
||||
title: "Mark's Handouts".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: None,
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
};
|
||||
pub fn page() -> Page {
|
||||
Page {
|
||||
meta: PageMetadata {
|
||||
title: "Mark's Handouts".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: None,
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
},
|
||||
|
||||
html! {
|
||||
(BasePage(
|
||||
meta,
|
||||
html!(
|
||||
generate_html: Box::new(|_page| {
|
||||
html! {
|
||||
(Backlinks(&[("/", "home")], "handouts"))
|
||||
|
||||
(Markdown(MD_A))
|
||||
)
|
||||
))
|
||||
}
|
||||
}),
|
||||
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,29 +1,28 @@
|
||||
use assetserver::Asset;
|
||||
use maud::{Markup, html};
|
||||
use maud::html;
|
||||
|
||||
use crate::{
|
||||
components::{
|
||||
base::{BasePage, PageMetadata},
|
||||
fa::FAIcon,
|
||||
mangle::{MangledBetaEmail, MangledGoogleEmail},
|
||||
md::Markdown,
|
||||
misc::FarLink,
|
||||
},
|
||||
page::{Page, PageMetadata},
|
||||
routes::assets::{Image_Cover, Image_Icon},
|
||||
};
|
||||
|
||||
pub async fn index() -> Markup {
|
||||
let meta = PageMetadata {
|
||||
title: "Betalupi: About".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: Some("Description".into()),
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
};
|
||||
pub fn page() -> Page {
|
||||
Page {
|
||||
meta: PageMetadata {
|
||||
title: "Betalupi: About".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: Some("Description".into()),
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
},
|
||||
|
||||
html! {
|
||||
(BasePage(
|
||||
meta,
|
||||
html!(
|
||||
generate_html: Box::new(move |_page| {
|
||||
html! {
|
||||
h2 id="about" { "About" }
|
||||
|
||||
div {
|
||||
@@ -68,9 +67,9 @@ pub async fn index() -> Markup {
|
||||
br style="clear:both;" {}
|
||||
}
|
||||
|
||||
|
||||
(Markdown(include_str!("index.md")))
|
||||
)
|
||||
))
|
||||
}
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
35
crates/service/service-webpage/src/pages/links.rs
Normal file
35
crates/service/service-webpage/src/pages/links.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use assetserver::Asset;
|
||||
use maud::html;
|
||||
|
||||
use crate::{
|
||||
components::{md::Markdown, misc::Backlinks},
|
||||
page::{Page, PageMetadata},
|
||||
routes::assets::Image_Icon,
|
||||
};
|
||||
|
||||
pub fn page() -> Page {
|
||||
Page {
|
||||
meta: PageMetadata {
|
||||
title: "Links".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: None,
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
},
|
||||
|
||||
generate_html: Box::new(|_page| {
|
||||
html! {
|
||||
(Backlinks(&[("/", "home")], "links"))
|
||||
(Markdown(include_str!("links.md")))
|
||||
}
|
||||
}),
|
||||
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Dead links:
|
||||
|
||||
https://www.commitstrip.com/en/
|
||||
http://www.3dprintmath.com/
|
||||
*/
|
||||
4
crates/service/service-webpage/src/pages/mod.rs
Normal file
4
crates/service/service-webpage/src/pages/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
pub mod betalupi;
|
||||
pub mod handouts;
|
||||
pub mod index;
|
||||
pub mod links;
|
||||
@@ -1,37 +0,0 @@
|
||||
use assetserver::Asset;
|
||||
use maud::{Markup, html};
|
||||
|
||||
use crate::{
|
||||
components::{
|
||||
base::{BasePage, PageMetadata},
|
||||
md::Markdown,
|
||||
misc::Backlinks,
|
||||
},
|
||||
routes::assets::Image_Icon,
|
||||
};
|
||||
|
||||
pub async fn links() -> Markup {
|
||||
let meta = PageMetadata {
|
||||
title: "Links".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: None,
|
||||
image: Some(Image_Icon::URL.into()),
|
||||
};
|
||||
|
||||
html! {
|
||||
(BasePage(
|
||||
meta,
|
||||
html!(
|
||||
(Backlinks(&[("/", "home")], "links"))
|
||||
(Markdown(include_str!("links.md")))
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Dead links:
|
||||
|
||||
https://www.commitstrip.com/en/
|
||||
http://www.3dprintmath.com/
|
||||
*/
|
||||
@@ -1,26 +1,62 @@
|
||||
use assetserver::Asset;
|
||||
use axum::Router;
|
||||
use axum::routing::get;
|
||||
use maud::{DOCTYPE, PreEscaped, html};
|
||||
use tracing::info;
|
||||
use utoipa::OpenApi;
|
||||
|
||||
use crate::{components::misc::FarLink, page::PageServer, pages, routes::assets::Styles_Main};
|
||||
|
||||
pub mod assets;
|
||||
mod betalupi;
|
||||
mod handouts;
|
||||
mod index;
|
||||
mod links;
|
||||
|
||||
#[derive(OpenApi)]
|
||||
#[openapi(tags(), paths(), components(schemas()))]
|
||||
pub(super) struct Api;
|
||||
|
||||
pub(super) fn router() -> Router<()> {
|
||||
let (asset_prefix, asset_router) = assets::asset_router();
|
||||
info!("Serving assets at {asset_prefix}");
|
||||
|
||||
Router::new()
|
||||
.route("/", get(index::index))
|
||||
.route("/whats-a-betalupi", get(betalupi::betalupi))
|
||||
.route("/links", get(links::links))
|
||||
.route("/handouts", get(handouts::handouts))
|
||||
.nest(asset_prefix, asset_router)
|
||||
let server = PageServer::new(Box::new(|page| {
|
||||
html! {
|
||||
(DOCTYPE)
|
||||
html {
|
||||
head {
|
||||
meta charset="UTF" {}
|
||||
meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" {}
|
||||
meta content="text/html; charset=UTF-8" http-equiv="content-type" {}
|
||||
meta property="og:type" content="website" {}
|
||||
|
||||
link rel="stylesheet" href=(Styles_Main::URL) {}
|
||||
|
||||
(&page.meta)
|
||||
title { (PreEscaped(page.meta.title.clone())) }
|
||||
}
|
||||
|
||||
body {
|
||||
div class="wrapper" {
|
||||
main { ( page.generate_html() ) }
|
||||
|
||||
footer {
|
||||
hr class = "footline" {}
|
||||
div class = "footContainer" {
|
||||
p {
|
||||
"This site was built by hand using "
|
||||
(FarLink("https://rust-lang.org", "Rust"))
|
||||
", "
|
||||
(FarLink("https://maud.lambda.xyz", "Maud"))
|
||||
", "
|
||||
(FarLink("https://github.com/connorskees/grass", "Grass"))
|
||||
", and "
|
||||
(FarLink("https://docs.rs/axum/latest/axum", "Axum"))
|
||||
"."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}))
|
||||
.add_page("/", pages::index::page())
|
||||
.add_page("/links", pages::links::page())
|
||||
.add_page("/whats-a-betalupi", pages::betalupi::page())
|
||||
.add_page("/handouts", pages::handouts::page())
|
||||
.into_router();
|
||||
|
||||
Router::new().merge(server).nest(asset_prefix, asset_router)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user