Render handout page on server
All checks were successful
CI / Check typos (push) Successful in 22s
CI / Check links (push) Successful in 23s
CI / Clippy (push) Successful in 1m5s
CI / Build and test (push) Successful in 1m12s
CI / Build container (push) Successful in 1m37s
CI / Deploy on waypoint (push) Successful in 45s
All checks were successful
CI / Check typos (push) Successful in 22s
CI / Check links (push) Successful in 23s
CI / Clippy (push) Successful in 1m5s
CI / Build and test (push) Successful in 1m12s
CI / Build container (push) Successful in 1m37s
CI / Deploy on waypoint (push) Successful in 45s
This commit is contained in:
@@ -68,6 +68,8 @@ impl From<LoggingConfig> for EnvFilter {
|
||||
format!("h2={}", conf.silence),
|
||||
format!("rustls={}", conf.silence),
|
||||
format!("tower={}", conf.silence),
|
||||
format!("reqwest={}", conf.silence),
|
||||
format!("axum={}", conf.silence),
|
||||
//
|
||||
// Libs
|
||||
//
|
||||
|
||||
@@ -21,7 +21,8 @@ emojis = { workspace = true }
|
||||
strum = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
lru = { workspace = true }
|
||||
lazy_static = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Handout list pages
|
||||
// works with "{{ handout() }}" shortcode.
|
||||
|
||||
.handout-li-links {
|
||||
color: var(--grey);
|
||||
}
|
||||
@@ -39,10 +36,6 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
.handout-star {
|
||||
color: var(--yellow);
|
||||
}
|
||||
|
||||
// Email obfuscation
|
||||
// Works with "{{ email_*() }}" shortcodes.
|
||||
.eobf {
|
||||
|
||||
@@ -9,14 +9,19 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use libservice::ServiceConnectInfo;
|
||||
use lru::LruCache;
|
||||
use markdown_it::Node;
|
||||
use maud::{Markup, PreEscaped, Render, html};
|
||||
use parking_lot::Mutex;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use serde::Deserialize;
|
||||
use std::{collections::HashMap, num::NonZero, sync::Arc, time::Duration};
|
||||
use tracing::{debug, trace};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tracing::{trace, warn};
|
||||
|
||||
use crate::components::{
|
||||
md::{FrontMatter, Markdown},
|
||||
@@ -70,6 +75,21 @@ impl Render for PageMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
impl PageMetadata {
|
||||
/// Try to read page metadata from a markdown file's frontmatter.
|
||||
/// - returns `none` if there is no frontmatter
|
||||
/// - returns an error if we fail to parse frontmatter
|
||||
pub fn from_markdown_frontmatter(
|
||||
root_node: &Node,
|
||||
) -> Result<Option<PageMetadata>, serde_yaml::Error> {
|
||||
root_node
|
||||
.children.first()
|
||||
.and_then(|x| x.cast::<FrontMatter>())
|
||||
.map(|x| serde_yaml::from_str::<PageMetadata>(&x.content))
|
||||
.map_or(Ok(None), |v| v.map(Some))
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: page
|
||||
//
|
||||
@@ -79,9 +99,10 @@ pub struct Page {
|
||||
pub meta: PageMetadata,
|
||||
|
||||
/// How long this page's html may be cached.
|
||||
/// This controls the maximum age of a page shown to the user.
|
||||
///
|
||||
/// If `None`, this page is always rendered from scratch.
|
||||
pub html_ttl: Option<Duration>,
|
||||
pub html_ttl: Option<TimeDelta>,
|
||||
|
||||
/// A function that generates this page's html.
|
||||
///
|
||||
@@ -89,41 +110,40 @@ pub struct Page {
|
||||
/// 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>,
|
||||
pub generate_html: Box<
|
||||
dyn Send
|
||||
+ Sync
|
||||
+ for<'a> Fn(&'a Page) -> Pin<Box<dyn Future<Output = Markup> + 'a + Send + Sync>>,
|
||||
>,
|
||||
}
|
||||
|
||||
impl Default for Page {
|
||||
fn default() -> Self {
|
||||
Page {
|
||||
meta: Default::default(),
|
||||
html_ttl: Some(Duration::from_secs(60 * 24 * 30)),
|
||||
html_ttl: Some(TimeDelta::seconds(60 * 24 * 30)),
|
||||
//css_ttl: Duration::from_secs(60 * 24 * 30),
|
||||
//generate_css: None,
|
||||
generate_html: Box::new(|_| html!()),
|
||||
generate_html: Box::new(|_| Box::pin(async { html!() })),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub fn generate_html(&self) -> Markup {
|
||||
(self.generate_html)(self)
|
||||
pub async fn generate_html(&self) -> Markup {
|
||||
(self.generate_html)(self).await
|
||||
}
|
||||
|
||||
pub fn from_markdown(md: impl Into<String>, default_image: Option<String>) -> Self {
|
||||
let md: String = md.into();
|
||||
let md = Markdown::parse(&md);
|
||||
|
||||
let mut meta = md
|
||||
.children
|
||||
.get(0)
|
||||
.map(|x| x.cast::<FrontMatter>())
|
||||
.flatten()
|
||||
.map(|x| serde_yaml::from_str::<PageMetadata>(&x.content))
|
||||
.unwrap_or(Ok(Default::default()))
|
||||
.unwrap_or(PageMetadata {
|
||||
let mut meta = PageMetadata::from_markdown_frontmatter(&md)
|
||||
.unwrap_or(Some(PageMetadata {
|
||||
title: "Invalid frontmatter!".into(),
|
||||
..Default::default()
|
||||
});
|
||||
}))
|
||||
.unwrap_or_default();
|
||||
|
||||
if meta.image.is_none() {
|
||||
meta.image = default_image
|
||||
@@ -134,13 +154,16 @@ impl Page {
|
||||
Page {
|
||||
meta,
|
||||
generate_html: Box::new(move |page| {
|
||||
html! {
|
||||
@if let Some(slug) = &page.meta.slug {
|
||||
(Backlinks(&[("/", "home")], slug))
|
||||
}
|
||||
let html = html.clone();
|
||||
Box::pin(async move {
|
||||
html! {
|
||||
@if let Some(slug) = &page.meta.slug {
|
||||
(Backlinks(&[("/", "home")], slug))
|
||||
}
|
||||
|
||||
(html)
|
||||
}
|
||||
(html)
|
||||
}
|
||||
})
|
||||
}),
|
||||
|
||||
..Default::default()
|
||||
@@ -153,35 +176,50 @@ impl Page {
|
||||
//
|
||||
|
||||
pub struct PageServer {
|
||||
/// If true, expired pages will be rerendered before being sent to the user.
|
||||
/// If false, requests never trigger rerenders. We rely on the rerender task.
|
||||
///
|
||||
/// If true, we deliver fresher pages but delay responses.
|
||||
/// TODO: replace this with a smarter rendering strategy?
|
||||
never_rerender_on_request: bool,
|
||||
|
||||
/// Map of `{ route: page }`
|
||||
pages: HashMap<String, Page>,
|
||||
pages: Arc<Mutex<HashMap<String, Arc<Page>>>>,
|
||||
|
||||
/// Map of `{ route: (page data, expire time) }`
|
||||
///
|
||||
/// We use an LruCache for bounded memory usage.
|
||||
html_cache: Mutex<LruCache<String, (String, DateTime<Utc>)>>,
|
||||
html_cache: RwLock<HashMap<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>,
|
||||
render_page: Box<
|
||||
dyn Send
|
||||
+ Sync
|
||||
+ for<'a> Fn(&'a Page) -> Pin<Box<dyn Future<Output = Markup> + 'a + Send + Sync>>,
|
||||
>,
|
||||
}
|
||||
|
||||
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 new(
|
||||
render_page: Box<
|
||||
dyn Send
|
||||
+ Sync
|
||||
+ for<'a> Fn(&'a Page) -> Pin<Box<dyn Future<Output = Markup> + 'a + Send + Sync>>,
|
||||
>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
pages: Arc::new(Mutex::new(HashMap::new())),
|
||||
html_cache: RwLock::new(HashMap::new()),
|
||||
render_page,
|
||||
never_rerender_on_request: true,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_page(mut self, route: impl Into<String>, page: Page) -> Self {
|
||||
pub fn add_page(&self, route: impl Into<String>, page: Page) -> &Self {
|
||||
#[expect(clippy::expect_used)]
|
||||
let route = route
|
||||
.into()
|
||||
@@ -189,24 +227,79 @@ impl PageServer {
|
||||
.expect("page route must start with /")
|
||||
.to_owned();
|
||||
|
||||
self.pages.insert(route, page);
|
||||
|
||||
self.pages.lock().insert(route, Arc::new(page));
|
||||
self
|
||||
}
|
||||
|
||||
/// Re-render the page at `route`, regardless of cache state.
|
||||
/// Does nothing if there is no page at `route`.
|
||||
///
|
||||
/// Returns the rendered page's content.
|
||||
async fn render_page(&self, reason: &'static str, route: &str) -> Option<String> {
|
||||
let now = Utc::now();
|
||||
let start = Instant::now();
|
||||
trace!(message = "Rendering page", route, reason);
|
||||
|
||||
let page = match self.pages.lock().get(route) {
|
||||
Some(x) => x.clone(),
|
||||
None => {
|
||||
warn!(message = "Not rerendering, no such route", route, reason);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let html = (self.render_page)(&page).await.0;
|
||||
|
||||
if let Some(ttl) = page.html_ttl {
|
||||
self.html_cache
|
||||
.write()
|
||||
.insert(route.to_owned(), (html.clone(), now + ttl));
|
||||
}
|
||||
|
||||
let elapsed = start.elapsed().as_millis();
|
||||
trace!(message = "Rendered page", route, reason, time_ms = elapsed);
|
||||
return Some(html);
|
||||
}
|
||||
|
||||
// Rerender considerations:
|
||||
// - rerendering often in the background is wasteful. Maybe we should fall asleep?
|
||||
// - rerendering on request is slow
|
||||
// - rerendering in the background after a request could be a good idea. Maybe implement?
|
||||
//
|
||||
// - cached pages only make sense for static assets.
|
||||
// - user pages can't be pre-rendered!
|
||||
pub async fn start_rerender_task(self: Arc<Self>, interval: Duration) {
|
||||
loop {
|
||||
tokio::time::sleep(interval).await;
|
||||
|
||||
let now = Utc::now();
|
||||
let pages = self
|
||||
.pages
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(_, v)| v.html_ttl.is_some())
|
||||
.map(|(k, _)| k.clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for route in pages {
|
||||
let needs_render = match self.html_cache.read().get(&route) {
|
||||
Some(x) => x.1 < now, // Expired
|
||||
None => true, // Never rendered
|
||||
};
|
||||
|
||||
if needs_render {
|
||||
self.render_page("rerender_task", &route).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handler(
|
||||
Path(path): Path<String>,
|
||||
Path(route): 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(),
|
||||
};
|
||||
trace!("Serving {route} to {}", addr.addr);
|
||||
|
||||
let now = Utc::now();
|
||||
let headers = [(
|
||||
@@ -214,30 +307,28 @@ impl PageServer {
|
||||
HeaderValue::from_static("text/html; charset=utf-8"),
|
||||
)];
|
||||
|
||||
if let Some((html, expires)) = state.html_cache.lock().get(&path)
|
||||
&& *expires > now
|
||||
if let Some((html, expires)) = state.html_cache.read().get(&route)
|
||||
&& (*expires > now || state.never_rerender_on_request)
|
||||
{
|
||||
// TODO: no clone?
|
||||
return (headers, html.clone()).into_response();
|
||||
};
|
||||
|
||||
debug!("Rendering {path}");
|
||||
let html = (state.render_page)(page).0;
|
||||
let html = match state.render_page("request", &route).await {
|
||||
Some(x) => x.clone(),
|
||||
None => return (StatusCode::NOT_FOUND, "page doesn't exist").into_response(),
|
||||
};
|
||||
|
||||
if let Some(ttl) = page.html_ttl {
|
||||
state.html_cache.lock().put(path, (html.clone(), now + ttl));
|
||||
}
|
||||
|
||||
return (headers, html.clone()).into_response();
|
||||
return (headers, html).into_response();
|
||||
}
|
||||
|
||||
pub fn into_router(self) -> Router<()> {
|
||||
pub fn into_router(self: Arc<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))
|
||||
.with_state(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,200 +33,10 @@ are written with this in mind.\
|
||||
I do not expect the average student to finish all problems during this two-hour session.
|
||||
If the class finishes early, the lesson is either too short or too easy.
|
||||
|
||||
The sources for all these handouts are available [here](https://git.betalupi.com/mark/handouts).\
|
||||
Some are written in LaTeX, some are in [Typst](https://typst.app). \
|
||||
The latter is vastly superior.
|
||||
|
||||
<br></br>
|
||||
<hr></hr>
|
||||
<br></br>
|
||||
|
||||
## Warm-Ups
|
||||
|
||||
Students never show up on time. Some come early, some come late. Warm-ups
|
||||
are my solution to this problem: we hand these out as students walk in,
|
||||
giving them something to do until we can start the lesson.
|
||||
|
||||
|
||||
<ul id="handout-ul-Warm-Ups" class="handout-ul"></ul>
|
||||
|
||||
<script>
|
||||
fetch("https://git.betalupi.com/api/packages/Mark/generic/ormc-handouts/latest/index.json")
|
||||
.then(res => res.json())
|
||||
.then(out => {
|
||||
out = out.sort((a, b) => (
|
||||
a["title"].toLowerCase() < b["title"].toLowerCase()
|
||||
));
|
||||
|
||||
out.forEach(element => {
|
||||
if (element["group"] != "Warm-Ups") { return }
|
||||
|
||||
// Handout title
|
||||
const title = document.createElement("span");
|
||||
const title_a = document.createElement("strong");
|
||||
title_a.appendChild(document.createTextNode(element["title"] + " "));
|
||||
title.appendChild(title_a)
|
||||
title.classList.add("handout-li-title");
|
||||
|
||||
// Handout title
|
||||
const desc = document.createElement("span");
|
||||
desc.appendChild(document.createTextNode(element["description"]));
|
||||
desc.classList.add("handout-li-desc");
|
||||
|
||||
const handout_link = element["handout"];
|
||||
const solutions_link = element["solutions"];
|
||||
|
||||
const links = document.createElement("span");
|
||||
links.classList.add("handout-li-links");
|
||||
const h = document.createElement("a");
|
||||
h.appendChild(document.createTextNode("handout"))
|
||||
h.href = handout_link;
|
||||
if (solutions_link === null) {
|
||||
links.appendChild(document.createTextNode("[ "));
|
||||
links.appendChild(h);
|
||||
links.appendChild(document.createTextNode(" ]"));
|
||||
} else {
|
||||
var s = document.createElement("a");
|
||||
s.appendChild(document.createTextNode("solutions"))
|
||||
s.href = solutions_link;
|
||||
links.appendChild(document.createTextNode("[ "));
|
||||
links.appendChild(h);
|
||||
links.appendChild(document.createTextNode(" | "));
|
||||
links.appendChild(s);
|
||||
links.appendChild(document.createTextNode(" ]"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Add to main list
|
||||
const item = document.createElement("li");
|
||||
item.appendChild(title)
|
||||
item.appendChild(links);
|
||||
//item.appendChild(desc)
|
||||
const list = document.getElementById("handout-ul-Warm-Ups");
|
||||
list.insertBefore(item, list.children[0]);
|
||||
})}
|
||||
)
|
||||
.catch(err => {
|
||||
// Print fallback link if we failed to load json index
|
||||
console.log(err)
|
||||
|
||||
const title = document.createElement("span");
|
||||
const title_a = document.createElement("strong");
|
||||
title_a.appendChild(document.createTextNode("Error: "));
|
||||
title.appendChild(title_a)
|
||||
title.appendChild(document.createTextNode("failed to load handouts, something broke."))
|
||||
title.classList.add("handout-li-title");
|
||||
|
||||
const fallback = "https://git.betalupi.com/Mark/-/packages/generic/ormc-handouts/latest";
|
||||
const link = document.createElement("a");
|
||||
link.href = fallback
|
||||
link.appendChild(document.createTextNode("ormc-handouts"));
|
||||
|
||||
const item_a = document.createElement("li");
|
||||
item_a.appendChild(title)
|
||||
const item_b = document.createElement("li");
|
||||
item_b.appendChild(document.createTextNode("Fallback link: "))
|
||||
item_b.appendChild(link)
|
||||
|
||||
const list = document.getElementById("handout-ul-Warm-Ups");
|
||||
list.insertBefore(item_b, list.children[0]);
|
||||
list.insertBefore(item_a, list.children[0]);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
<br></br>
|
||||
|
||||
|
||||
## Advanced
|
||||
|
||||
The highest level of the ORMC, and the group I spend most of my time with.
|
||||
Students in ORMC Advanced are in high school, which means
|
||||
they're ~14-18 years old.
|
||||
|
||||
|
||||
<ul id="handout-ul-Advanced" class="handout-ul"></ul>
|
||||
|
||||
<script>
|
||||
fetch("https://git.betalupi.com/api/packages/Mark/generic/ormc-handouts/latest/index.json")
|
||||
.then(res => res.json())
|
||||
.then(out => {
|
||||
out = out.sort((a, b) => (
|
||||
a["title"].toLowerCase() < b["title"].toLowerCase()
|
||||
));
|
||||
|
||||
out.forEach(element => {
|
||||
if (element["group"] != "Advanced") { return }
|
||||
|
||||
// Handout title
|
||||
const title = document.createElement("span");
|
||||
const title_a = document.createElement("strong");
|
||||
title_a.appendChild(document.createTextNode(element["title"] + " "));
|
||||
title.appendChild(title_a)
|
||||
title.classList.add("handout-li-title");
|
||||
|
||||
// Handout title
|
||||
const desc = document.createElement("span");
|
||||
desc.appendChild(document.createTextNode(element["description"]));
|
||||
desc.classList.add("handout-li-desc");
|
||||
|
||||
const handout_link = element["handout"];
|
||||
const solutions_link = element["solutions"];
|
||||
|
||||
const links = document.createElement("span");
|
||||
links.classList.add("handout-li-links");
|
||||
const h = document.createElement("a");
|
||||
h.appendChild(document.createTextNode("handout"))
|
||||
h.href = handout_link;
|
||||
if (solutions_link === null) {
|
||||
links.appendChild(document.createTextNode("[ "));
|
||||
links.appendChild(h);
|
||||
links.appendChild(document.createTextNode(" ]"));
|
||||
} else {
|
||||
var s = document.createElement("a");
|
||||
s.appendChild(document.createTextNode("solutions"))
|
||||
s.href = solutions_link;
|
||||
links.appendChild(document.createTextNode("[ "));
|
||||
links.appendChild(h);
|
||||
links.appendChild(document.createTextNode(" | "));
|
||||
links.appendChild(s);
|
||||
links.appendChild(document.createTextNode(" ]"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Add to main list
|
||||
const item = document.createElement("li");
|
||||
item.appendChild(title)
|
||||
item.appendChild(links);
|
||||
//item.appendChild(desc)
|
||||
const list = document.getElementById("handout-ul-Advanced");
|
||||
list.insertBefore(item, list.children[0]);
|
||||
})}
|
||||
)
|
||||
.catch(err => {
|
||||
// Print fallback link if we failed to load json index
|
||||
console.log(err)
|
||||
|
||||
const title = document.createElement("span");
|
||||
const title_a = document.createElement("strong");
|
||||
title_a.appendChild(document.createTextNode("Error: "));
|
||||
title.appendChild(title_a)
|
||||
title.appendChild(document.createTextNode("failed to load handouts, something broke."))
|
||||
title.classList.add("handout-li-title");
|
||||
|
||||
const fallback = "https://git.betalupi.com/Mark/-/packages/generic/ormc-handouts/latest";
|
||||
const link = document.createElement("a");
|
||||
link.href = fallback
|
||||
link.appendChild(document.createTextNode("ormc-handouts"));
|
||||
|
||||
const item_a = document.createElement("li");
|
||||
item_a.appendChild(title)
|
||||
const item_b = document.createElement("li");
|
||||
item_b.appendChild(document.createTextNode("Fallback link: "))
|
||||
item_b.appendChild(link)
|
||||
|
||||
const list = document.getElementById("handout-ul-Advanced");
|
||||
list.insertBefore(item_b, list.children[0]);
|
||||
list.insertBefore(item_a, list.children[0]);
|
||||
});
|
||||
</script>
|
||||
|
||||
<br></br>
|
||||
|
||||
173
crates/service/service-webpage/src/pages/handouts.rs
Normal file
173
crates/service/service-webpage/src/pages/handouts.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use assetserver::Asset;
|
||||
use chrono::TimeDelta;
|
||||
use maud::{Markup, PreEscaped, html};
|
||||
use serde::Deserialize;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use crate::{
|
||||
components::{
|
||||
md::Markdown,
|
||||
misc::{Backlinks, FarLink},
|
||||
},
|
||||
page::{Page, PageMetadata},
|
||||
routes::assets::Image_Icon,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct HandoutEntry {
|
||||
title: String,
|
||||
group: String,
|
||||
handout: String,
|
||||
solutions: Option<String>,
|
||||
}
|
||||
|
||||
async fn get_index() -> Result<Vec<HandoutEntry>, reqwest::Error> {
|
||||
let start = Instant::now();
|
||||
let res = reqwest::get(
|
||||
"https://git.betalupi.com/api/packages/Mark/generic/ormc-handouts/latest/index.json",
|
||||
)
|
||||
.await;
|
||||
|
||||
let res = match res {
|
||||
Ok(x) => x,
|
||||
Err(err) => {
|
||||
warn!("Error while getting index: {err:?}");
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
|
||||
let mut res: Vec<HandoutEntry> = res.json().await?;
|
||||
res.sort_by_key(|x| x.title.clone());
|
||||
|
||||
debug!(
|
||||
message = "Fetched handout index",
|
||||
n_handouts = res.len(),
|
||||
time_ms = start.elapsed().as_millis()
|
||||
);
|
||||
return Ok(res);
|
||||
}
|
||||
|
||||
fn build_list_for_group(handouts: &[HandoutEntry], group: &str) -> Markup {
|
||||
html! {
|
||||
ul class="handout-ul" {
|
||||
|
||||
@for h in handouts {
|
||||
@if h.group ==group {
|
||||
li {
|
||||
span class="handdout-li-title" {
|
||||
strong { (h.title) }
|
||||
}
|
||||
span class="handout-li-links" {
|
||||
"[ "
|
||||
|
||||
@if let Some(solutions) = &h.solutions {
|
||||
a href=(h.handout) {"handout"}
|
||||
" | "
|
||||
a href=(solutions) {"solutions"}
|
||||
} @else {
|
||||
a href=(h.handout) {"handout"}
|
||||
}
|
||||
"] "
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: page
|
||||
//
|
||||
|
||||
pub fn handouts() -> Page {
|
||||
let md = Markdown::parse(include_str!("handouts.md"));
|
||||
|
||||
#[expect(clippy::unwrap_used)]
|
||||
let mut meta = PageMetadata::from_markdown_frontmatter(&md)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
if meta.image.is_none() {
|
||||
meta.image = Some(Image_Icon::URL.to_owned());
|
||||
}
|
||||
|
||||
let html = PreEscaped(md.render());
|
||||
|
||||
Page {
|
||||
meta,
|
||||
html_ttl: Some(TimeDelta::seconds(300)),
|
||||
|
||||
generate_html: Box::new(move |page| {
|
||||
let html = html.clone(); // TODO: find a way to not clone here
|
||||
Box::pin(async move {
|
||||
let handouts = get_index().await;
|
||||
|
||||
let warmups = match &handouts {
|
||||
Ok(handouts) => build_list_for_group(handouts, "Warm-Ups"),
|
||||
Err(error) => {
|
||||
warn!("Could not load handout index: {error:?}");
|
||||
html! {
|
||||
span style="color:var(--yellow)" {
|
||||
"Could not load handouts, something broke."
|
||||
}
|
||||
" "
|
||||
(
|
||||
FarLink(
|
||||
"https://git.betalupi.com/Mark/-/packages/generic/ormc-handouts/latest",
|
||||
"Try this direct link."
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let advanced = match &handouts {
|
||||
Ok(handouts) => build_list_for_group(handouts, "Advanced"),
|
||||
Err(_) => html! {
|
||||
span style="color:var(--yellow)" {
|
||||
"Could not load handouts, something broke."
|
||||
}
|
||||
" "
|
||||
(
|
||||
FarLink(
|
||||
"https://git.betalupi.com/Mark/-/packages/generic/ormc-handouts/latest",
|
||||
"Try this direct link."
|
||||
)
|
||||
)
|
||||
},
|
||||
};
|
||||
|
||||
html! {
|
||||
@if let Some(slug) = &page.meta.slug {
|
||||
(Backlinks(&[("/", "home")], slug))
|
||||
}
|
||||
|
||||
(html)
|
||||
|
||||
(Markdown(concat!(
|
||||
"## Warm-Ups",
|
||||
"\n\n",
|
||||
"Students never show up on time. Some come early, some come late. Warm-ups ",
|
||||
"are my solution to this problem: we hand these out as students walk in, ",
|
||||
"giving them something to do until we can start the lesson.",
|
||||
)))
|
||||
(warmups)
|
||||
br {}
|
||||
|
||||
(Markdown(concat!(
|
||||
"## Advanced",
|
||||
"\n\n",
|
||||
"The highest level of the ORMC, and the group I spend most of my time with. ",
|
||||
"Students in ORMC Advanced are in high school, which means ",
|
||||
"they're ~14-18 years old.",
|
||||
)))
|
||||
(advanced)
|
||||
br {}
|
||||
}
|
||||
})
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -23,53 +23,55 @@ pub fn index() -> Page {
|
||||
},
|
||||
|
||||
generate_html: Box::new(move |_page| {
|
||||
html! {
|
||||
h2 id="about" { "About" }
|
||||
Box::pin(async {
|
||||
html! {
|
||||
h2 id="about" { "About" }
|
||||
|
||||
div {
|
||||
img
|
||||
src=(Image_Cover::URL)
|
||||
style="float:left;margin:10px 10px 10px 10px;display:block;width:25%;"
|
||||
{}
|
||||
div {
|
||||
img
|
||||
src=(Image_Cover::URL)
|
||||
style="float:left;margin:10px 10px 10px 10px;display:block;width:25%;"
|
||||
{}
|
||||
|
||||
div style="margin:2ex 1ex 2ex 1ex;display:inline-block;overflow:hidden;width:60%;" {
|
||||
"Welcome, you've reached Mark's main page. Here you'll find"
|
||||
" links to various projects I've worked on."
|
||||
div style="margin:2ex 1ex 2ex 1ex;display:inline-block;overflow:hidden;width:60%;" {
|
||||
"Welcome, you've reached Mark's main page. Here you'll find"
|
||||
" links to various projects I've worked on."
|
||||
|
||||
ul {
|
||||
li { (MangledBetaEmail {}) }
|
||||
li { (MangledGoogleEmail {}) }
|
||||
ul {
|
||||
li { (MangledBetaEmail {}) }
|
||||
li { (MangledGoogleEmail {}) }
|
||||
|
||||
li {
|
||||
(
|
||||
FarLink(
|
||||
"https://github.com/rm-dr",
|
||||
html!(
|
||||
(FAIcon::Github)
|
||||
"rm-dr"
|
||||
li {
|
||||
(
|
||||
FarLink(
|
||||
"https://github.com/rm-dr",
|
||||
html!(
|
||||
(FAIcon::Github)
|
||||
"rm-dr"
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
li {
|
||||
(
|
||||
FarLink(
|
||||
"https://git.betalupi.com",
|
||||
html!(
|
||||
(FAIcon::Git)
|
||||
"git.betalupi.com"
|
||||
li {
|
||||
(
|
||||
FarLink(
|
||||
"https://git.betalupi.com",
|
||||
html!(
|
||||
(FAIcon::Git)
|
||||
"git.betalupi.com"
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
br style="clear:both;" {}
|
||||
}
|
||||
br style="clear:both;" {}
|
||||
}
|
||||
|
||||
(Markdown(include_str!("index.md")))
|
||||
}
|
||||
(Markdown(include_str!("index.md")))
|
||||
}
|
||||
})
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
mod index;
|
||||
use assetserver::Asset;
|
||||
pub use index::index;
|
||||
|
||||
use crate::{page::Page, routes::assets::Image_Icon};
|
||||
|
||||
mod handouts;
|
||||
mod index;
|
||||
|
||||
pub use handouts::handouts;
|
||||
pub use index::index;
|
||||
|
||||
pub fn links() -> Page {
|
||||
/*
|
||||
Dead links:
|
||||
@@ -12,19 +16,12 @@ pub fn links() -> Page {
|
||||
http://www.3dprintmath.com/
|
||||
*/
|
||||
|
||||
Page::from_markdown(include_str!("links.md"), Some(Image_Icon::URL.to_string()))
|
||||
Page::from_markdown(include_str!("links.md"), Some(Image_Icon::URL.to_owned()))
|
||||
}
|
||||
|
||||
pub fn betalupi() -> Page {
|
||||
Page::from_markdown(
|
||||
include_str!("betalupi.md"),
|
||||
Some(Image_Icon::URL.to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn handouts() -> Page {
|
||||
Page::from_markdown(
|
||||
include_str!("handouts.md"),
|
||||
Some(Image_Icon::URL.to_string()),
|
||||
Some(Image_Icon::URL.to_owned()),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::{pin::Pin, sync::Arc, time::Duration};
|
||||
|
||||
use assetserver::Asset;
|
||||
use axum::Router;
|
||||
use maud::{DOCTYPE, Markup, PreEscaped, html};
|
||||
@@ -16,59 +18,65 @@ pub(super) fn router() -> Router<()> {
|
||||
let (asset_prefix, asset_router) = assets::asset_router();
|
||||
info!("Serving assets at {asset_prefix}");
|
||||
|
||||
let server = build_server().into_router();
|
||||
let server = build_server();
|
||||
tokio::task::spawn(server.clone().start_rerender_task(Duration::from_secs(3)));
|
||||
let router = server.into_router();
|
||||
|
||||
Router::new().merge(server).nest(asset_prefix, asset_router)
|
||||
Router::new().merge(router).nest(asset_prefix, asset_router)
|
||||
}
|
||||
|
||||
fn build_server() -> PageServer {
|
||||
PageServer::new(Box::new(page_wrapper))
|
||||
fn build_server() -> Arc<PageServer> {
|
||||
let server = PageServer::new(Box::new(page_wrapper));
|
||||
server
|
||||
.add_page("/", pages::index())
|
||||
.add_page("/links", pages::links())
|
||||
.add_page("/whats-a-betalupi", pages::betalupi())
|
||||
.add_page("/handouts", pages::handouts())
|
||||
.add_page("/handouts", pages::handouts());
|
||||
server
|
||||
}
|
||||
|
||||
fn page_wrapper(page: &Page) -> Markup {
|
||||
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" {}
|
||||
fn page_wrapper<'a>(page: &'a Page) -> Pin<Box<dyn Future<Output = Markup> + 'a + Send + Sync>> {
|
||||
Box::pin(async move {
|
||||
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) {}
|
||||
link rel="stylesheet" href=(Styles_Main::URL) {}
|
||||
|
||||
(&page.meta)
|
||||
title { (PreEscaped(page.meta.title.clone())) }
|
||||
}
|
||||
(&page.meta)
|
||||
title { (PreEscaped(page.meta.title.clone())) }
|
||||
}
|
||||
|
||||
body {
|
||||
div class="wrapper" {
|
||||
main { ( page.generate_html() ) }
|
||||
body {
|
||||
div class="wrapper" {
|
||||
main { ( page.generate_html().await ) }
|
||||
|
||||
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"))
|
||||
"."
|
||||
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"))
|
||||
"."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user