Migrate to servable
Some checks failed
CI / Check typos (push) Successful in 15s
CI / Check links (push) Failing after 1m37s
CI / Clippy (push) Successful in 3m44s
CI / Build and test (push) Successful in 12m33s
CI / Build container (push) Successful in 10m24s
CI / Deploy on waypoint (push) Successful in 49s
Some checks failed
CI / Check typos (push) Successful in 15s
CI / Check links (push) Failing after 1m37s
CI / Clippy (push) Successful in 3m44s
CI / Build and test (push) Successful in 12m33s
CI / Build container (push) Successful in 10m24s
CI / Deploy on waypoint (push) Successful in 49s
This commit is contained in:
@@ -1,21 +0,0 @@
|
||||
[package]
|
||||
name = "page"
|
||||
version = { workspace = true }
|
||||
rust-version = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
toolbox = { workspace = true }
|
||||
pixel-transform = { workspace = true }
|
||||
|
||||
axum = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
maud = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
tower = { workspace = true }
|
||||
serde_urlencoded = { workspace = true }
|
||||
1
crates/lib/page/htmx/htmx-2.0.8.min.js
vendored
1
crates/lib/page/htmx/htmx-2.0.8.min.js
vendored
File diff suppressed because one or more lines are too long
@@ -1,11 +0,0 @@
|
||||
htmx.defineExtension('json-enc', {
|
||||
onEvent: function (name, evt) {
|
||||
if (name === "htmx:configRequest") {
|
||||
evt.detail.headers['Content-Type'] = "application/json";
|
||||
}
|
||||
},
|
||||
encodeParameters: function (xhr, parameters, elt) {
|
||||
xhr.overrideMimeType('text/json');
|
||||
return (JSON.stringify(parameters));
|
||||
}
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
//! A web stack for embedded uis.
|
||||
//!
|
||||
//! Featuring:
|
||||
//! - htmx
|
||||
//! - axum
|
||||
//! - rust
|
||||
//! - and maud
|
||||
|
||||
pub mod servable;
|
||||
|
||||
mod types;
|
||||
pub use types::*;
|
||||
|
||||
mod route;
|
||||
pub use route::*;
|
||||
|
||||
pub const HTMX_2_0_8: servable::StaticAsset = servable::StaticAsset {
|
||||
bytes: include_str!("../htmx/htmx-2.0.8.min.js").as_bytes(),
|
||||
mime: toolbox::mime::MimeType::Javascript,
|
||||
};
|
||||
|
||||
pub const EXT_JSON_1_19_12: servable::StaticAsset = servable::StaticAsset {
|
||||
bytes: include_str!("../htmx/json-enc-1.9.12.js").as_bytes(),
|
||||
mime: toolbox::mime::MimeType::Javascript,
|
||||
};
|
||||
@@ -1,275 +0,0 @@
|
||||
use axum::{
|
||||
Router,
|
||||
body::Body,
|
||||
http::{HeaderMap, HeaderValue, Method, Request, StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use chrono::TimeDelta;
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
convert::Infallible,
|
||||
net::SocketAddr,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
time::Instant,
|
||||
};
|
||||
use toolbox::mime::MimeType;
|
||||
use tower::Service;
|
||||
use tracing::trace;
|
||||
|
||||
use crate::{ClientInfo, RenderContext, Rendered, RenderedBody, servable::Servable};
|
||||
|
||||
struct Default404 {}
|
||||
impl Servable for Default404 {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
return Rendered {
|
||||
code: StatusCode::NOT_FOUND,
|
||||
body: (),
|
||||
ttl: Some(TimeDelta::days(1)),
|
||||
immutable: true,
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(MimeType::Html),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async { self.head(ctx).await.with_body(RenderedBody::Empty) })
|
||||
}
|
||||
}
|
||||
|
||||
/// A set of related [Servable]s under one route.
|
||||
///
|
||||
/// Use as follows:
|
||||
/// ```ignore
|
||||
///
|
||||
/// // Add compression, for example.
|
||||
/// // Also consider CORS and timeout.
|
||||
/// let compression: CompressionLayer = CompressionLayer::new()
|
||||
/// .br(true)
|
||||
/// .deflate(true)
|
||||
/// .gzip(true)
|
||||
/// .zstd(true)
|
||||
/// .compress_when(DefaultPredicate::new());
|
||||
///
|
||||
/// let route = ServableRoute::new()
|
||||
/// .add_page(
|
||||
/// "/page",
|
||||
/// StaticAsset {
|
||||
/// bytes: "I am a page".as_bytes(),
|
||||
/// mime: MimeType::Text,
|
||||
/// },
|
||||
/// );
|
||||
///
|
||||
/// Router::new()
|
||||
/// .nest_service("/", route)
|
||||
/// .layer(compression.clone());
|
||||
/// ```
|
||||
#[derive(Clone)]
|
||||
pub struct ServableRoute {
|
||||
pages: Arc<HashMap<String, Arc<dyn Servable>>>,
|
||||
notfound: Arc<dyn Servable>,
|
||||
}
|
||||
|
||||
impl ServableRoute {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
pages: Arc::new(HashMap::new()),
|
||||
notfound: Arc::new(Default404 {}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set this server's "not found" page
|
||||
pub fn with_404<S: Servable + 'static>(mut self, page: S) -> Self {
|
||||
self.notfound = Arc::new(page);
|
||||
self
|
||||
}
|
||||
|
||||
/// Add a page to this server at the given route.
|
||||
/// - panics if route does not start with a `/`, ends with a `/`, or contains `//`.
|
||||
/// - urls are normalized, routes that violate this condition will never be served.
|
||||
/// - `/` is an exception, it is valid.
|
||||
/// - panics if called after this service is started
|
||||
/// - overwrites existing pages
|
||||
pub fn add_page<S: Servable + 'static>(mut self, route: impl Into<String>, page: S) -> Self {
|
||||
let route = route.into();
|
||||
|
||||
if !route.starts_with("/") {
|
||||
panic!("route must start with /")
|
||||
};
|
||||
|
||||
if route.ends_with("/") && route != "/" {
|
||||
panic!("route must not end with /")
|
||||
};
|
||||
|
||||
if route.contains("//") {
|
||||
panic!("route must not contain //")
|
||||
};
|
||||
|
||||
#[expect(clippy::expect_used)]
|
||||
Arc::get_mut(&mut self.pages)
|
||||
.expect("add_pages called after service was started")
|
||||
.insert(route, Arc::new(page));
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Convenience method.
|
||||
/// Turns this service into a router.
|
||||
///
|
||||
/// Equivalent to:
|
||||
/// ```ignore
|
||||
/// Router::new().fallback_service(self)
|
||||
/// ```
|
||||
pub fn into_router<T: Clone + Send + Sync + 'static>(self) -> Router<T> {
|
||||
Router::new().fallback_service(self)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: impl Service
|
||||
//
|
||||
|
||||
impl Service<Request<Body>> for ServableRoute {
|
||||
type Response = Response;
|
||||
type Error = Infallible;
|
||||
type Future =
|
||||
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request<Body>) -> Self::Future {
|
||||
if req.method() != Method::GET && req.method() != Method::HEAD {
|
||||
let mut headers = HeaderMap::with_capacity(1);
|
||||
headers.insert(header::ACCEPT, HeaderValue::from_static("GET,HEAD"));
|
||||
return Box::pin(async {
|
||||
Ok((StatusCode::METHOD_NOT_ALLOWED, headers).into_response())
|
||||
});
|
||||
}
|
||||
|
||||
let pages = self.pages.clone();
|
||||
let notfound = self.notfound.clone();
|
||||
Box::pin(async move {
|
||||
let addr = req.extensions().get::<SocketAddr>().copied();
|
||||
let route = req.uri().path().to_owned();
|
||||
let headers = req.headers().clone();
|
||||
let query: BTreeMap<String, String> =
|
||||
serde_urlencoded::from_str(req.uri().query().unwrap_or("")).unwrap_or_default();
|
||||
|
||||
let start = Instant::now();
|
||||
let client_info = ClientInfo::from_headers(&headers);
|
||||
let ua = headers
|
||||
.get("user-agent")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
.unwrap_or("");
|
||||
|
||||
trace!(
|
||||
message = "Serving route",
|
||||
route,
|
||||
addr = ?addr,
|
||||
user_agent = ua,
|
||||
device_type = ?client_info.device_type
|
||||
);
|
||||
|
||||
// Normalize url with redirect
|
||||
if (route.ends_with('/') && route != "/") || route.contains("//") {
|
||||
let mut new_route = route.clone();
|
||||
while new_route.contains("//") {
|
||||
new_route = new_route.replace("//", "/");
|
||||
}
|
||||
let new_route = new_route.trim_matches('/');
|
||||
|
||||
trace!(
|
||||
message = "Redirecting",
|
||||
route,
|
||||
new_route,
|
||||
addr = ?addr,
|
||||
user_agent = ua,
|
||||
device_type = ?client_info.device_type
|
||||
);
|
||||
|
||||
let mut headers = HeaderMap::with_capacity(1);
|
||||
match HeaderValue::from_str(&format!("/{new_route}")) {
|
||||
Ok(x) => headers.append(header::LOCATION, x),
|
||||
Err(_) => return Ok(StatusCode::BAD_REQUEST.into_response()),
|
||||
};
|
||||
return Ok((StatusCode::PERMANENT_REDIRECT, headers).into_response());
|
||||
}
|
||||
|
||||
let ctx = RenderContext {
|
||||
client_info,
|
||||
route,
|
||||
query,
|
||||
};
|
||||
|
||||
let page = pages.get(&ctx.route).unwrap_or(¬found);
|
||||
let mut rend = match req.method() == Method::HEAD {
|
||||
true => page.head(&ctx).await.with_body(RenderedBody::Empty),
|
||||
false => page.render(&ctx).await,
|
||||
};
|
||||
|
||||
// Tweak headers
|
||||
{
|
||||
if !rend.headers.contains_key(header::CACHE_CONTROL) {
|
||||
let max_age = rend.ttl.map(|x| x.num_seconds()).unwrap_or(1).max(1);
|
||||
|
||||
let mut value = String::new();
|
||||
if rend.immutable {
|
||||
value.push_str("immutable, ");
|
||||
}
|
||||
|
||||
value.push_str("public, ");
|
||||
value.push_str(&format!("max-age={}, ", max_age));
|
||||
|
||||
#[expect(clippy::unwrap_used)]
|
||||
rend.headers.insert(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_str(value.trim().trim_end_matches(',')).unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
if !rend.headers.contains_key("Accept-CH") {
|
||||
rend.headers
|
||||
.insert("Accept-CH", HeaderValue::from_static("Sec-CH-UA-Mobile"));
|
||||
}
|
||||
|
||||
if !rend.headers.contains_key(header::CONTENT_TYPE)
|
||||
&& let Some(mime) = &rend.mime
|
||||
{
|
||||
#[expect(clippy::unwrap_used)]
|
||||
rend.headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_str(&mime.to_string()).unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
trace!(
|
||||
message = "Served route",
|
||||
route = ctx.route,
|
||||
addr = ?addr,
|
||||
user_agent = ua,
|
||||
device_type = ?client_info.device_type,
|
||||
time_ns = start.elapsed().as_nanos()
|
||||
);
|
||||
|
||||
Ok(match rend.body {
|
||||
RenderedBody::Markup(m) => (rend.code, rend.headers, m.0).into_response(),
|
||||
RenderedBody::Static(d) => (rend.code, rend.headers, d).into_response(),
|
||||
RenderedBody::Bytes(d) => (rend.code, rend.headers, d).into_response(),
|
||||
RenderedBody::String(s) => (rend.code, rend.headers, s).into_response(),
|
||||
RenderedBody::Empty => (rend.code, rend.headers).into_response(),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use chrono::TimeDelta;
|
||||
use pixel_transform::TransformerChain;
|
||||
use std::{pin::Pin, str::FromStr};
|
||||
use toolbox::mime::MimeType;
|
||||
use tracing::{error, trace};
|
||||
|
||||
use crate::{RenderContext, Rendered, RenderedBody, servable::Servable};
|
||||
|
||||
pub struct StaticAsset {
|
||||
pub bytes: &'static [u8],
|
||||
pub mime: MimeType,
|
||||
}
|
||||
|
||||
impl Servable for StaticAsset {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
let ttl = Some(TimeDelta::days(30));
|
||||
let is_image = TransformerChain::mime_is_image(&self.mime);
|
||||
|
||||
let transform = match (is_image, ctx.query.get("t")) {
|
||||
(false, _) | (_, None) => None,
|
||||
|
||||
(true, Some(x)) => match TransformerChain::from_str(x) {
|
||||
Ok(x) => Some(x),
|
||||
Err(_err) => {
|
||||
return Rendered {
|
||||
code: StatusCode::BAD_REQUEST,
|
||||
body: (),
|
||||
ttl,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
match transform {
|
||||
Some(transform) => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(
|
||||
transform
|
||||
.output_mime(&self.mime)
|
||||
.unwrap_or(self.mime.clone()),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
None => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: (),
|
||||
ttl,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
let ttl = Some(TimeDelta::days(30));
|
||||
|
||||
// Automatically provide transformation if this is an image
|
||||
let is_image = TransformerChain::mime_is_image(&self.mime);
|
||||
|
||||
let transform = match (is_image, ctx.query.get("t")) {
|
||||
(false, _) | (_, None) => None,
|
||||
|
||||
(true, Some(x)) => match TransformerChain::from_str(x) {
|
||||
Ok(x) => Some(x),
|
||||
Err(err) => {
|
||||
return Rendered {
|
||||
code: StatusCode::BAD_REQUEST,
|
||||
body: RenderedBody::String(err),
|
||||
ttl,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
match transform {
|
||||
Some(transform) => {
|
||||
trace!(message = "Transforming image", ?transform);
|
||||
|
||||
let task = {
|
||||
let mime = Some(self.mime.clone());
|
||||
let bytes = self.bytes;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
transform.transform_bytes(bytes, mime.as_ref())
|
||||
})
|
||||
};
|
||||
|
||||
let res = match task.await {
|
||||
Ok(x) => x,
|
||||
Err(error) => {
|
||||
error!(message = "Error while transforming image", ?error);
|
||||
return Rendered {
|
||||
code: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
body: RenderedBody::String(format!(
|
||||
"Error while transforming image: {error:?}"
|
||||
)),
|
||||
ttl: None,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
match res {
|
||||
Ok((mime, bytes)) => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: RenderedBody::Bytes(bytes),
|
||||
ttl,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(mime),
|
||||
};
|
||||
}
|
||||
|
||||
Err(err) => {
|
||||
return Rendered {
|
||||
code: StatusCode::INTERNAL_SERVER_ERROR,
|
||||
body: RenderedBody::String(format!("{err}")),
|
||||
ttl,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: None,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None => {
|
||||
return Rendered {
|
||||
code: StatusCode::OK,
|
||||
body: RenderedBody::Static(self.bytes),
|
||||
ttl,
|
||||
immutable: true,
|
||||
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(self.mime.clone()),
|
||||
};
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
mod asset;
|
||||
pub use asset::*;
|
||||
|
||||
mod page;
|
||||
pub use page::*;
|
||||
|
||||
mod redirect;
|
||||
pub use redirect::*;
|
||||
|
||||
/// Something that may be served over http.
|
||||
pub trait Servable: Send + Sync {
|
||||
/// Return the same response as [Servable::render], but with an empty body.
|
||||
/// Used to respond to `HEAD` requests.
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<Box<dyn Future<Output = crate::Rendered<()>> + 'a + Send + Sync>>;
|
||||
|
||||
/// Render this page
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a crate::RenderContext,
|
||||
) -> std::pin::Pin<
|
||||
Box<dyn Future<Output = crate::Rendered<crate::RenderedBody>> + 'a + Send + Sync>,
|
||||
>;
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use chrono::TimeDelta;
|
||||
use maud::{DOCTYPE, Markup, PreEscaped, html};
|
||||
use serde::Deserialize;
|
||||
use std::{pin::Pin, sync::Arc};
|
||||
use toolbox::mime::MimeType;
|
||||
|
||||
use crate::{RenderContext, Rendered, RenderedBody, servable::Servable};
|
||||
|
||||
//
|
||||
// MARK: metadata
|
||||
//
|
||||
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq, Deserialize)]
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: page
|
||||
//
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Page {
|
||||
pub meta: PageMetadata,
|
||||
pub immutable: bool,
|
||||
|
||||
/// 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<TimeDelta>,
|
||||
|
||||
/// 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: Arc<
|
||||
dyn Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
+ for<'a> Fn(
|
||||
&'a Page,
|
||||
&'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Markup> + Send + Sync + 'a>>,
|
||||
>,
|
||||
|
||||
pub response_code: StatusCode,
|
||||
|
||||
pub scripts_inline: Vec<String>,
|
||||
pub scripts_linked: Vec<String>,
|
||||
pub styles_linked: Vec<String>,
|
||||
pub styles_inline: Vec<String>,
|
||||
|
||||
/// `name`, `content` for extra `<meta>` tags
|
||||
pub extra_meta: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Default for Page {
|
||||
fn default() -> Self {
|
||||
Page {
|
||||
// No cache by default
|
||||
html_ttl: None,
|
||||
immutable: false,
|
||||
|
||||
meta: Default::default(),
|
||||
generate_html: Arc::new(|_, _| Box::pin(async { html!() })),
|
||||
response_code: StatusCode::OK,
|
||||
scripts_inline: Vec::new(),
|
||||
scripts_linked: Vec::new(),
|
||||
styles_inline: Vec::new(),
|
||||
styles_linked: Vec::new(),
|
||||
extra_meta: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub async fn generate_html(&self, ctx: &RenderContext) -> Markup {
|
||||
(self.generate_html)(self, ctx).await
|
||||
}
|
||||
|
||||
pub fn immutable(mut self, immutable: bool) -> Self {
|
||||
self.immutable = immutable;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn html_ttl(mut self, html_ttl: Option<TimeDelta>) -> Self {
|
||||
self.html_ttl = html_ttl;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn response_code(mut self, response_code: StatusCode) -> Self {
|
||||
self.response_code = response_code;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_script_inline(mut self, script: impl Into<String>) -> Self {
|
||||
self.scripts_inline.push(script.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_script_linked(mut self, url: impl Into<String>) -> Self {
|
||||
self.scripts_linked.push(url.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_style_inline(mut self, style: impl Into<String>) -> Self {
|
||||
self.styles_inline.push(style.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_style_linked(mut self, url: impl Into<String>) -> Self {
|
||||
self.styles_linked.push(url.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_extra_meta(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
|
||||
self.extra_meta.push((key.into(), value.into()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Servable for Page {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
return Rendered {
|
||||
code: self.response_code,
|
||||
body: (),
|
||||
ttl: self.html_ttl,
|
||||
immutable: self.immutable,
|
||||
headers: HeaderMap::new(),
|
||||
mime: Some(MimeType::Html),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
let inner_html = self.generate_html(ctx).await;
|
||||
|
||||
let html = html! {
|
||||
(DOCTYPE)
|
||||
html {
|
||||
head {
|
||||
meta charset="UTF-8";
|
||||
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";
|
||||
@for (name, content) in &self.extra_meta {
|
||||
meta name=(name) content=(content);
|
||||
}
|
||||
|
||||
//
|
||||
// Metadata
|
||||
//
|
||||
title { (PreEscaped(self.meta.title.clone())) }
|
||||
meta property="og:site_name" content=(self.meta.title);
|
||||
meta name="title" content=(self.meta.title);
|
||||
meta property="og:title" content=(self.meta.title);
|
||||
meta property="twitter:title" content=(self.meta.title);
|
||||
|
||||
@if let Some(author) = &self.meta.author {
|
||||
meta name="author" content=(author);
|
||||
}
|
||||
|
||||
@if let Some(desc) = &self.meta.description {
|
||||
meta name="description" content=(desc);
|
||||
meta property="og:description" content=(desc);
|
||||
meta property="twitter:description" content=(desc);
|
||||
}
|
||||
|
||||
@if let Some(image) = &self.meta.image {
|
||||
meta content=(image) property="og:image";
|
||||
link rel="shortcut icon" href=(image) type="image/x-icon";
|
||||
}
|
||||
|
||||
//
|
||||
// Scripts & styles
|
||||
//
|
||||
@for script in &self.scripts_linked {
|
||||
script src=(script) {}
|
||||
}
|
||||
@for style in &self.styles_linked {
|
||||
link rel="stylesheet" type="text/css" href=(style);
|
||||
}
|
||||
|
||||
@for script in &self.scripts_inline {
|
||||
script { (PreEscaped(script)) }
|
||||
}
|
||||
@for style in &self.styles_inline {
|
||||
style { (PreEscaped(style)) }
|
||||
}
|
||||
}
|
||||
|
||||
body { main { (inner_html) } }
|
||||
}
|
||||
};
|
||||
|
||||
return self.head(ctx).await.with_body(RenderedBody::Markup(html));
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: template
|
||||
//
|
||||
|
||||
pub struct PageTemplate {
|
||||
pub immutable: bool,
|
||||
pub html_ttl: Option<TimeDelta>,
|
||||
pub response_code: StatusCode,
|
||||
|
||||
pub scripts_inline: &'static [&'static str],
|
||||
pub scripts_linked: &'static [&'static str],
|
||||
pub styles_inline: &'static [&'static str],
|
||||
pub styles_linked: &'static [&'static str],
|
||||
pub extra_meta: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
impl Default for PageTemplate {
|
||||
fn default() -> Self {
|
||||
Self::const_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl PageTemplate {
|
||||
pub const fn const_default() -> Self {
|
||||
Self {
|
||||
html_ttl: Some(TimeDelta::days(1)),
|
||||
immutable: true,
|
||||
response_code: StatusCode::OK,
|
||||
|
||||
scripts_inline: &[],
|
||||
scripts_linked: &[],
|
||||
styles_inline: &[],
|
||||
styles_linked: &[],
|
||||
extra_meta: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new page using this template,
|
||||
/// with the given metadata and renderer.
|
||||
pub fn derive<
|
||||
R: Send
|
||||
+ Sync
|
||||
+ 'static
|
||||
+ for<'a> Fn(
|
||||
&'a Page,
|
||||
&'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Markup> + Send + Sync + 'a>>,
|
||||
>(
|
||||
&self,
|
||||
meta: PageMetadata,
|
||||
generate_html: R,
|
||||
) -> Page {
|
||||
Page {
|
||||
meta,
|
||||
immutable: self.immutable,
|
||||
html_ttl: self.html_ttl,
|
||||
response_code: self.response_code,
|
||||
|
||||
scripts_inline: self
|
||||
.scripts_inline
|
||||
.iter()
|
||||
.map(|x| (*x).to_owned())
|
||||
.collect(),
|
||||
|
||||
scripts_linked: self
|
||||
.scripts_linked
|
||||
.iter()
|
||||
.map(|x| (*x).to_owned())
|
||||
.collect(),
|
||||
|
||||
styles_inline: self.styles_inline.iter().map(|x| (*x).to_owned()).collect(),
|
||||
styles_linked: self.styles_linked.iter().map(|x| (*x).to_owned()).collect(),
|
||||
|
||||
extra_meta: self
|
||||
.extra_meta
|
||||
.iter()
|
||||
.map(|(a, b)| ((*a).to_owned(), (*b).to_owned()))
|
||||
.collect(),
|
||||
|
||||
generate_html: Arc::new(generate_html),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
use std::pin::Pin;
|
||||
|
||||
use axum::http::{
|
||||
HeaderMap, HeaderValue, StatusCode,
|
||||
header::{self, InvalidHeaderValue},
|
||||
};
|
||||
|
||||
use crate::{RenderContext, Rendered, RenderedBody, servable::Servable};
|
||||
|
||||
pub struct Redirect {
|
||||
to: HeaderValue,
|
||||
}
|
||||
|
||||
impl Redirect {
|
||||
pub fn new(to: impl Into<String>) -> Result<Self, InvalidHeaderValue> {
|
||||
Ok(Self {
|
||||
to: HeaderValue::from_str(&to.into())?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Servable for Redirect {
|
||||
fn head<'a>(
|
||||
&'a self,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<()>> + 'a + Send + Sync>> {
|
||||
Box::pin(async {
|
||||
let mut headers = HeaderMap::with_capacity(1);
|
||||
headers.append(header::LOCATION, self.to.clone());
|
||||
|
||||
return Rendered {
|
||||
code: StatusCode::PERMANENT_REDIRECT,
|
||||
headers,
|
||||
body: (),
|
||||
ttl: None,
|
||||
immutable: true,
|
||||
mime: None,
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn render<'a>(
|
||||
&'a self,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Rendered<RenderedBody>> + 'a + Send + Sync>> {
|
||||
Box::pin(async { self.head(ctx).await.with_body(RenderedBody::Empty) })
|
||||
}
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
use axum::http::{HeaderMap, StatusCode};
|
||||
use chrono::TimeDelta;
|
||||
use maud::Markup;
|
||||
use std::collections::BTreeMap;
|
||||
use toolbox::mime::MimeType;
|
||||
|
||||
//
|
||||
// MARK: rendered
|
||||
//
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum RenderedBody {
|
||||
Markup(Markup),
|
||||
Static(&'static [u8]),
|
||||
Bytes(Vec<u8>),
|
||||
String(String),
|
||||
Empty,
|
||||
}
|
||||
|
||||
pub trait RenderedBodyType {}
|
||||
impl RenderedBodyType for () {}
|
||||
impl RenderedBodyType for RenderedBody {}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Rendered<T: RenderedBodyType> {
|
||||
pub code: StatusCode,
|
||||
pub headers: HeaderMap,
|
||||
pub body: T,
|
||||
pub mime: Option<MimeType>,
|
||||
|
||||
/// How long to cache this response.
|
||||
/// If none, don't cache.
|
||||
pub ttl: Option<TimeDelta>,
|
||||
pub immutable: bool,
|
||||
}
|
||||
|
||||
impl Rendered<()> {
|
||||
/// Turn this [Rendered] into a [Rendered] with a body.
|
||||
pub fn with_body(self, body: RenderedBody) -> Rendered<RenderedBody> {
|
||||
Rendered {
|
||||
code: self.code,
|
||||
headers: self.headers,
|
||||
body,
|
||||
mime: self.mime,
|
||||
ttl: self.ttl,
|
||||
immutable: self.immutable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: context
|
||||
//
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct RenderContext {
|
||||
pub client_info: ClientInfo,
|
||||
pub route: String,
|
||||
pub query: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: clientinfo
|
||||
//
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum DeviceType {
|
||||
Mobile,
|
||||
Desktop,
|
||||
}
|
||||
|
||||
impl Default for DeviceType {
|
||||
fn default() -> Self {
|
||||
Self::Desktop
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ClientInfo {
|
||||
/// This is an estimate, but it's probably good enough.
|
||||
pub device_type: DeviceType,
|
||||
}
|
||||
|
||||
impl ClientInfo {
|
||||
pub fn from_headers(headers: &HeaderMap) -> Self {
|
||||
let ua = headers
|
||||
.get("user-agent")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
.unwrap_or("");
|
||||
|
||||
let ch_mobile = headers
|
||||
.get("Sec-CH-UA-Mobile")
|
||||
.and_then(|x| x.to_str().ok())
|
||||
.unwrap_or("");
|
||||
|
||||
let mut device_type = None;
|
||||
|
||||
if device_type.is_none() && ch_mobile.contains("1") {
|
||||
device_type = Some(DeviceType::Mobile);
|
||||
}
|
||||
|
||||
if device_type.is_none() && ua.contains("Mobile") {
|
||||
device_type = Some(DeviceType::Mobile);
|
||||
}
|
||||
|
||||
Self {
|
||||
device_type: device_type.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "pixel-transform"
|
||||
version = { workspace = true }
|
||||
rust-version = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
toolbox = { workspace = true }
|
||||
|
||||
serde = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
image = { workspace = true }
|
||||
strum = { workspace = true }
|
||||
@@ -1,159 +0,0 @@
|
||||
use image::{DynamicImage, ImageFormat};
|
||||
use serde::{Deserialize, Deserializer, de};
|
||||
use std::{fmt::Display, hash::Hash, io::Cursor, str::FromStr};
|
||||
use thiserror::Error;
|
||||
use toolbox::mime::MimeType;
|
||||
|
||||
use crate::transformers::{ImageTransformer, TransformerEnum};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TransformBytesError {
|
||||
#[error("{0} is not a valid image type")]
|
||||
NotAnImage(String),
|
||||
|
||||
#[error("error while processing image")]
|
||||
ImageError(#[from] image::ImageError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TransformerChain {
|
||||
pub steps: Vec<TransformerEnum>,
|
||||
}
|
||||
|
||||
impl TransformerChain {
|
||||
#[inline]
|
||||
pub fn mime_is_image(mime: &MimeType) -> bool {
|
||||
ImageFormat::from_mime_type(mime.to_string()).is_some()
|
||||
}
|
||||
|
||||
pub fn transform_image(&self, mut image: DynamicImage) -> DynamicImage {
|
||||
for step in &self.steps {
|
||||
match step {
|
||||
TransformerEnum::Format { .. } => {}
|
||||
TransformerEnum::MaxDim(t) => t.transform(&mut image),
|
||||
TransformerEnum::Crop(t) => t.transform(&mut image),
|
||||
}
|
||||
}
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
pub fn output_mime(&self, input_mime: &MimeType) -> Option<MimeType> {
|
||||
let mime = self
|
||||
.steps
|
||||
.last()
|
||||
.and_then(|x| match x {
|
||||
TransformerEnum::Format { format } => Some(MimeType::from(format.to_mime_type())),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(input_mime.clone());
|
||||
|
||||
let fmt = ImageFormat::from_mime_type(mime.to_string());
|
||||
fmt.map(|_| mime)
|
||||
}
|
||||
|
||||
pub fn transform_bytes(
|
||||
&self,
|
||||
image_bytes: &[u8],
|
||||
image_format: Option<&MimeType>,
|
||||
) -> Result<(MimeType, Vec<u8>), TransformBytesError> {
|
||||
let format: ImageFormat = match image_format {
|
||||
Some(x) => ImageFormat::from_mime_type(x.to_string())
|
||||
.ok_or(TransformBytesError::NotAnImage(x.to_string()))?,
|
||||
None => image::guess_format(image_bytes)?,
|
||||
};
|
||||
|
||||
let out_format = self
|
||||
.steps
|
||||
.last()
|
||||
.and_then(|x| match x {
|
||||
TransformerEnum::Format { format } => Some(format),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(&format);
|
||||
|
||||
let img = image::load_from_memory_with_format(image_bytes, format)?;
|
||||
let img = self.transform_image(img);
|
||||
|
||||
let out_mime = MimeType::from(out_format.to_mime_type());
|
||||
let mut out_bytes = Cursor::new(Vec::new());
|
||||
img.write_to(&mut out_bytes, *out_format)?;
|
||||
|
||||
return Ok((out_mime, out_bytes.into_inner()));
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for TransformerChain {
|
||||
type Err = String;
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let steps_str = s.split(";");
|
||||
|
||||
let mut steps = Vec::new();
|
||||
for s in steps_str {
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let step = s.parse();
|
||||
match step {
|
||||
Ok(x) => steps.push(x),
|
||||
Err(msg) => return Err(format!("invalid step `{s}`: {msg}")),
|
||||
}
|
||||
}
|
||||
|
||||
let n_format = steps
|
||||
.iter()
|
||||
.filter(|x| matches!(x, TransformerEnum::Format { .. }))
|
||||
.count();
|
||||
if n_format > 2 {
|
||||
return Err("provide at most one format()".to_owned());
|
||||
}
|
||||
|
||||
if n_format == 1 && !matches!(steps.last(), Some(TransformerEnum::Format { .. })) {
|
||||
return Err("format() must be last".to_owned());
|
||||
}
|
||||
|
||||
return Ok(Self { steps });
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for TransformerChain {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Self::from_str(&s).map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for TransformerChain {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut first = true;
|
||||
for step in &self.steps {
|
||||
if first {
|
||||
write!(f, "{step}")?;
|
||||
first = false
|
||||
} else {
|
||||
write!(f, ";{step}")?;
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for TransformerChain {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.to_string() == other.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for TransformerChain {}
|
||||
|
||||
impl Hash for TransformerChain {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.to_string().hash(state);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
mod pixeldim;
|
||||
|
||||
pub mod transformers;
|
||||
|
||||
mod chain;
|
||||
pub use chain::*;
|
||||
@@ -1,68 +0,0 @@
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
// TODO: parse -, + (100vw - 10px)
|
||||
// TODO: parse 100vw [min] 10
|
||||
// TODO: parse 100vw [max] 10
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum PixelDim {
|
||||
Pixels(u32),
|
||||
WidthPercent(f32),
|
||||
HeightPercent(f32),
|
||||
}
|
||||
|
||||
impl FromStr for PixelDim {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let numeric_end = s.find(|c: char| !c.is_ascii_digit() && c != '.');
|
||||
|
||||
let (quantity, unit) = numeric_end.map(|x| s.split_at(x)).unwrap_or((s, "px"));
|
||||
let quantity = quantity.trim();
|
||||
let unit = unit.trim();
|
||||
|
||||
match unit {
|
||||
"vw" => Ok(PixelDim::WidthPercent(
|
||||
quantity
|
||||
.parse()
|
||||
.map_err(|_err| format!("invalid quantity {quantity}"))?,
|
||||
)),
|
||||
|
||||
"vh" => Ok(PixelDim::HeightPercent(
|
||||
quantity
|
||||
.parse()
|
||||
.map_err(|_err| format!("invalid quantity {quantity}"))?,
|
||||
)),
|
||||
|
||||
"px" => Ok(PixelDim::Pixels(
|
||||
quantity
|
||||
.parse()
|
||||
.map_err(|_err| format!("invalid quantity {quantity}"))?,
|
||||
)),
|
||||
|
||||
_ => Err(format!("invalid unit {unit}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for PixelDim {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
FromStr::from_str(&s).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for PixelDim {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PixelDim::Pixels(px) => write!(f, "{px}"),
|
||||
PixelDim::WidthPercent(p) => write!(f, "{p:.2}vw"),
|
||||
PixelDim::HeightPercent(p) => write!(f, "{p:.2}vh"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
use std::{fmt::Display, str::FromStr};
|
||||
|
||||
use image::DynamicImage;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use strum::{Display, EnumString};
|
||||
|
||||
use crate::{pixeldim::PixelDim, transformers::ImageTransformer};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, Serialize, Deserialize, Display)]
|
||||
pub enum Direction {
|
||||
#[serde(rename = "n")]
|
||||
#[strum(to_string = "n")]
|
||||
#[strum(serialize = "north")]
|
||||
North,
|
||||
|
||||
#[serde(rename = "e")]
|
||||
#[strum(serialize = "e")]
|
||||
#[strum(serialize = "east")]
|
||||
East,
|
||||
|
||||
#[serde(rename = "s")]
|
||||
#[strum(serialize = "s")]
|
||||
#[strum(serialize = "south")]
|
||||
South,
|
||||
|
||||
#[serde(rename = "w")]
|
||||
#[strum(to_string = "w")]
|
||||
#[strum(serialize = "west")]
|
||||
West,
|
||||
|
||||
#[serde(rename = "c")]
|
||||
#[strum(serialize = "c")]
|
||||
#[strum(serialize = "center")]
|
||||
Center,
|
||||
|
||||
#[serde(rename = "ne")]
|
||||
#[strum(serialize = "ne")]
|
||||
#[strum(serialize = "northeast")]
|
||||
NorthEast,
|
||||
|
||||
#[serde(rename = "se")]
|
||||
#[strum(serialize = "se")]
|
||||
#[strum(serialize = "southeast")]
|
||||
SouthEast,
|
||||
|
||||
#[serde(rename = "nw")]
|
||||
#[strum(serialize = "nw")]
|
||||
#[strum(serialize = "northwest")]
|
||||
NorthWest,
|
||||
|
||||
#[serde(rename = "sw")]
|
||||
#[strum(serialize = "sw")]
|
||||
#[strum(serialize = "southwest")]
|
||||
SouthWest,
|
||||
}
|
||||
|
||||
/// Crop an image to the given size.
|
||||
/// - does not crop width if `w` is greater than image width
|
||||
/// - does not crop height if `h` is greater than image height
|
||||
/// - does nothing if `w` or `h` are less than or equal to zero.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CropTransformer {
|
||||
w: PixelDim,
|
||||
h: PixelDim,
|
||||
float: Direction,
|
||||
}
|
||||
|
||||
impl CropTransformer {
|
||||
pub fn new(w: PixelDim, h: PixelDim, float: Direction) -> Self {
|
||||
Self { w, h, float }
|
||||
}
|
||||
|
||||
fn crop_dim(&self, img_width: u32, img_height: u32) -> (u32, u32) {
|
||||
let crop_width = match self.w {
|
||||
PixelDim::Pixels(w) => w,
|
||||
PixelDim::WidthPercent(pct) => ((img_width as f32) * pct / 100.0) as u32,
|
||||
PixelDim::HeightPercent(pct) => ((img_height as f32) * pct / 100.0) as u32,
|
||||
};
|
||||
|
||||
let crop_height = match self.h {
|
||||
PixelDim::Pixels(h) => h,
|
||||
PixelDim::WidthPercent(pct) => ((img_width as f32) * pct / 100.0) as u32,
|
||||
PixelDim::HeightPercent(pct) => ((img_height as f32) * pct / 100.0) as u32,
|
||||
};
|
||||
|
||||
(crop_width, crop_height)
|
||||
}
|
||||
|
||||
#[expect(clippy::integer_division)]
|
||||
fn crop_pos(
|
||||
&self,
|
||||
img_width: u32,
|
||||
img_height: u32,
|
||||
crop_width: u32,
|
||||
crop_height: u32,
|
||||
) -> (u32, u32) {
|
||||
match self.float {
|
||||
Direction::North => {
|
||||
let x = (img_width - crop_width) / 2;
|
||||
let y = 0;
|
||||
(x, y)
|
||||
}
|
||||
Direction::East => {
|
||||
let x = img_width - crop_width;
|
||||
let y = (img_height - crop_height) / 2;
|
||||
(x, y)
|
||||
}
|
||||
Direction::South => {
|
||||
let x = (img_width - crop_width) / 2;
|
||||
let y = img_height - crop_height;
|
||||
(x, y)
|
||||
}
|
||||
Direction::West => {
|
||||
let x = 0;
|
||||
let y = (img_height - crop_height) / 2;
|
||||
(x, y)
|
||||
}
|
||||
Direction::Center => {
|
||||
let x = (img_width - crop_width) / 2;
|
||||
let y = (img_height - crop_height) / 2;
|
||||
(x, y)
|
||||
}
|
||||
Direction::NorthEast => {
|
||||
let x = img_width - crop_width;
|
||||
let y = 0;
|
||||
(x, y)
|
||||
}
|
||||
Direction::SouthEast => {
|
||||
let x = img_width - crop_width;
|
||||
let y = img_height - crop_height;
|
||||
(x, y)
|
||||
}
|
||||
Direction::NorthWest => {
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
(x, y)
|
||||
}
|
||||
Direction::SouthWest => {
|
||||
let x = 0;
|
||||
let y = img_height - crop_height;
|
||||
(x, y)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for CropTransformer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "crop({},{},{})", self.w, self.h, self.float)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageTransformer for CropTransformer {
|
||||
fn parse_args(args: &str) -> Result<Self, String> {
|
||||
let args: Vec<&str> = args.split(",").collect();
|
||||
if args.len() != 3 {
|
||||
return Err(format!("expected 3 args, got {}", args.len()));
|
||||
}
|
||||
|
||||
let w = args[0].trim().parse::<PixelDim>()?;
|
||||
let h = args[1].trim().parse::<PixelDim>()?;
|
||||
|
||||
let direction = args[2].trim();
|
||||
let direction = Direction::from_str(direction)
|
||||
.map_err(|_err| format!("invalid direction {direction}"))?;
|
||||
|
||||
Ok(Self {
|
||||
w,
|
||||
h,
|
||||
float: direction,
|
||||
})
|
||||
}
|
||||
|
||||
fn transform(&self, input: &mut DynamicImage) {
|
||||
let (img_width, img_height) = (input.width(), input.height());
|
||||
let (crop_width, crop_height) = self.crop_dim(img_width, img_height);
|
||||
|
||||
if (crop_width < img_width || crop_height < img_height) && crop_width > 0 && crop_height > 0
|
||||
{
|
||||
let (x, y) = self.crop_pos(img_width, img_height, crop_width, crop_height);
|
||||
*input = input.crop(x, y, crop_width, crop_height);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
use std::fmt::Display;
|
||||
|
||||
use image::{DynamicImage, imageops::FilterType};
|
||||
|
||||
use crate::{pixeldim::PixelDim, transformers::ImageTransformer};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MaxDimTransformer {
|
||||
w: PixelDim,
|
||||
h: PixelDim,
|
||||
}
|
||||
|
||||
impl MaxDimTransformer {
|
||||
pub fn new(w: PixelDim, h: PixelDim) -> Self {
|
||||
Self { w, h }
|
||||
}
|
||||
|
||||
fn target_dim(&self, img_width: u32, img_height: u32) -> (u32, u32) {
|
||||
let max_width = match self.w {
|
||||
PixelDim::Pixels(w) => Some(w),
|
||||
PixelDim::WidthPercent(pct) => Some(((img_width as f32) * pct / 100.0) as u32),
|
||||
PixelDim::HeightPercent(_) => None,
|
||||
};
|
||||
|
||||
let max_height = match self.h {
|
||||
PixelDim::Pixels(h) => Some(h),
|
||||
PixelDim::HeightPercent(pct) => Some(((img_height as f32) * pct / 100.0) as u32),
|
||||
PixelDim::WidthPercent(_) => None,
|
||||
};
|
||||
|
||||
if max_width.map(|x| img_width <= x).unwrap_or(true)
|
||||
&& max_height.map(|x| img_height <= x).unwrap_or(true)
|
||||
{
|
||||
return (img_width, img_height);
|
||||
}
|
||||
|
||||
let width_ratio = max_width
|
||||
.map(|x| x as f32 / img_width as f32)
|
||||
.unwrap_or(1.0);
|
||||
|
||||
let height_ratio = max_height
|
||||
.map(|x| x as f32 / img_height as f32)
|
||||
.unwrap_or(1.0);
|
||||
|
||||
let ratio = width_ratio.min(height_ratio);
|
||||
|
||||
(
|
||||
(img_width as f32 * ratio) as u32,
|
||||
(img_height as f32 * ratio) as u32,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for MaxDimTransformer {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "maxdim({},{})", self.w, self.h)
|
||||
}
|
||||
}
|
||||
|
||||
impl ImageTransformer for MaxDimTransformer {
|
||||
fn parse_args(args: &str) -> Result<Self, String> {
|
||||
let args: Vec<&str> = args.split(",").collect();
|
||||
if args.len() != 2 {
|
||||
return Err(format!("expected 2 args, got {}", args.len()));
|
||||
}
|
||||
|
||||
let w = args[0].parse::<PixelDim>()?;
|
||||
let h = args[1].parse::<PixelDim>()?;
|
||||
|
||||
Ok(Self { w, h })
|
||||
}
|
||||
|
||||
fn transform(&self, input: &mut DynamicImage) {
|
||||
let (img_width, img_height) = (input.width(), input.height());
|
||||
let (target_width, target_height) = self.target_dim(img_width, img_height);
|
||||
|
||||
// Only resize if needed
|
||||
if target_width != img_width || target_height != img_height {
|
||||
*input = input.resize(target_width, target_height, FilterType::Lanczos3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
use image::{DynamicImage, ImageFormat};
|
||||
use std::fmt;
|
||||
use std::fmt::{Debug, Display};
|
||||
use std::str::FromStr;
|
||||
|
||||
mod crop;
|
||||
pub use crop::*;
|
||||
|
||||
mod maxdim;
|
||||
pub use maxdim::*;
|
||||
|
||||
pub trait ImageTransformer
|
||||
where
|
||||
Self: PartialEq,
|
||||
Self: Sized + Clone,
|
||||
Self: Display + Debug,
|
||||
{
|
||||
/// Transform the given image in place
|
||||
fn transform(&self, input: &mut DynamicImage);
|
||||
|
||||
/// Parse an arg string.
|
||||
///
|
||||
/// `name({arg_string})`
|
||||
fn parse_args(args: &str) -> Result<Self, String>;
|
||||
}
|
||||
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
/// An enum of all [`ImageTransformer`]s
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum TransformerEnum {
|
||||
/// Usage: `maxdim(w, h)`
|
||||
///
|
||||
/// Scale the image so its width is smaller than `w`
|
||||
/// and its height is smaller than `h`. Aspect ratio is preserved.
|
||||
///
|
||||
/// To only limit the size of one dimension, use `vw` or `vh`.
|
||||
/// For example, `maxdim(50,100vh)` will not limit width.
|
||||
MaxDim(MaxDimTransformer),
|
||||
|
||||
/// Usage: `crop(w, h, float)`
|
||||
///
|
||||
/// Crop the image to at most `w` by `h` pixels,
|
||||
/// floating the crop area in the specified direction.
|
||||
///
|
||||
/// Directions are one of:
|
||||
/// - Cardinal: n,e,s,w
|
||||
/// - Diagonal: ne,nw,se,sw,
|
||||
/// - Centered: c
|
||||
///
|
||||
/// Examples:
|
||||
/// - `crop(100vw, 50)` gets the top 50 pixels of the image \
|
||||
/// (or fewer, if the image's height is smaller than 50)
|
||||
///
|
||||
/// To only limit the size of one dimension, use `vw` or `vh`.
|
||||
/// For example, `maxdim(50,100vh)` will not limit width.
|
||||
Crop(CropTransformer),
|
||||
|
||||
/// Usage: `format(format)`
|
||||
///
|
||||
/// Transcode the image to the given format.
|
||||
/// This step must be last, and cannot be provided
|
||||
/// more than once.
|
||||
///
|
||||
/// Valid formats:
|
||||
/// - bmp
|
||||
/// - gif
|
||||
/// - ico
|
||||
/// - jpeg or jpg
|
||||
/// - png
|
||||
/// - qoi
|
||||
/// - webp
|
||||
///
|
||||
/// Example:
|
||||
/// - `format(png)`
|
||||
///
|
||||
/// When transcoding an animated gif, the first frame is taken
|
||||
/// and all others are thrown away. This happens even if we
|
||||
/// transcode from a gif to a gif.
|
||||
Format { format: ImageFormat },
|
||||
}
|
||||
|
||||
impl FromStr for TransformerEnum {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.trim();
|
||||
|
||||
let (name, args) = {
|
||||
let name_len = match s.find('(') {
|
||||
Some(x) => x + 1,
|
||||
None => {
|
||||
return Err(format!(
|
||||
"invalid transformation {s}. Must look like name(args)."
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut balance = 1;
|
||||
let mut end = name_len;
|
||||
for i in s[name_len..].bytes() {
|
||||
match i {
|
||||
b')' => balance -= 1,
|
||||
b'(' => balance += 1,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if balance == 0 {
|
||||
break;
|
||||
}
|
||||
|
||||
end += 1;
|
||||
}
|
||||
|
||||
if balance != 0 {
|
||||
return Err(format!("mismatched parenthesis in {s}"));
|
||||
}
|
||||
|
||||
let name = s[0..name_len - 1].trim();
|
||||
let args = s[name_len..end].trim();
|
||||
let trail = s[end + 1..].trim();
|
||||
if !trail.is_empty() {
|
||||
return Err(format!(
|
||||
"invalid transformation {s}. Must look like name(args)."
|
||||
));
|
||||
}
|
||||
|
||||
(name, args)
|
||||
};
|
||||
|
||||
match name {
|
||||
"maxdim" => Ok(Self::MaxDim(MaxDimTransformer::parse_args(args)?)),
|
||||
"crop" => Ok(Self::Crop(CropTransformer::parse_args(args)?)),
|
||||
|
||||
"format" => Ok(TransformerEnum::Format {
|
||||
format: ImageFormat::from_extension(args)
|
||||
.ok_or(format!("invalid image format {args}"))?,
|
||||
}),
|
||||
|
||||
_ => Err(format!("unknown transformation {name}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for TransformerEnum {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
s.parse().map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for TransformerEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
TransformerEnum::MaxDim(x) => Display::fmt(x, f),
|
||||
TransformerEnum::Crop(x) => Display::fmt(x, f),
|
||||
TransformerEnum::Format { format } => {
|
||||
write!(f, "format({})", format.extensions_str()[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ tokio = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
num = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
envy = { workspace = true }
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! This crate contains various bits of useful code that don't fit anywhere else.
|
||||
|
||||
pub mod env;
|
||||
pub mod mime;
|
||||
pub mod misc;
|
||||
pub mod strings;
|
||||
|
||||
#[cfg(feature = "cli")]
|
||||
|
||||
@@ -70,6 +70,8 @@ impl From<LoggingConfig> for EnvFilter {
|
||||
format!("tower={}", conf.silence),
|
||||
format!("reqwest={}", conf.silence),
|
||||
format!("axum={}", conf.silence),
|
||||
format!("selectors={}", conf.silence),
|
||||
format!("html5ever={}", conf.silence),
|
||||
//
|
||||
// Libs
|
||||
//
|
||||
|
||||
@@ -1,811 +0,0 @@
|
||||
use std::{fmt::Display, str::FromStr};
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use tracing::debug;
|
||||
|
||||
/// A media type, conveniently parsed
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub enum MimeType {
|
||||
/// A mimetype we didn't recognize
|
||||
Other(String),
|
||||
|
||||
/// An unstructured binary blob
|
||||
/// Use this whenever a mime type is unknown
|
||||
Blob,
|
||||
|
||||
// MARK: Audio
|
||||
/// AAC audio file (audio/aac)
|
||||
Aac,
|
||||
/// FLAC audio file (audio/flac)
|
||||
Flac,
|
||||
/// MIDI audio file (audio/midi)
|
||||
Midi,
|
||||
/// MP3 audio file (audio/mpeg)
|
||||
Mp3,
|
||||
/// OGG audio file (audio/ogg)
|
||||
Oga,
|
||||
/// Opus audio file in Ogg container (audio/ogg)
|
||||
Opus,
|
||||
/// Waveform Audio Format (audio/wav)
|
||||
Wav,
|
||||
/// WEBM audio file (audio/webm)
|
||||
Weba,
|
||||
|
||||
// MARK: Video
|
||||
/// AVI: Audio Video Interleave (video/x-msvideo)
|
||||
Avi,
|
||||
/// MP4 video file (video/mp4)
|
||||
Mp4,
|
||||
/// MPEG video file (video/mpeg)
|
||||
Mpeg,
|
||||
/// OGG video file (video/ogg)
|
||||
Ogv,
|
||||
/// MPEG transport stream (video/mp2t)
|
||||
Ts,
|
||||
/// WEBM video file (video/webm)
|
||||
WebmVideo,
|
||||
/// 3GPP audio/video container (video/3gpp)
|
||||
ThreeGp,
|
||||
/// 3GPP2 audio/video container (video/3gpp2)
|
||||
ThreeG2,
|
||||
|
||||
// MARK: Images
|
||||
/// Animated Portable Network Graphics (image/apng)
|
||||
Apng,
|
||||
/// AVIF image (image/avif)
|
||||
Avif,
|
||||
/// Windows OS/2 Bitmap Graphics (image/bmp)
|
||||
Bmp,
|
||||
/// Graphics Interchange Format (image/gif)
|
||||
Gif,
|
||||
/// Icon format (image/vnd.microsoft.icon)
|
||||
Ico,
|
||||
/// JPEG image (image/jpeg)
|
||||
Jpg,
|
||||
/// Portable Network Graphics (image/png)
|
||||
Png,
|
||||
/// Quite ok Image Format
|
||||
Qoi,
|
||||
/// Scalable Vector Graphics (image/svg+xml)
|
||||
Svg,
|
||||
/// Tagged Image File Format (image/tiff)
|
||||
Tiff,
|
||||
/// WEBP image (image/webp)
|
||||
Webp,
|
||||
|
||||
// MARK: Text
|
||||
/// Plain text (text/plain)
|
||||
Text,
|
||||
/// Cascading Style Sheets (text/css)
|
||||
Css,
|
||||
/// Comma-separated values (text/csv)
|
||||
Csv,
|
||||
/// HyperText Markup Language (text/html)
|
||||
Html,
|
||||
/// JavaScript (text/javascript)
|
||||
Javascript,
|
||||
/// JSON format (application/json)
|
||||
Json,
|
||||
/// JSON-LD format (application/ld+json)
|
||||
JsonLd,
|
||||
/// XML (application/xml)
|
||||
Xml,
|
||||
|
||||
// MARK: Documents
|
||||
/// Adobe Portable Document Format (application/pdf)
|
||||
Pdf,
|
||||
/// Rich Text Format (application/rtf)
|
||||
Rtf,
|
||||
|
||||
// MARK: Archives
|
||||
/// Archive document, multiple files embedded (application/x-freearc)
|
||||
Arc,
|
||||
/// BZip archive (application/x-bzip)
|
||||
Bz,
|
||||
/// BZip2 archive (application/x-bzip2)
|
||||
Bz2,
|
||||
/// GZip Compressed Archive (application/gzip)
|
||||
Gz,
|
||||
/// Java Archive (application/java-archive)
|
||||
Jar,
|
||||
/// OGG (application/ogg)
|
||||
Ogg,
|
||||
/// RAR archive (application/vnd.rar)
|
||||
Rar,
|
||||
/// 7-zip archive (application/x-7z-compressed)
|
||||
SevenZ,
|
||||
/// Tape Archive (application/x-tar)
|
||||
Tar,
|
||||
/// ZIP archive (application/zip)
|
||||
Zip,
|
||||
|
||||
// MARK: Fonts
|
||||
/// MS Embedded OpenType fonts (application/vnd.ms-fontobject)
|
||||
Eot,
|
||||
/// OpenType font (font/otf)
|
||||
Otf,
|
||||
/// TrueType Font (font/ttf)
|
||||
Ttf,
|
||||
/// Web Open Font Format (font/woff)
|
||||
Woff,
|
||||
/// Web Open Font Format 2 (font/woff2)
|
||||
Woff2,
|
||||
|
||||
// MARK: Applications
|
||||
/// AbiWord document (application/x-abiword)
|
||||
Abiword,
|
||||
/// Amazon Kindle eBook format (application/vnd.amazon.ebook)
|
||||
Azw,
|
||||
/// CD audio (application/x-cdf)
|
||||
Cda,
|
||||
/// C-Shell script (application/x-csh)
|
||||
Csh,
|
||||
/// Microsoft Word (application/msword)
|
||||
Doc,
|
||||
/// Microsoft Word OpenXML (application/vnd.openxmlformats-officedocument.wordprocessingml.document)
|
||||
Docx,
|
||||
/// Electronic publication (application/epub+zip)
|
||||
Epub,
|
||||
/// iCalendar format (text/calendar)
|
||||
Ics,
|
||||
/// Apple Installer Package (application/vnd.apple.installer+xml)
|
||||
Mpkg,
|
||||
/// OpenDocument presentation (application/vnd.oasis.opendocument.presentation)
|
||||
Odp,
|
||||
/// OpenDocument spreadsheet (application/vnd.oasis.opendocument.spreadsheet)
|
||||
Ods,
|
||||
/// OpenDocument text document (application/vnd.oasis.opendocument.text)
|
||||
Odt,
|
||||
/// Hypertext Preprocessor (application/x-httpd-php)
|
||||
Php,
|
||||
/// Microsoft PowerPoint (application/vnd.ms-powerpoint)
|
||||
Ppt,
|
||||
/// Microsoft PowerPoint OpenXML (application/vnd.openxmlformats-officedocument.presentationml.presentation)
|
||||
Pptx,
|
||||
/// Bourne shell script (application/x-sh)
|
||||
Sh,
|
||||
/// Microsoft Visio (application/vnd.visio)
|
||||
Vsd,
|
||||
/// XHTML (application/xhtml+xml)
|
||||
Xhtml,
|
||||
/// Microsoft Excel (application/vnd.ms-excel)
|
||||
Xls,
|
||||
/// Microsoft Excel OpenXML (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)
|
||||
Xlsx,
|
||||
/// XUL (application/vnd.mozilla.xul+xml)
|
||||
Xul,
|
||||
}
|
||||
|
||||
// MARK: ser/de
|
||||
|
||||
/*
|
||||
impl utoipa::ToSchema for MimeType {
|
||||
fn name() -> std::borrow::Cow<'static, str> {
|
||||
std::borrow::Cow::Borrowed("MimeType")
|
||||
}
|
||||
}
|
||||
impl utoipa::PartialSchema for MimeType {
|
||||
fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
|
||||
utoipa::openapi::Schema::Object(
|
||||
utoipa::openapi::schema::ObjectBuilder::new()
|
||||
.schema_type(utoipa::openapi::schema::SchemaType::Type(Type::String))
|
||||
.description(Some(
|
||||
"A media type string (e.g., 'application/json', 'text/plain')",
|
||||
))
|
||||
.examples(Some("application/json"))
|
||||
.build(),
|
||||
)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
impl Serialize for MimeType {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for MimeType {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
Ok(MimeType::from_str(&s).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: misc
|
||||
//
|
||||
|
||||
impl Default for MimeType {
|
||||
fn default() -> Self {
|
||||
Self::Blob
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for MimeType {
|
||||
fn from(value: String) -> Self {
|
||||
Self::from_str(&value).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for MimeType {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::from_str(value).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&MimeType> for String {
|
||||
fn from(value: &MimeType) -> Self {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: fromstr
|
||||
//
|
||||
|
||||
impl MimeType {
|
||||
/// Parse a mimetype from a string that may contain
|
||||
/// whitespace or ";" parameters.
|
||||
///
|
||||
/// Parameters are discarded, write your own parser if you need them.
|
||||
pub fn from_header(s: &str) -> Result<Self, <Self as FromStr>::Err> {
|
||||
let s = s.trim();
|
||||
let semi = s.find(';').unwrap_or(s.len());
|
||||
let space = s.find(' ').unwrap_or(s.len());
|
||||
let limit = semi.min(space);
|
||||
let s = &s[0..limit];
|
||||
let s = s.trim();
|
||||
|
||||
return Self::from_str(s);
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for MimeType {
|
||||
type Err = std::convert::Infallible;
|
||||
|
||||
// Must match `display` below, but may provide other alternatives.
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Ok(match s {
|
||||
"application/octet-stream" => Self::Blob,
|
||||
|
||||
// Audio
|
||||
"audio/aac" => Self::Aac,
|
||||
"audio/flac" => Self::Flac,
|
||||
"audio/midi" | "audio/x-midi" => Self::Midi,
|
||||
"audio/mpeg" => Self::Mp3,
|
||||
"audio/ogg" => Self::Oga,
|
||||
"audio/wav" => Self::Wav,
|
||||
"audio/webm" => Self::Weba,
|
||||
|
||||
// Video
|
||||
"video/x-msvideo" => Self::Avi,
|
||||
"video/mp4" => Self::Mp4,
|
||||
"video/mpeg" => Self::Mpeg,
|
||||
"video/ogg" => Self::Ogv,
|
||||
"video/mp2t" => Self::Ts,
|
||||
"video/webm" => Self::WebmVideo,
|
||||
"video/3gpp" => Self::ThreeGp,
|
||||
"video/3gpp2" => Self::ThreeG2,
|
||||
|
||||
// Images
|
||||
"image/apng" => Self::Apng,
|
||||
"image/avif" => Self::Avif,
|
||||
"image/bmp" => Self::Bmp,
|
||||
"image/gif" => Self::Gif,
|
||||
"image/vnd.microsoft.icon" => Self::Ico,
|
||||
"image/jpeg" | "image/jpg" => Self::Jpg,
|
||||
"image/png" => Self::Png,
|
||||
"image/svg+xml" => Self::Svg,
|
||||
"image/tiff" => Self::Tiff,
|
||||
"image/webp" => Self::Webp,
|
||||
"image/qoi" => Self::Qoi,
|
||||
|
||||
// Text
|
||||
"text/plain" => Self::Text,
|
||||
"text/css" => Self::Css,
|
||||
"text/csv" => Self::Csv,
|
||||
"text/html" => Self::Html,
|
||||
"text/javascript" => Self::Javascript,
|
||||
"application/json" => Self::Json,
|
||||
"application/ld+json" => Self::JsonLd,
|
||||
"application/xml" | "text/xml" => Self::Xml,
|
||||
|
||||
// Documents
|
||||
"application/pdf" => Self::Pdf,
|
||||
"application/rtf" => Self::Rtf,
|
||||
|
||||
// Archives
|
||||
"application/x-freearc" => Self::Arc,
|
||||
"application/x-bzip" => Self::Bz,
|
||||
"application/x-bzip2" => Self::Bz2,
|
||||
"application/gzip" | "application/x-gzip" => Self::Gz,
|
||||
"application/java-archive" => Self::Jar,
|
||||
"application/ogg" => Self::Ogg,
|
||||
"application/vnd.rar" => Self::Rar,
|
||||
"application/x-7z-compressed" => Self::SevenZ,
|
||||
"application/x-tar" => Self::Tar,
|
||||
"application/zip" | "application/x-zip-compressed" => Self::Zip,
|
||||
|
||||
// Fonts
|
||||
"application/vnd.ms-fontobject" => Self::Eot,
|
||||
"font/otf" => Self::Otf,
|
||||
"font/ttf" => Self::Ttf,
|
||||
"font/woff" => Self::Woff,
|
||||
"font/woff2" => Self::Woff2,
|
||||
|
||||
// Applications
|
||||
"application/x-abiword" => Self::Abiword,
|
||||
"application/vnd.amazon.ebook" => Self::Azw,
|
||||
"application/x-cdf" => Self::Cda,
|
||||
"application/x-csh" => Self::Csh,
|
||||
"application/msword" => Self::Doc,
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document" => Self::Docx,
|
||||
"application/epub+zip" => Self::Epub,
|
||||
"text/calendar" => Self::Ics,
|
||||
"application/vnd.apple.installer+xml" => Self::Mpkg,
|
||||
"application/vnd.oasis.opendocument.presentation" => Self::Odp,
|
||||
"application/vnd.oasis.opendocument.spreadsheet" => Self::Ods,
|
||||
"application/vnd.oasis.opendocument.text" => Self::Odt,
|
||||
"application/x-httpd-php" => Self::Php,
|
||||
"application/vnd.ms-powerpoint" => Self::Ppt,
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => {
|
||||
Self::Pptx
|
||||
}
|
||||
"application/x-sh" => Self::Sh,
|
||||
"application/vnd.visio" => Self::Vsd,
|
||||
"application/xhtml+xml" => Self::Xhtml,
|
||||
"application/vnd.ms-excel" => Self::Xls,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => Self::Xlsx,
|
||||
"application/vnd.mozilla.xul+xml" => Self::Xul,
|
||||
|
||||
_ => {
|
||||
debug!(message = "Encountered unknown mimetype", mime_string = s);
|
||||
Self::Other(s.into())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: display
|
||||
//
|
||||
|
||||
impl Display for MimeType {
|
||||
/// Get a string representation of this mimetype.
|
||||
///
|
||||
/// The following always holds:
|
||||
/// ```rust
|
||||
/// # use toolbox::mime::MimeType;
|
||||
/// # let x = MimeType::Blob;
|
||||
/// assert_eq!(MimeType::from(x.to_string()), x);
|
||||
/// ```
|
||||
///
|
||||
/// The following might not hold:
|
||||
/// ```rust
|
||||
/// # use toolbox::mime::MimeType;
|
||||
/// # let y = "application/custom";
|
||||
/// // MimeType::from(y).to_string() may not equal y
|
||||
/// ```
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Blob => write!(f, "application/octet-stream"),
|
||||
|
||||
// Audio
|
||||
Self::Aac => write!(f, "audio/aac"),
|
||||
Self::Flac => write!(f, "audio/flac"),
|
||||
Self::Midi => write!(f, "audio/midi"),
|
||||
Self::Mp3 => write!(f, "audio/mpeg"),
|
||||
Self::Oga => write!(f, "audio/ogg"),
|
||||
Self::Opus => write!(f, "audio/ogg"),
|
||||
Self::Wav => write!(f, "audio/wav"),
|
||||
Self::Weba => write!(f, "audio/webm"),
|
||||
|
||||
// Video
|
||||
Self::Avi => write!(f, "video/x-msvideo"),
|
||||
Self::Mp4 => write!(f, "video/mp4"),
|
||||
Self::Mpeg => write!(f, "video/mpeg"),
|
||||
Self::Ogv => write!(f, "video/ogg"),
|
||||
Self::Ts => write!(f, "video/mp2t"),
|
||||
Self::WebmVideo => write!(f, "video/webm"),
|
||||
Self::ThreeGp => write!(f, "video/3gpp"),
|
||||
Self::ThreeG2 => write!(f, "video/3gpp2"),
|
||||
|
||||
// Images
|
||||
Self::Apng => write!(f, "image/apng"),
|
||||
Self::Avif => write!(f, "image/avif"),
|
||||
Self::Bmp => write!(f, "image/bmp"),
|
||||
Self::Gif => write!(f, "image/gif"),
|
||||
Self::Ico => write!(f, "image/vnd.microsoft.icon"),
|
||||
Self::Jpg => write!(f, "image/jpeg"),
|
||||
Self::Png => write!(f, "image/png"),
|
||||
Self::Svg => write!(f, "image/svg+xml"),
|
||||
Self::Tiff => write!(f, "image/tiff"),
|
||||
Self::Webp => write!(f, "image/webp"),
|
||||
Self::Qoi => write!(f, "image/qoi"),
|
||||
|
||||
// Text
|
||||
Self::Text => write!(f, "text/plain"),
|
||||
Self::Css => write!(f, "text/css"),
|
||||
Self::Csv => write!(f, "text/csv"),
|
||||
Self::Html => write!(f, "text/html"),
|
||||
Self::Javascript => write!(f, "text/javascript"),
|
||||
Self::Json => write!(f, "application/json"),
|
||||
Self::JsonLd => write!(f, "application/ld+json"),
|
||||
Self::Xml => write!(f, "application/xml"),
|
||||
|
||||
// Documents
|
||||
Self::Pdf => write!(f, "application/pdf"),
|
||||
Self::Rtf => write!(f, "application/rtf"),
|
||||
|
||||
// Archives
|
||||
Self::Arc => write!(f, "application/x-freearc"),
|
||||
Self::Bz => write!(f, "application/x-bzip"),
|
||||
Self::Bz2 => write!(f, "application/x-bzip2"),
|
||||
Self::Gz => write!(f, "application/gzip"),
|
||||
Self::Jar => write!(f, "application/java-archive"),
|
||||
Self::Ogg => write!(f, "application/ogg"),
|
||||
Self::Rar => write!(f, "application/vnd.rar"),
|
||||
Self::SevenZ => write!(f, "application/x-7z-compressed"),
|
||||
Self::Tar => write!(f, "application/x-tar"),
|
||||
Self::Zip => write!(f, "application/zip"),
|
||||
|
||||
// Fonts
|
||||
Self::Eot => write!(f, "application/vnd.ms-fontobject"),
|
||||
Self::Otf => write!(f, "font/otf"),
|
||||
Self::Ttf => write!(f, "font/ttf"),
|
||||
Self::Woff => write!(f, "font/woff"),
|
||||
Self::Woff2 => write!(f, "font/woff2"),
|
||||
|
||||
// Applications
|
||||
Self::Abiword => write!(f, "application/x-abiword"),
|
||||
Self::Azw => write!(f, "application/vnd.amazon.ebook"),
|
||||
Self::Cda => write!(f, "application/x-cdf"),
|
||||
Self::Csh => write!(f, "application/x-csh"),
|
||||
Self::Doc => write!(f, "application/msword"),
|
||||
Self::Docx => write!(
|
||||
f,
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
),
|
||||
Self::Epub => write!(f, "application/epub+zip"),
|
||||
Self::Ics => write!(f, "text/calendar"),
|
||||
Self::Mpkg => write!(f, "application/vnd.apple.installer+xml"),
|
||||
Self::Odp => write!(f, "application/vnd.oasis.opendocument.presentation"),
|
||||
Self::Ods => write!(f, "application/vnd.oasis.opendocument.spreadsheet"),
|
||||
Self::Odt => write!(f, "application/vnd.oasis.opendocument.text"),
|
||||
Self::Php => write!(f, "application/x-httpd-php"),
|
||||
Self::Ppt => write!(f, "application/vnd.ms-powerpoint"),
|
||||
Self::Pptx => write!(
|
||||
f,
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
||||
),
|
||||
Self::Sh => write!(f, "application/x-sh"),
|
||||
Self::Vsd => write!(f, "application/vnd.visio"),
|
||||
Self::Xhtml => write!(f, "application/xhtml+xml"),
|
||||
Self::Xls => write!(f, "application/vnd.ms-excel"),
|
||||
Self::Xlsx => write!(
|
||||
f,
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
),
|
||||
Self::Xul => write!(f, "application/vnd.mozilla.xul+xml"),
|
||||
|
||||
Self::Other(x) => write!(f, "{x}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MimeType {
|
||||
//
|
||||
// MARK: from extension
|
||||
//
|
||||
|
||||
/// Try to guess a file's mime type from its extension.
|
||||
/// `ext` should NOT start with a dot.
|
||||
pub fn from_extension(ext: &str) -> Option<Self> {
|
||||
Some(match ext {
|
||||
// Audio
|
||||
"aac" => Self::Aac,
|
||||
"flac" => Self::Flac,
|
||||
"mid" | "midi" => Self::Midi,
|
||||
"mp3" => Self::Mp3,
|
||||
"oga" => Self::Oga,
|
||||
"opus" => Self::Opus,
|
||||
"wav" => Self::Wav,
|
||||
"weba" => Self::Weba,
|
||||
|
||||
// Video
|
||||
"avi" => Self::Avi,
|
||||
"mp4" => Self::Mp4,
|
||||
"mpeg" => Self::Mpeg,
|
||||
"ogv" => Self::Ogv,
|
||||
"ts" => Self::Ts,
|
||||
"webm" => Self::WebmVideo,
|
||||
"3gp" => Self::ThreeGp,
|
||||
"3g2" => Self::ThreeG2,
|
||||
|
||||
// Images
|
||||
"apng" => Self::Apng,
|
||||
"avif" => Self::Avif,
|
||||
"bmp" => Self::Bmp,
|
||||
"gif" => Self::Gif,
|
||||
"ico" => Self::Ico,
|
||||
"jpg" | "jpeg" => Self::Jpg,
|
||||
"png" => Self::Png,
|
||||
"svg" => Self::Svg,
|
||||
"tif" | "tiff" => Self::Tiff,
|
||||
"webp" => Self::Webp,
|
||||
"qoi" => Self::Qoi,
|
||||
|
||||
// Text
|
||||
"txt" => Self::Text,
|
||||
"css" => Self::Css,
|
||||
"csv" => Self::Csv,
|
||||
"htm" | "html" => Self::Html,
|
||||
"js" | "mjs" => Self::Javascript,
|
||||
"json" => Self::Json,
|
||||
"jsonld" => Self::JsonLd,
|
||||
"xml" => Self::Xml,
|
||||
|
||||
// Documents
|
||||
"pdf" => Self::Pdf,
|
||||
"rtf" => Self::Rtf,
|
||||
|
||||
// Archives
|
||||
"arc" => Self::Arc,
|
||||
"bz" => Self::Bz,
|
||||
"bz2" => Self::Bz2,
|
||||
"gz" => Self::Gz,
|
||||
"jar" => Self::Jar,
|
||||
"ogx" => Self::Ogg,
|
||||
"rar" => Self::Rar,
|
||||
"7z" => Self::SevenZ,
|
||||
"tar" => Self::Tar,
|
||||
"zip" => Self::Zip,
|
||||
|
||||
// Fonts
|
||||
"eot" => Self::Eot,
|
||||
"otf" => Self::Otf,
|
||||
"ttf" => Self::Ttf,
|
||||
"woff" => Self::Woff,
|
||||
"woff2" => Self::Woff2,
|
||||
|
||||
// Applications
|
||||
"abw" => Self::Abiword,
|
||||
"azw" => Self::Azw,
|
||||
"cda" => Self::Cda,
|
||||
"csh" => Self::Csh,
|
||||
"doc" => Self::Doc,
|
||||
"docx" => Self::Docx,
|
||||
"epub" => Self::Epub,
|
||||
"ics" => Self::Ics,
|
||||
"mpkg" => Self::Mpkg,
|
||||
"odp" => Self::Odp,
|
||||
"ods" => Self::Ods,
|
||||
"odt" => Self::Odt,
|
||||
"php" => Self::Php,
|
||||
"ppt" => Self::Ppt,
|
||||
"pptx" => Self::Pptx,
|
||||
"sh" => Self::Sh,
|
||||
"vsd" => Self::Vsd,
|
||||
"xhtml" => Self::Xhtml,
|
||||
"xls" => Self::Xls,
|
||||
"xlsx" => Self::Xlsx,
|
||||
"xul" => Self::Xul,
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: to extension
|
||||
//
|
||||
|
||||
/// Get the extension we use for files with this type.
|
||||
/// Never includes a dot.
|
||||
pub fn extension(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Blob => None,
|
||||
Self::Other(_) => None,
|
||||
|
||||
// Audio
|
||||
Self::Aac => Some("aac"),
|
||||
Self::Flac => Some("flac"),
|
||||
Self::Midi => Some("midi"),
|
||||
Self::Mp3 => Some("mp3"),
|
||||
Self::Oga => Some("oga"),
|
||||
Self::Opus => Some("opus"),
|
||||
Self::Wav => Some("wav"),
|
||||
Self::Weba => Some("weba"),
|
||||
|
||||
// Video
|
||||
Self::Avi => Some("avi"),
|
||||
Self::Mp4 => Some("mp4"),
|
||||
Self::Mpeg => Some("mpeg"),
|
||||
Self::Ogv => Some("ogv"),
|
||||
Self::Ts => Some("ts"),
|
||||
Self::WebmVideo => Some("webm"),
|
||||
Self::ThreeGp => Some("3gp"),
|
||||
Self::ThreeG2 => Some("3g2"),
|
||||
|
||||
// Images
|
||||
Self::Apng => Some("apng"),
|
||||
Self::Avif => Some("avif"),
|
||||
Self::Bmp => Some("bmp"),
|
||||
Self::Gif => Some("gif"),
|
||||
Self::Ico => Some("ico"),
|
||||
Self::Jpg => Some("jpg"),
|
||||
Self::Png => Some("png"),
|
||||
Self::Svg => Some("svg"),
|
||||
Self::Tiff => Some("tiff"),
|
||||
Self::Webp => Some("webp"),
|
||||
Self::Qoi => Some("qoi"),
|
||||
|
||||
// Text
|
||||
Self::Text => Some("txt"),
|
||||
Self::Css => Some("css"),
|
||||
Self::Csv => Some("csv"),
|
||||
Self::Html => Some("html"),
|
||||
Self::Javascript => Some("js"),
|
||||
Self::Json => Some("json"),
|
||||
Self::JsonLd => Some("jsonld"),
|
||||
Self::Xml => Some("xml"),
|
||||
|
||||
// Documents
|
||||
Self::Pdf => Some("pdf"),
|
||||
Self::Rtf => Some("rtf"),
|
||||
|
||||
// Archives
|
||||
Self::Arc => Some("arc"),
|
||||
Self::Bz => Some("bz"),
|
||||
Self::Bz2 => Some("bz2"),
|
||||
Self::Gz => Some("gz"),
|
||||
Self::Jar => Some("jar"),
|
||||
Self::Ogg => Some("ogx"),
|
||||
Self::Rar => Some("rar"),
|
||||
Self::SevenZ => Some("7z"),
|
||||
Self::Tar => Some("tar"),
|
||||
Self::Zip => Some("zip"),
|
||||
|
||||
// Fonts
|
||||
Self::Eot => Some("eot"),
|
||||
Self::Otf => Some("otf"),
|
||||
Self::Ttf => Some("ttf"),
|
||||
Self::Woff => Some("woff"),
|
||||
Self::Woff2 => Some("woff2"),
|
||||
|
||||
// Applications
|
||||
Self::Abiword => Some("abw"),
|
||||
Self::Azw => Some("azw"),
|
||||
Self::Cda => Some("cda"),
|
||||
Self::Csh => Some("csh"),
|
||||
Self::Doc => Some("doc"),
|
||||
Self::Docx => Some("docx"),
|
||||
Self::Epub => Some("epub"),
|
||||
Self::Ics => Some("ics"),
|
||||
Self::Mpkg => Some("mpkg"),
|
||||
Self::Odp => Some("odp"),
|
||||
Self::Ods => Some("ods"),
|
||||
Self::Odt => Some("odt"),
|
||||
Self::Php => Some("php"),
|
||||
Self::Ppt => Some("ppt"),
|
||||
Self::Pptx => Some("pptx"),
|
||||
Self::Sh => Some("sh"),
|
||||
Self::Vsd => Some("vsd"),
|
||||
Self::Xhtml => Some("xhtml"),
|
||||
Self::Xls => Some("xls"),
|
||||
Self::Xlsx => Some("xlsx"),
|
||||
Self::Xul => Some("xul"),
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: is_text
|
||||
//
|
||||
|
||||
/// Returns true if this MIME type is always plain text.
|
||||
pub fn is_text(&self) -> bool {
|
||||
match self {
|
||||
// Text types
|
||||
Self::Text => true,
|
||||
Self::Css => true,
|
||||
Self::Csv => true,
|
||||
Self::Html => true,
|
||||
Self::Javascript => true,
|
||||
Self::Json => true,
|
||||
Self::JsonLd => true,
|
||||
Self::Xml => true,
|
||||
Self::Svg => true,
|
||||
Self::Ics => true,
|
||||
Self::Xhtml => true,
|
||||
|
||||
// Script types
|
||||
Self::Csh => true,
|
||||
Self::Php => true,
|
||||
Self::Sh => true,
|
||||
|
||||
// All other types are not plain text
|
||||
Self::Other(_) => false,
|
||||
Self::Blob => false,
|
||||
|
||||
// Audio
|
||||
Self::Aac => false,
|
||||
Self::Flac => false,
|
||||
Self::Midi => false,
|
||||
Self::Mp3 => false,
|
||||
Self::Oga => false,
|
||||
Self::Opus => false,
|
||||
Self::Wav => false,
|
||||
Self::Weba => false,
|
||||
|
||||
// Video
|
||||
Self::Avi => false,
|
||||
Self::Mp4 => false,
|
||||
Self::Mpeg => false,
|
||||
Self::Ogv => false,
|
||||
Self::Ts => false,
|
||||
Self::WebmVideo => false,
|
||||
Self::ThreeGp => false,
|
||||
Self::ThreeG2 => false,
|
||||
|
||||
// Images
|
||||
Self::Apng => false,
|
||||
Self::Avif => false,
|
||||
Self::Bmp => false,
|
||||
Self::Gif => false,
|
||||
Self::Ico => false,
|
||||
Self::Jpg => false,
|
||||
Self::Png => false,
|
||||
Self::Qoi => false,
|
||||
Self::Tiff => false,
|
||||
Self::Webp => false,
|
||||
|
||||
// Documents
|
||||
Self::Pdf => false,
|
||||
Self::Rtf => false,
|
||||
|
||||
// Archives
|
||||
Self::Arc => false,
|
||||
Self::Bz => false,
|
||||
Self::Bz2 => false,
|
||||
Self::Gz => false,
|
||||
Self::Jar => false,
|
||||
Self::Ogg => false,
|
||||
Self::Rar => false,
|
||||
Self::SevenZ => false,
|
||||
Self::Tar => false,
|
||||
Self::Zip => false,
|
||||
|
||||
// Fonts
|
||||
Self::Eot => false,
|
||||
Self::Otf => false,
|
||||
Self::Ttf => false,
|
||||
Self::Woff => false,
|
||||
Self::Woff2 => false,
|
||||
|
||||
// Applications
|
||||
Self::Abiword => false,
|
||||
Self::Azw => false,
|
||||
Self::Cda => false,
|
||||
Self::Doc => false,
|
||||
Self::Docx => false,
|
||||
Self::Epub => false,
|
||||
Self::Mpkg => false,
|
||||
Self::Odp => false,
|
||||
Self::Ods => false,
|
||||
Self::Odt => false,
|
||||
Self::Ppt => false,
|
||||
Self::Pptx => false,
|
||||
Self::Vsd => false,
|
||||
Self::Xls => false,
|
||||
Self::Xlsx => false,
|
||||
Self::Xul => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
/// Normalize a domain. This does the following:
|
||||
/// - removes protocol prefixes
|
||||
/// - removes leading `www`
|
||||
/// - removes query params and path segments.
|
||||
///
|
||||
/// This function is for roach, and should exactly match the ts implementation.
|
||||
///
|
||||
/// ## Examples:
|
||||
/// ```
|
||||
/// # use toolbox::misc::normalize_domain;
|
||||
/// assert_eq!("domain.com", normalize_domain("domain.com"));
|
||||
/// assert_eq!("domain.com", normalize_domain("domain.com/"));
|
||||
/// assert_eq!("domain.com", normalize_domain("domain.com/en/us"));
|
||||
/// assert_eq!("domain.com", normalize_domain("domain.com/?key=val"));
|
||||
/// assert_eq!("domain.com", normalize_domain("www.domain.com"));
|
||||
/// assert_eq!("domain.com", normalize_domain("https://www.domain.com"));
|
||||
/// assert_eq!("us.domain.com", normalize_domain("us.domain.com"));
|
||||
/// ```
|
||||
pub fn normalize_domain(domain: &str) -> &str {
|
||||
let mut domain = domain.strip_prefix("http://").unwrap_or(domain);
|
||||
domain = domain.strip_prefix("https://").unwrap_or(domain);
|
||||
domain = domain.strip_prefix("www.").unwrap_or(domain);
|
||||
domain = domain.find("/").map_or(domain, |x| &domain[0..x]);
|
||||
|
||||
return domain;
|
||||
}
|
||||
|
||||
/*
|
||||
pub fn random_string(length: usize) -> String {
|
||||
rand::rng()
|
||||
.sample_iter(&Alphanumeric)
|
||||
.take(length)
|
||||
.map(char::from)
|
||||
.collect()
|
||||
}
|
||||
*/
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "macro-sass"
|
||||
version = { workspace = true }
|
||||
rust-version = { workspace = true }
|
||||
edition = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
syn = { workspace = true }
|
||||
quote = { workspace = true }
|
||||
grass = { workspace = true }
|
||||
@@ -1,149 +0,0 @@
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use std::path::PathBuf;
|
||||
use syn::{LitStr, parse_macro_input};
|
||||
|
||||
/// A macro for parsing Sass/SCSS files at compile time.
|
||||
///
|
||||
/// This macro takes a file path to a Sass/SCSS file, compiles it to CSS at compile time
|
||||
/// using the `grass` compiler, and returns the resulting CSS as a `&'static str`.
|
||||
///
|
||||
/// # Behavior
|
||||
///
|
||||
/// Similar to `include_str!`, this macro:
|
||||
/// - Reads the specified file at compile time
|
||||
/// - Compiles the Sass/SCSS to CSS using `grass::from_path()` with default options
|
||||
/// - Handles `@import` and `@use` directives, resolving imported files relative to the main file
|
||||
/// - Embeds the resulting CSS string in the binary
|
||||
/// - Returns a `&'static str` containing the compiled CSS
|
||||
///
|
||||
/// # Syntax
|
||||
///
|
||||
/// ```notrust
|
||||
/// sass!("path/to/file.scss")
|
||||
/// ```
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// - A string literal containing the path to the Sass/SCSS file (relative to the crate root)
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```notrust
|
||||
/// // Relative to crate root: looks for src/routes/css/main.scss
|
||||
/// const MY_STYLES: &str = sass!("src/routes/css/main.scss");
|
||||
///
|
||||
/// // Use in HTML generation
|
||||
/// html! {
|
||||
/// style { (PreEscaped(MY_STYLES)) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// # Import Support
|
||||
///
|
||||
/// The macro fully supports Sass imports and uses:
|
||||
/// ```notrust
|
||||
/// // main.scss
|
||||
/// @import "variables";
|
||||
/// @use "mixins";
|
||||
///
|
||||
/// .button {
|
||||
/// color: $primary-color;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// All imported files are resolved relative to the location of the main Sass file.
|
||||
///
|
||||
/// # Compile-time vs Runtime
|
||||
///
|
||||
/// Instead of this runtime code:
|
||||
/// ```notrust
|
||||
/// let css = grass::from_path(
|
||||
/// "styles.scss",
|
||||
/// &grass::Options::default()
|
||||
/// ).unwrap();
|
||||
/// ```
|
||||
///
|
||||
/// You can use:
|
||||
/// ```notrust
|
||||
/// const CSS: &str = sass!("styles.scss");
|
||||
/// ```
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This macro will cause a compile error if:
|
||||
/// - The specified file does not exist
|
||||
/// - The file path is invalid
|
||||
/// - The Sass/SCSS file contains syntax errors
|
||||
/// - Any imported files cannot be found
|
||||
/// - The grass compiler fails for any reason
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// The file path is relative to the crate root (where `Cargo.toml` is located), determined
|
||||
/// by the `CARGO_MANIFEST_DIR` environment variable. This is similar to how `include!()` works
|
||||
/// but differs from `include_str!()` which is relative to the current file.
|
||||
#[proc_macro]
|
||||
pub fn sass(input: TokenStream) -> TokenStream {
|
||||
let input_lit = parse_macro_input!(input as LitStr);
|
||||
let file_path = PathBuf::from(input_lit.value());
|
||||
|
||||
// Not stable yet, we have to use crate-relative paths :(
|
||||
//let span = proc_macro::Span::call_site();
|
||||
//let source_file = span.source_file();
|
||||
//let path: PathBuf = source_file.path();
|
||||
|
||||
// Use a combination of include_str! and grass compilation
|
||||
// include_str! handles the relative path resolution for us
|
||||
// We generate code that uses include_str! at the user's call site
|
||||
// and compiles it at macro expansion time
|
||||
|
||||
// First, try to read and compile the file at macro expansion time
|
||||
// The path is interpreted relative to CARGO_MANIFEST_DIR
|
||||
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_owned());
|
||||
let full_path = std::path::Path::new(&manifest_dir).join(&file_path);
|
||||
|
||||
let css = match grass::from_path(&full_path, &grass::Options::default()) {
|
||||
Ok(css) => css,
|
||||
Err(e) => {
|
||||
return syn::Error::new(
|
||||
input_lit.span(),
|
||||
format!(
|
||||
"Failed to compile Sass file '{}': {}",
|
||||
file_path.display(),
|
||||
e,
|
||||
),
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
};
|
||||
|
||||
// Generate code that returns the compiled CSS as a string literal
|
||||
let expanded = quote! {
|
||||
#css
|
||||
};
|
||||
|
||||
TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn sass_str(input: TokenStream) -> TokenStream {
|
||||
let input_lit = parse_macro_input!(input as LitStr);
|
||||
let sass_str = input_lit.value();
|
||||
|
||||
let css = match grass::from_string(&sass_str, &grass::Options::default()) {
|
||||
Ok(css) => css,
|
||||
Err(e) => {
|
||||
return syn::Error::new(
|
||||
input_lit.span(),
|
||||
format!("Failed to compile Sass string: {e}."),
|
||||
)
|
||||
.to_compile_error()
|
||||
.into();
|
||||
}
|
||||
};
|
||||
|
||||
let expanded = quote! { #css };
|
||||
TokenStream::from(expanded)
|
||||
}
|
||||
@@ -9,13 +9,11 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
libservice = { workspace = true }
|
||||
macro-sass = { workspace = true }
|
||||
toolbox = { workspace = true }
|
||||
page = { workspace = true }
|
||||
|
||||
md-footnote = { workspace = true }
|
||||
|
||||
markdown-it = { workspace = true }
|
||||
grass = { workspace = true }
|
||||
axum = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
maud = { workspace = true }
|
||||
@@ -29,3 +27,4 @@ serde = { workspace = true }
|
||||
reqwest = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tower-http = { workspace = true }
|
||||
servable = { workspace = true }
|
||||
|
||||
BIN
crates/service/service-webpage/assets/lockhart.pdf
Normal file
BIN
crates/service/service-webpage/assets/lockhart.pdf
Normal file
Binary file not shown.
@@ -1,145 +0,0 @@
|
||||
ul {
|
||||
list-style: none;
|
||||
margin-top: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
li {
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
li p {
|
||||
margin-bottom: 0.2rem;
|
||||
}
|
||||
|
||||
/* Bonus space after last li */
|
||||
//li:last-child {
|
||||
// margin-bottom: 3rem;
|
||||
//}
|
||||
|
||||
ul li::marker {
|
||||
content: "> ";
|
||||
color: var(--metaColor);
|
||||
}
|
||||
|
||||
ul li:hover::marker {
|
||||
content: ">> ";
|
||||
font-weight: 1000;
|
||||
color: var(--linkColor);
|
||||
transition: 100ms;
|
||||
}
|
||||
|
||||
|
||||
.titleList li {
|
||||
margin-bottom: .75rem;
|
||||
}
|
||||
|
||||
|
||||
blockquote {
|
||||
border-left: .5rem solid var(--metaColor);
|
||||
margin: 1rem;
|
||||
padding: 0 0 0 1rem
|
||||
}
|
||||
|
||||
|
||||
textarea {
|
||||
border: 2px dotted;
|
||||
outline: 0;
|
||||
resize: none;
|
||||
overflow: auto;
|
||||
background-color: var(--bgColor)
|
||||
}
|
||||
|
||||
|
||||
|
||||
pre .wrap {
|
||||
overflow: hidden;
|
||||
overflow-wrap: break-word;
|
||||
word-break: break-all;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
pre :not(.wrap) {
|
||||
padding: 1rem;
|
||||
font-style: monospace;
|
||||
white-space: pre;
|
||||
overflow: scroll;
|
||||
display: block;
|
||||
border: solid .2rem transparent;
|
||||
transition: 150ms;
|
||||
counter-reset: line;
|
||||
}
|
||||
|
||||
pre:hover {
|
||||
border: solid .2rem var(--lightBgColor);
|
||||
}
|
||||
|
||||
pre span:first-of-type:before {
|
||||
border-top: 1px dashed var(--lightBgColor);
|
||||
}
|
||||
|
||||
pre span:before {
|
||||
counter-increment: line;
|
||||
content: counter(line, decimal-leading-zero);
|
||||
display: inline-block;
|
||||
border-right: 1px solid var(--lightBgColor);
|
||||
border-bottom: 1px dashed var(--lightBgColor);
|
||||
padding: 0 .5em;
|
||||
margin-right: .5em;
|
||||
color: #888
|
||||
}
|
||||
|
||||
p code,
|
||||
li code,
|
||||
div code {
|
||||
padding: .2rem .4rem .2rem .4rem;
|
||||
font-size: 85%;
|
||||
border-radius: .3rem;
|
||||
color: var(--codeFgColor);
|
||||
background-color: var(--codeBgColor);
|
||||
}
|
||||
|
||||
pre code {
|
||||
padding: 0;
|
||||
border-radius: 0;
|
||||
color: inherit;
|
||||
background-color: inherit;
|
||||
}
|
||||
|
||||
|
||||
table {
|
||||
table-layout: fixed;
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: none;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
margin-bottom: 1rem;
|
||||
line-height: 1.1
|
||||
}
|
||||
|
||||
thead th:first-child {
|
||||
width: 20%
|
||||
}
|
||||
|
||||
td,
|
||||
th {
|
||||
text-align: left
|
||||
}
|
||||
|
||||
th {
|
||||
font-weight: 400
|
||||
}
|
||||
|
||||
|
||||
td,
|
||||
th {
|
||||
padding: .5rem;
|
||||
border: dashed .1rem var(--metaColor)
|
||||
}
|
||||
|
||||
.metaData,
|
||||
hr,
|
||||
textarea {
|
||||
color: var(--metaColor)
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
// animating icons
|
||||
// --------------------------
|
||||
|
||||
.#{$fa-css-prefix}-beat {
|
||||
animation-name: #{$fa-css-prefix}-beat;
|
||||
animation-delay: var(--#{$fa-css-prefix}-animation-delay, 0s);
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 1s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, ease-in-out);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-bounce {
|
||||
animation-name: #{$fa-css-prefix}-bounce;
|
||||
animation-delay: var(--#{$fa-css-prefix}-animation-delay, 0s);
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 1s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, cubic-bezier(0.280, 0.840, 0.420, 1));
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-fade {
|
||||
animation-name: #{$fa-css-prefix}-fade;
|
||||
animation-delay: var(--#{$fa-css-prefix}-animation-delay, 0s);
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 1s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, cubic-bezier(.4,0,.6,1));
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-beat-fade {
|
||||
animation-name: #{$fa-css-prefix}-beat-fade;
|
||||
animation-delay: var(--#{$fa-css-prefix}-animation-delay, 0s);
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 1s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, cubic-bezier(.4,0,.6,1));
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-flip {
|
||||
animation-name: #{$fa-css-prefix}-flip;
|
||||
animation-delay: var(--#{$fa-css-prefix}-animation-delay, 0s);
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 1s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, ease-in-out);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-shake {
|
||||
animation-name: #{$fa-css-prefix}-shake;
|
||||
animation-delay: var(--#{$fa-css-prefix}-animation-delay, 0s);
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 1s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, linear);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-spin {
|
||||
animation-name: #{$fa-css-prefix}-spin;
|
||||
animation-delay: var(--#{$fa-css-prefix}-animation-delay, 0s);
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 2s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, linear);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-spin-reverse {
|
||||
--#{$fa-css-prefix}-animation-direction: reverse;
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-pulse,
|
||||
.#{$fa-css-prefix}-spin-pulse {
|
||||
animation-name: #{$fa-css-prefix}-spin;
|
||||
animation-direction: var(--#{$fa-css-prefix}-animation-direction, normal);
|
||||
animation-duration: var(--#{$fa-css-prefix}-animation-duration, 1s);
|
||||
animation-iteration-count: var(--#{$fa-css-prefix}-animation-iteration-count, infinite);
|
||||
animation-timing-function: var(--#{$fa-css-prefix}-animation-timing, steps(8));
|
||||
}
|
||||
|
||||
// if agent or operating system prefers reduced motion, disable animations
|
||||
// see: https://www.smashingmagazine.com/2020/09/design-reduced-motion-sensitivities/
|
||||
// see: https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.#{$fa-css-prefix}-beat,
|
||||
.#{$fa-css-prefix}-bounce,
|
||||
.#{$fa-css-prefix}-fade,
|
||||
.#{$fa-css-prefix}-beat-fade,
|
||||
.#{$fa-css-prefix}-flip,
|
||||
.#{$fa-css-prefix}-pulse,
|
||||
.#{$fa-css-prefix}-shake,
|
||||
.#{$fa-css-prefix}-spin,
|
||||
.#{$fa-css-prefix}-spin-pulse {
|
||||
animation-delay: -1ms;
|
||||
animation-duration: 1ms;
|
||||
animation-iteration-count: 1;
|
||||
transition-delay: 0s;
|
||||
transition-duration: 0s;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes #{$fa-css-prefix}-beat {
|
||||
0%, 90% { transform: scale(1); }
|
||||
45% { transform: scale(var(--#{$fa-css-prefix}-beat-scale, 1.25)); }
|
||||
}
|
||||
|
||||
@keyframes #{$fa-css-prefix}-bounce {
|
||||
0% { transform: scale(1,1) translateY(0); }
|
||||
10% { transform: scale(var(--#{$fa-css-prefix}-bounce-start-scale-x, 1.1),var(--#{$fa-css-prefix}-bounce-start-scale-y, 0.9)) translateY(0); }
|
||||
30% { transform: scale(var(--#{$fa-css-prefix}-bounce-jump-scale-x, 0.9),var(--#{$fa-css-prefix}-bounce-jump-scale-y, 1.1)) translateY(var(--#{$fa-css-prefix}-bounce-height, -0.5em)); }
|
||||
50% { transform: scale(var(--#{$fa-css-prefix}-bounce-land-scale-x, 1.05),var(--#{$fa-css-prefix}-bounce-land-scale-y, 0.95)) translateY(0); }
|
||||
57% { transform: scale(1,1) translateY(var(--#{$fa-css-prefix}-bounce-rebound, -0.125em)); }
|
||||
64% { transform: scale(1,1) translateY(0); }
|
||||
100% { transform: scale(1,1) translateY(0); }
|
||||
}
|
||||
|
||||
@keyframes #{$fa-css-prefix}-fade {
|
||||
50% { opacity: var(--#{$fa-css-prefix}-fade-opacity, 0.4); }
|
||||
}
|
||||
|
||||
@keyframes #{$fa-css-prefix}-beat-fade {
|
||||
0%, 100% {
|
||||
opacity: var(--#{$fa-css-prefix}-beat-fade-opacity, 0.4);
|
||||
transform: scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
transform: scale(var(--#{$fa-css-prefix}-beat-fade-scale, 1.125));
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes #{$fa-css-prefix}-flip {
|
||||
50% {
|
||||
transform: rotate3d(var(--#{$fa-css-prefix}-flip-x, 0), var(--#{$fa-css-prefix}-flip-y, 1), var(--#{$fa-css-prefix}-flip-z, 0), var(--#{$fa-css-prefix}-flip-angle, -180deg));
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes #{$fa-css-prefix}-shake {
|
||||
0% { transform: rotate(-15deg); }
|
||||
4% { transform: rotate(15deg); }
|
||||
8%, 24% { transform: rotate(-18deg); }
|
||||
12%, 28% { transform: rotate(18deg); }
|
||||
16% { transform: rotate(-22deg); }
|
||||
20% { transform: rotate(22deg); }
|
||||
32% { transform: rotate(-12deg); }
|
||||
36% { transform: rotate(12deg); }
|
||||
40%, 100% { transform: rotate(0deg); }
|
||||
}
|
||||
|
||||
@keyframes #{$fa-css-prefix}-spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
// bordered + pulled icons
|
||||
// -------------------------
|
||||
|
||||
.#{$fa-css-prefix}-border {
|
||||
border-color: var(--#{$fa-css-prefix}-border-color, #{$fa-border-color});
|
||||
border-radius: var(--#{$fa-css-prefix}-border-radius, #{$fa-border-radius});
|
||||
border-style: var(--#{$fa-css-prefix}-border-style, #{$fa-border-style});
|
||||
border-width: var(--#{$fa-css-prefix}-border-width, #{$fa-border-width});
|
||||
padding: var(--#{$fa-css-prefix}-border-padding, #{$fa-border-padding});
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-pull-left {
|
||||
float: left;
|
||||
margin-right: var(--#{$fa-css-prefix}-pull-margin, #{$fa-pull-margin});
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-pull-right {
|
||||
float: right;
|
||||
margin-left: var(--#{$fa-css-prefix}-pull-margin, #{$fa-pull-margin});
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
// base icon class definition
|
||||
// -------------------------
|
||||
|
||||
.#{$fa-css-prefix} {
|
||||
font-family: var(--#{$fa-css-prefix}-style-family, '#{$fa-style-family}');
|
||||
font-weight: var(--#{$fa-css-prefix}-style, #{$fa-style});
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix},
|
||||
.#{$fa-css-prefix}-classic,
|
||||
.#{$fa-css-prefix}-sharp,
|
||||
.fas,
|
||||
.#{$fa-css-prefix}-solid,
|
||||
.far,
|
||||
.#{$fa-css-prefix}-regular,
|
||||
.fab,
|
||||
.#{$fa-css-prefix}-brands {
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
display: var(--#{$fa-css-prefix}-display, #{$fa-display});
|
||||
font-style: normal;
|
||||
font-variant: normal;
|
||||
line-height: 1;
|
||||
text-rendering: auto;
|
||||
}
|
||||
|
||||
.fas,
|
||||
.#{$fa-css-prefix}-classic,
|
||||
.#{$fa-css-prefix}-solid,
|
||||
.far,
|
||||
.#{$fa-css-prefix}-regular {
|
||||
font-family: 'Font Awesome 6 Free';
|
||||
}
|
||||
|
||||
.fab,
|
||||
.#{$fa-css-prefix}-brands {
|
||||
font-family: 'Font Awesome 6 Brands';
|
||||
}
|
||||
|
||||
|
||||
%fa-icon {
|
||||
@include fa-icon;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// fixed-width icons
|
||||
// -------------------------
|
||||
|
||||
.#{$fa-css-prefix}-fw {
|
||||
text-align: center;
|
||||
width: $fa-fw-width;
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// functions
|
||||
// --------------------------
|
||||
|
||||
// fa-content: convenience function used to set content property
|
||||
@function fa-content($fa-var) {
|
||||
@return unquote("\"#{ $fa-var }\"");
|
||||
}
|
||||
|
||||
// fa-divide: Originally obtained from the Bootstrap https://github.com/twbs/bootstrap
|
||||
//
|
||||
// Licensed under: The MIT License (MIT)
|
||||
//
|
||||
// Copyright (c) 2011-2021 Twitter, Inc.
|
||||
// Copyright (c) 2011-2021 The Bootstrap Authors
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in
|
||||
// all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
@function fa-divide($dividend, $divisor, $precision: 10) {
|
||||
$sign: if($dividend > 0 and $divisor > 0, 1, -1);
|
||||
$dividend: abs($dividend);
|
||||
$divisor: abs($divisor);
|
||||
$quotient: 0;
|
||||
$remainder: $dividend;
|
||||
@if $dividend == 0 {
|
||||
@return 0;
|
||||
}
|
||||
@if $divisor == 0 {
|
||||
@error "Cannot divide by 0";
|
||||
}
|
||||
@if $divisor == 1 {
|
||||
@return $dividend;
|
||||
}
|
||||
@while $remainder >= $divisor {
|
||||
$quotient: $quotient + 1;
|
||||
$remainder: $remainder - $divisor;
|
||||
}
|
||||
@if $remainder > 0 and $precision > 0 {
|
||||
$remainder: fa-divide($remainder * 10, $divisor, $precision - 1) * .1;
|
||||
}
|
||||
@return ($quotient + $remainder) * $sign;
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// specific icon class definition
|
||||
// -------------------------
|
||||
|
||||
/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
|
||||
readers do not read off random characters that represent icons */
|
||||
|
||||
@each $name, $icon in $fa-icons {
|
||||
.#{$fa-css-prefix}-#{$name}::before { content: unquote("\"#{ $icon }\""); }
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
// icons in a list
|
||||
// -------------------------
|
||||
|
||||
.#{$fa-css-prefix}-ul {
|
||||
list-style-type: none;
|
||||
margin-left: var(--#{$fa-css-prefix}-li-margin, #{$fa-li-margin});
|
||||
padding-left: 0;
|
||||
|
||||
> li { position: relative; }
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-li {
|
||||
left: calc(var(--#{$fa-css-prefix}-li-width, #{$fa-li-width}) * -1);
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
width: var(--#{$fa-css-prefix}-li-width, #{$fa-li-width});
|
||||
line-height: inherit;
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
// mixins
|
||||
// --------------------------
|
||||
|
||||
// base rendering for an icon
|
||||
@mixin fa-icon {
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
display: inline-block;
|
||||
font-style: normal;
|
||||
font-variant: normal;
|
||||
font-weight: normal;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
// sets relative font-sizing and alignment (in _sizing)
|
||||
@mixin fa-size ($font-size) {
|
||||
font-size: fa-divide($font-size, $fa-size-scale-base) * 1em; // converts step in sizing scale into an em-based value that's relative to the scale's base
|
||||
line-height: fa-divide(1, $font-size) * 1em; // sets the line-height of the icon back to that of it's parent
|
||||
vertical-align: (fa-divide(6, $font-size) - fa-divide(3, 8)) * 1em; // vertically centers the icon taking into account the surrounding text's descender
|
||||
}
|
||||
|
||||
// only display content to screen readers
|
||||
// see: https://www.a11yproject.com/posts/2013-01-11-how-to-hide-content/
|
||||
// see: https://hugogiraudel.com/2016/10/13/css-hide-and-seek/
|
||||
@mixin fa-sr-only() {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
// use in conjunction with .sr-only to only display content when it's focused
|
||||
@mixin fa-sr-only-focusable() {
|
||||
&:not(:focus) {
|
||||
@include fa-sr-only();
|
||||
}
|
||||
}
|
||||
|
||||
// sets a specific icon family to use alongside style + icon mixins
|
||||
|
||||
// convenience mixins for declaring pseudo-elements by CSS variable,
|
||||
// including all style-specific font properties, and both the ::before
|
||||
// and ::after elements in the duotone case.
|
||||
@mixin fa-icon-solid($fa-var) {
|
||||
@extend %fa-icon;
|
||||
@extend .fa-solid;
|
||||
|
||||
&::before {
|
||||
content: unquote("\"#{ $fa-var }\"");
|
||||
}
|
||||
}
|
||||
@mixin fa-icon-regular($fa-var) {
|
||||
@extend %fa-icon;
|
||||
@extend .fa-regular;
|
||||
|
||||
&::before {
|
||||
content: unquote("\"#{ $fa-var }\"");
|
||||
}
|
||||
}
|
||||
@mixin fa-icon-brands($fa-var) {
|
||||
@extend %fa-icon;
|
||||
@extend .fa-brands;
|
||||
|
||||
&::before {
|
||||
content: unquote("\"#{ $fa-var }\"");
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
// rotating + flipping icons
|
||||
// -------------------------
|
||||
|
||||
.#{$fa-css-prefix}-rotate-90 {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-rotate-180 {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-rotate-270 {
|
||||
transform: rotate(270deg);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-flip-horizontal {
|
||||
transform: scale(-1, 1);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-flip-vertical {
|
||||
transform: scale(1, -1);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-flip-both,
|
||||
.#{$fa-css-prefix}-flip-horizontal.#{$fa-css-prefix}-flip-vertical {
|
||||
transform: scale(-1, -1);
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-rotate-by {
|
||||
transform: rotate(var(--#{$fa-css-prefix}-rotate-angle, 0));
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// screen-reader utilities
|
||||
// -------------------------
|
||||
|
||||
// only display content to screen readers
|
||||
.sr-only,
|
||||
.#{$fa-css-prefix}-sr-only {
|
||||
@include fa-sr-only;
|
||||
}
|
||||
|
||||
// use in conjunction with .sr-only to only display content when it's focused
|
||||
.sr-only-focusable,
|
||||
.#{$fa-css-prefix}-sr-only-focusable {
|
||||
@include fa-sr-only-focusable;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,16 +0,0 @@
|
||||
// sizing icons
|
||||
// -------------------------
|
||||
|
||||
// literal magnification scale
|
||||
@for $i from 1 through 10 {
|
||||
.#{$fa-css-prefix}-#{$i}x {
|
||||
font-size: $i * 1em;
|
||||
}
|
||||
}
|
||||
|
||||
// step-based scale (with alignment)
|
||||
@each $size, $value in $fa-sizes {
|
||||
.#{$fa-css-prefix}-#{$size} {
|
||||
@include fa-size($value);
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// stacking icons
|
||||
// -------------------------
|
||||
|
||||
.#{$fa-css-prefix}-stack {
|
||||
display: inline-block;
|
||||
height: 2em;
|
||||
line-height: 2em;
|
||||
position: relative;
|
||||
vertical-align: $fa-stack-vertical-align;
|
||||
width: $fa-stack-width;
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-stack-1x,
|
||||
.#{$fa-css-prefix}-stack-2x {
|
||||
left: 0;
|
||||
position: absolute;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
z-index: var(--#{$fa-css-prefix}-stack-z-index, #{$fa-stack-z-index});
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-stack-1x {
|
||||
line-height: inherit;
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-stack-2x {
|
||||
font-size: 2em;
|
||||
}
|
||||
|
||||
.#{$fa-css-prefix}-inverse {
|
||||
color: var(--#{$fa-css-prefix}-inverse, #{$fa-inverse});
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,30 +0,0 @@
|
||||
/*!
|
||||
* Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com
|
||||
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
|
||||
* Copyright 2024 Fonticons, Inc.
|
||||
*/
|
||||
@import 'functions';
|
||||
@import 'variables';
|
||||
|
||||
:root, :host {
|
||||
--#{$fa-css-prefix}-style-family-brands: 'Font Awesome 6 Brands';
|
||||
--#{$fa-css-prefix}-font-brands: normal 400 1em/1 'Font Awesome 6 Brands';
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Font Awesome 6 Brands';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: $fa-font-display;
|
||||
src: url('#{$fa-font-path}/fa-brands-400.woff2') format('woff2'),
|
||||
url('#{$fa-font-path}/fa-brands-400.ttf') format('truetype');
|
||||
}
|
||||
|
||||
.fab,
|
||||
.#{$fa-css-prefix}-brands {
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
@each $name, $icon in $fa-brand-icons {
|
||||
.#{$fa-css-prefix}-#{$name}:before { content: unquote("\"#{ $icon }\""); }
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
/*!
|
||||
* Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com
|
||||
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
|
||||
* Copyright 2024 Fonticons, Inc.
|
||||
*/
|
||||
// Font Awesome core compile (Web Fonts-based)
|
||||
// -------------------------
|
||||
|
||||
@import 'functions';
|
||||
@import 'variables';
|
||||
@import 'mixins';
|
||||
@import 'core';
|
||||
@import 'sizing';
|
||||
@import 'fixed-width';
|
||||
@import 'list';
|
||||
@import 'bordered-pulled';
|
||||
@import 'animated';
|
||||
@import 'rotated-flipped';
|
||||
@import 'stacked';
|
||||
@import 'icons';
|
||||
@import 'screen-reader';
|
||||
@@ -1,26 +0,0 @@
|
||||
/*!
|
||||
* Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com
|
||||
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
|
||||
* Copyright 2024 Fonticons, Inc.
|
||||
*/
|
||||
@import 'functions';
|
||||
@import 'variables';
|
||||
|
||||
:root, :host {
|
||||
--#{$fa-css-prefix}-style-family-classic: '#{ $fa-style-family }';
|
||||
--#{$fa-css-prefix}-font-regular: normal 400 1em/1 '#{ $fa-style-family }';
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Font Awesome 6 Free';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
font-display: $fa-font-display;
|
||||
src: url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
|
||||
url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype');
|
||||
}
|
||||
|
||||
.far,
|
||||
.#{$fa-css-prefix}-regular {
|
||||
font-weight: 400;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
/*!
|
||||
* Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com
|
||||
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
|
||||
* Copyright 2024 Fonticons, Inc.
|
||||
*/
|
||||
@import 'functions';
|
||||
@import 'variables';
|
||||
|
||||
:root, :host {
|
||||
--#{$fa-css-prefix}-style-family-classic: '#{ $fa-style-family }';
|
||||
--#{$fa-css-prefix}-font-solid: normal 900 1em/1 '#{ $fa-style-family }';
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: 'Font Awesome 6 Free';
|
||||
font-style: normal;
|
||||
font-weight: 900;
|
||||
font-display: $fa-font-display;
|
||||
src: url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
|
||||
url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype');
|
||||
}
|
||||
|
||||
.fas,
|
||||
.#{$fa-css-prefix}-solid {
|
||||
font-weight: 900;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
/*!
|
||||
* Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com
|
||||
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
|
||||
* Copyright 2024 Fonticons, Inc.
|
||||
*/
|
||||
// V4 shims compile (Web Fonts-based)
|
||||
// -------------------------
|
||||
|
||||
@import 'functions';
|
||||
@import 'variables';
|
||||
@import 'shims';
|
||||
@@ -1,32 +0,0 @@
|
||||
img {
|
||||
max-width: 90%;
|
||||
height: auto;
|
||||
margin: .2rem;
|
||||
padding: .2rem;
|
||||
border-radius: 15px;
|
||||
border: solid .2rem transparent;
|
||||
transition: 150ms;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
|
||||
img:hover {
|
||||
border: solid .2rem var(--metaColor);
|
||||
transform: scale(1.02);
|
||||
}
|
||||
|
||||
|
||||
.icons {
|
||||
width: 2.0rem;
|
||||
height: 2.0rem;
|
||||
aspect-ratio: 1/1;
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
color: var(--fgColor);
|
||||
fill: var(--fgColor);
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.icons__background:hover {
|
||||
background-color: transparent;
|
||||
color: var(--metaColor);
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
@import "text";
|
||||
@import "blocks";
|
||||
@import "images";
|
||||
@import "special";
|
||||
|
||||
@import "fontawesome/fontawesome";
|
||||
@import "fontawesome/brands";
|
||||
@import "fontawesome/regular";
|
||||
@import "fontawesome/solid";
|
||||
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira";
|
||||
src: url("/assets/fonts/FiraCode-Bold.woff2") format("woff2");
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira";
|
||||
src: url("/assets/fonts/FiraCode-Light.woff2") format("woff2");
|
||||
font-weight: light;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira";
|
||||
src: url("/assets/fonts/FiraCode-Medium.woff2") format("woff2");
|
||||
font-weight: medium;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira";
|
||||
src: url("/assets/fonts/FiraCode-Regular.woff2") format("woff2");
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
:root {
|
||||
// Misc colors
|
||||
--bgColor: #121212;
|
||||
--lightBgColor: #3a3f46;
|
||||
--fgColor: #ebebeb;
|
||||
--metaColor: #6199bb;
|
||||
--lightMetaColor: #638c86;
|
||||
--linkColor: #e4dab3;
|
||||
--codeBgColor: #292929;
|
||||
--codeFgColor: var(--fgColor);
|
||||
|
||||
// Main colors
|
||||
--grey: #696969;
|
||||
|
||||
// Accent colors, used only manally
|
||||
--green: #a2c579;
|
||||
--magenta: #ad79c5;
|
||||
--orange: #e86a33;
|
||||
--yellow: #e8bc00;
|
||||
--pink: #fa9f83;
|
||||
}
|
||||
|
||||
::selection,
|
||||
::-moz-selection {
|
||||
color: var(--bgColor);
|
||||
background: var(--metaColor);
|
||||
}
|
||||
|
||||
html {
|
||||
-webkit-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
font-size: 62.5%;
|
||||
scrollbar-color: var(--metaColor) var(--bgColor);
|
||||
scrollbar-width: auto;
|
||||
background: var(--bgColor);
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Fira";
|
||||
font-size: 1.6rem;
|
||||
line-height: 1.35;
|
||||
max-width: 64rem;
|
||||
margin: auto;
|
||||
overflow-wrap: break-word;
|
||||
background: var(--bgColor);
|
||||
color: var(--fgColor);
|
||||
}
|
||||
|
||||
div.wrapper {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
hr.footline {
|
||||
border: 1pt solid;
|
||||
}
|
||||
|
||||
hr {
|
||||
border: 1pt dashed;
|
||||
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
iframe {
|
||||
max-width: 90%;
|
||||
}
|
||||
|
||||
|
||||
.footContainer {
|
||||
padding-top: 0;
|
||||
padding-bottom: 1em;
|
||||
padding-left: 1em;
|
||||
padding-right: 1em;
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.wrapper {
|
||||
margin: 1rem;
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
.handout-li-links {
|
||||
color: var(--grey);
|
||||
}
|
||||
|
||||
.handout-li-links a {
|
||||
@extend a;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 1.5pt;
|
||||
padding-left: 1ex;
|
||||
padding-right: 1ex;
|
||||
}
|
||||
|
||||
// Only do hover magic on mouse devices
|
||||
@media(hover: hover) and (pointer: fine) {
|
||||
.handout-ul li:hover {
|
||||
margin-left: 1ex;
|
||||
transition: 50ms;
|
||||
}
|
||||
|
||||
.handout-ul li {
|
||||
transition: 50ms;
|
||||
transition-delay: 50ms;
|
||||
}
|
||||
|
||||
.handout-ul li:hover .handout-li-links {
|
||||
display: inline-block;
|
||||
opacity: 1;
|
||||
transition: 100ms;
|
||||
}
|
||||
|
||||
.handout-ul li .handout-li-links {
|
||||
transition-delay: 50ms;
|
||||
transition: 100ms;
|
||||
opacity: 0;
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Email obfuscation
|
||||
// Works with "{{ email_*() }}" shortcodes.
|
||||
.eobf {
|
||||
@extend a;
|
||||
}
|
||||
|
||||
.eobf:hover {
|
||||
@extend a, :hover;
|
||||
}
|
||||
|
||||
// Change icon on hover
|
||||
.eobf #eobf-kb,
|
||||
.eobf:hover #eobf-en {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.eobf #eobf-en,
|
||||
.eobf:hover #eobf-kb {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
// Hover text
|
||||
.eobf:hover span:before {
|
||||
unicode-bidi: bidi-override;
|
||||
direction: ltr;
|
||||
content: attr(data-h);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Text for email_beta
|
||||
.eobf-beta span:before {
|
||||
content: "mo" attr(data-a) "teb" "\0040" attr(data-b) "m";
|
||||
unicode-bidi: bidi-override;
|
||||
direction: rtl;
|
||||
}
|
||||
|
||||
// Text for email_goog
|
||||
.eobf-goog span:before {
|
||||
content: "mo" attr(data-a) "mg" "\0040" attr(data-b) "p." attr(data-c) "m";
|
||||
unicode-bidi: bidi-override;
|
||||
direction: rtl;
|
||||
}
|
||||
|
||||
// Text for email_this
|
||||
.eobf-this span:before {
|
||||
content: attr(data-a);
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
h1 {
|
||||
font-size: 3.5rem;
|
||||
margin-top: 1ex;
|
||||
margin-bottom: 1ex;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 2.5rem;
|
||||
margin-top: 1ex;
|
||||
margin-bottom: 0.5ex;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
h3::before {
|
||||
color: var(--lightMetaColor);
|
||||
content: '## '
|
||||
}
|
||||
|
||||
h1::before,
|
||||
h2::before,
|
||||
h4::before,
|
||||
h5::before,
|
||||
h6::before {
|
||||
color: var(--metaColor);
|
||||
content: '# '
|
||||
}
|
||||
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
border-radius: .3rem;
|
||||
padding: 0 .2ex 0 .2ex;
|
||||
color: var(--linkColor);
|
||||
transition: 150ms;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
background-color: var(--linkColor);
|
||||
color: var(--bgColor);
|
||||
transition: 150ms;
|
||||
}
|
||||
|
||||
footer {
|
||||
font-size: 1.4rem;
|
||||
clear: both;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
footer {
|
||||
text-align: left
|
||||
}
|
||||
|
||||
.footnote-item p {
|
||||
display: inline;
|
||||
padding: 0 0 0 1rem;
|
||||
}
|
||||
|
||||
hr.footnotes-sep {
|
||||
margin: 5rem 0 0 0;
|
||||
}
|
||||
|
||||
.footnote-ref > a {
|
||||
padding: 0 2pt 0.8rem 2pt !important;
|
||||
}
|
||||
|
||||
a.footnote-backref, .footnote-ref > a
|
||||
{
|
||||
color: var(--metaColor);
|
||||
padding: 0 2pt 0 2pt;
|
||||
}
|
||||
|
||||
a.footnote-backref:hover,
|
||||
.footnote-ref > a:hover
|
||||
{
|
||||
color: var(--bgColor);
|
||||
background-color: var(--metaColor);
|
||||
}
|
||||
|
||||
.footContainer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use lazy_static::lazy_static;
|
||||
use markdown_it::generics::inline::full_link;
|
||||
use markdown_it::{MarkdownIt, Node};
|
||||
use maud::{Markup, PreEscaped, Render};
|
||||
use page::servable::PageMetadata;
|
||||
use servable::PageMetadata;
|
||||
|
||||
use crate::components::md::emote::InlineEmote;
|
||||
use crate::components::md::frontmatter::{TomlFrontMatter, YamlFrontMatter};
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use std::{
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
sync::{Arc, LazyLock},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use chrono::{DateTime, TimeDelta, Utc};
|
||||
use maud::{Markup, PreEscaped, html};
|
||||
use page::{DeviceType, RenderContext, servable::Page};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use servable::{DeviceType, HtmlPage, RenderContext};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use crate::{
|
||||
@@ -16,7 +16,8 @@ use crate::{
|
||||
md::{Markdown, meta_from_markdown},
|
||||
misc::FarLink,
|
||||
},
|
||||
pages::{MAIN_TEMPLATE, backlinks, footer},
|
||||
pages::{LAZY_IMAGE_JS, backlinks, footer},
|
||||
routes::{IMG_ICON, MAIN_CSS},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -174,7 +175,7 @@ fn build_list_for_group(handouts: &[HandoutEntry], group: &str, req_ctx: &Render
|
||||
// MARK: page
|
||||
//
|
||||
|
||||
pub fn handouts() -> Page {
|
||||
pub static HANDOUTS: LazyLock<HtmlPage> = LazyLock::new(|| {
|
||||
let md = Markdown::parse(include_str!("handouts.md"));
|
||||
|
||||
let index = CachedRequest::new(
|
||||
@@ -188,24 +189,27 @@ pub fn handouts() -> Page {
|
||||
let mut meta = meta_from_markdown(&md).unwrap().unwrap();
|
||||
|
||||
if meta.image.is_none() {
|
||||
meta.image = Some("/assets/img/icon.png".to_owned());
|
||||
meta.image = Some(IMG_ICON.route().into());
|
||||
}
|
||||
|
||||
let html = PreEscaped(md.render());
|
||||
|
||||
MAIN_TEMPLATE
|
||||
.derive(meta, move |page, ctx| {
|
||||
HtmlPage::default()
|
||||
.with_style_linked(MAIN_CSS.route())
|
||||
.with_script_inline(LAZY_IMAGE_JS)
|
||||
.with_meta(meta)
|
||||
.with_render(move |page, ctx| {
|
||||
let html = html.clone();
|
||||
let index = index.clone();
|
||||
render(html, index, page, ctx)
|
||||
})
|
||||
.html_ttl(Some(TimeDelta::seconds(300)))
|
||||
}
|
||||
.with_ttl(Some(TimeDelta::seconds(300)))
|
||||
});
|
||||
|
||||
fn render<'a>(
|
||||
html: Markup,
|
||||
index: Arc<CachedRequest<Result<Vec<HandoutEntry>, reqwest::Error>>>,
|
||||
_page: &'a Page,
|
||||
_page: &'a HtmlPage,
|
||||
ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Markup> + Send + Sync + 'a>> {
|
||||
Box::pin(async move {
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use maud::{Markup, html};
|
||||
use page::{
|
||||
RenderContext,
|
||||
servable::{Page, PageMetadata},
|
||||
};
|
||||
use std::pin::Pin;
|
||||
use servable::{HtmlPage, PageMetadata, RenderContext};
|
||||
use std::{pin::Pin, sync::LazyLock};
|
||||
|
||||
use crate::{
|
||||
components::{
|
||||
@@ -12,23 +9,25 @@ use crate::{
|
||||
md::Markdown,
|
||||
misc::FarLink,
|
||||
},
|
||||
pages::{MAIN_TEMPLATE, footer},
|
||||
pages::{LAZY_IMAGE_JS, footer},
|
||||
routes::{IMG_ICON, MAIN_CSS},
|
||||
};
|
||||
|
||||
pub fn index() -> Page {
|
||||
MAIN_TEMPLATE.derive(
|
||||
PageMetadata {
|
||||
pub static INDEX: LazyLock<HtmlPage> = LazyLock::new(|| {
|
||||
HtmlPage::default()
|
||||
.with_style_linked(MAIN_CSS.route())
|
||||
.with_script_inline(LAZY_IMAGE_JS)
|
||||
.with_meta(PageMetadata {
|
||||
title: "Betalupi: About".into(),
|
||||
author: Some("Mark".into()),
|
||||
description: None,
|
||||
image: Some("/assets/img/icon.png".to_owned()),
|
||||
},
|
||||
render,
|
||||
)
|
||||
}
|
||||
image: Some(IMG_ICON.route().into()),
|
||||
})
|
||||
.with_render(render)
|
||||
});
|
||||
|
||||
fn render<'a>(
|
||||
_page: &'a Page,
|
||||
_page: &'a HtmlPage,
|
||||
_ctx: &'a RenderContext,
|
||||
) -> Pin<Box<dyn Future<Output = Markup> + Send + Sync + 'a>> {
|
||||
Box::pin(async {
|
||||
|
||||
@@ -1,57 +1,29 @@
|
||||
use chrono::TimeDelta;
|
||||
use maud::{Markup, PreEscaped, html};
|
||||
use page::{
|
||||
RenderContext,
|
||||
servable::{Page, PageMetadata, PageTemplate},
|
||||
};
|
||||
use reqwest::StatusCode;
|
||||
use servable::{HtmlPage, PageMetadata, RenderContext};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use crate::components::{
|
||||
fa::FAIcon,
|
||||
md::{Markdown, meta_from_markdown},
|
||||
misc::FarLink,
|
||||
use crate::{
|
||||
components::{
|
||||
fa::FAIcon,
|
||||
md::{Markdown, meta_from_markdown},
|
||||
misc::FarLink,
|
||||
},
|
||||
routes::{IMG_ICON, MAIN_CSS},
|
||||
};
|
||||
|
||||
mod handouts;
|
||||
mod index;
|
||||
mod notfound;
|
||||
|
||||
pub use handouts::handouts;
|
||||
pub use index::index;
|
||||
pub use notfound::notfound;
|
||||
|
||||
pub fn links() -> Page {
|
||||
/*
|
||||
Dead links:
|
||||
|
||||
https://www.commitstrip.com/en/
|
||||
http://www.3dprintmath.com/
|
||||
*/
|
||||
|
||||
page_from_markdown(
|
||||
include_str!("links.md"),
|
||||
Some("/assets/img/icon.png".to_owned()),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn betalupi() -> Page {
|
||||
page_from_markdown(
|
||||
include_str!("betalupi.md"),
|
||||
Some("/assets/img/icon.png".to_owned()),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn htwah_typesetting() -> Page {
|
||||
page_from_markdown(
|
||||
include_str!("htwah-typesetting.md"),
|
||||
Some("/assets/img/icon.png".to_owned()),
|
||||
)
|
||||
}
|
||||
pub use handouts::HANDOUTS;
|
||||
pub use index::INDEX;
|
||||
|
||||
//
|
||||
// MARK: md
|
||||
//
|
||||
|
||||
fn page_from_markdown(md: impl Into<String>, default_image: Option<String>) -> Page {
|
||||
fn page_from_markdown(md: impl Into<String>, default_image: Option<String>) -> HtmlPage {
|
||||
let md: String = md.into();
|
||||
let md = Markdown::parse(&md);
|
||||
|
||||
@@ -68,8 +40,11 @@ fn page_from_markdown(md: impl Into<String>, default_image: Option<String>) -> P
|
||||
|
||||
let html = PreEscaped(md.render());
|
||||
|
||||
MAIN_TEMPLATE
|
||||
.derive(meta, move |_page, ctx| {
|
||||
HtmlPage::default()
|
||||
.with_script_inline(LAZY_IMAGE_JS)
|
||||
.with_style_linked(MAIN_CSS.route())
|
||||
.with_meta(meta)
|
||||
.with_render(move |_page, ctx| {
|
||||
let html = html.clone();
|
||||
|
||||
Box::pin(async move {
|
||||
@@ -86,48 +61,46 @@ fn page_from_markdown(md: impl Into<String>, default_image: Option<String>) -> P
|
||||
}
|
||||
})
|
||||
})
|
||||
.html_ttl(Some(TimeDelta::days(1)))
|
||||
.immutable(true)
|
||||
.with_ttl(Some(TimeDelta::days(1)))
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: components
|
||||
//
|
||||
|
||||
const LAZY_IMAGE_JS: &str = "
|
||||
window.onload = function() {
|
||||
var imgs = document.querySelectorAll('.img-placeholder');
|
||||
|
||||
imgs.forEach(img => {
|
||||
img.style.border = 'none';
|
||||
img.style.filter = 'blur(10px)';
|
||||
img.style.transition = 'filter 0.3s';
|
||||
|
||||
var lg = new Image();
|
||||
lg.src = img.dataset.large;
|
||||
lg.onload = function () {
|
||||
img.src = img.dataset.large;
|
||||
img.style.filter = 'blur(0px)';
|
||||
};
|
||||
})
|
||||
}
|
||||
";
|
||||
|
||||
/*
|
||||
const MAIN_TEMPLATE: PageTemplate = PageTemplate {
|
||||
// Order matters, base htmx goes first
|
||||
scripts_linked: &["/assets/htmx.js", "/assets/htmx-json.js"],
|
||||
|
||||
// TODO: use htmx for this
|
||||
scripts_inline: &["
|
||||
window.onload = function() {
|
||||
var imgs = document.querySelectorAll('.img-placeholder');
|
||||
|
||||
imgs.forEach(img => {
|
||||
img.style.border = 'none';
|
||||
img.style.filter = 'blur(10px)';
|
||||
img.style.transition = 'filter 0.3s';
|
||||
|
||||
var lg = new Image();
|
||||
lg.src = img.dataset.large;
|
||||
lg.onload = function () {
|
||||
img.src = img.dataset.large;
|
||||
img.style.filter = 'blur(0px)';
|
||||
};
|
||||
})
|
||||
}
|
||||
"],
|
||||
|
||||
styles_inline: &[],
|
||||
styles_linked: &["/assets/css/main.css"],
|
||||
scripts: &[
|
||||
ScriptSource::Linked(&"/assets/htmx-2.0.8.js"),
|
||||
ScriptSource::Linked(&"/assets/htmx-json-1.19.12.js"),
|
||||
],
|
||||
|
||||
extra_meta: &[(
|
||||
"viewport",
|
||||
"width=device-width,initial-scale=1,user-scalable=no",
|
||||
)],
|
||||
|
||||
..PageTemplate::const_default()
|
||||
};
|
||||
*/
|
||||
|
||||
pub fn backlinks(ctx: &RenderContext) -> Option<Markup> {
|
||||
let mut backlinks = vec![("/", "home")];
|
||||
@@ -184,3 +157,56 @@ pub fn footer() -> Markup {
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: pages
|
||||
//
|
||||
|
||||
pub const LINKS: LazyLock<HtmlPage> = LazyLock::new(|| {
|
||||
/*
|
||||
Dead links:
|
||||
|
||||
https://www.commitstrip.com/en/
|
||||
http://www.3dprintmath.com/
|
||||
*/
|
||||
|
||||
page_from_markdown(include_str!("links.md"), Some(IMG_ICON.route().into()))
|
||||
});
|
||||
|
||||
pub const BETALUPI: LazyLock<HtmlPage> = LazyLock::new(|| {
|
||||
page_from_markdown(include_str!("betalupi.md"), Some(IMG_ICON.route().into()))
|
||||
});
|
||||
|
||||
pub const HTWAH_TYPESETTING: LazyLock<HtmlPage> = LazyLock::new(|| {
|
||||
page_from_markdown(
|
||||
include_str!("htwah-typesetting.md"),
|
||||
Some(IMG_ICON.route().into()),
|
||||
)
|
||||
});
|
||||
|
||||
pub static NOT_FOUND: LazyLock<HtmlPage> = LazyLock::new(|| {
|
||||
HtmlPage::default()
|
||||
.with_style_linked(MAIN_CSS.route())
|
||||
.with_meta(PageMetadata {
|
||||
title: "Page not found".into(),
|
||||
author: None,
|
||||
description: None,
|
||||
image: Some(IMG_ICON.route().into()),
|
||||
})
|
||||
.with_render(
|
||||
move |_page, _ctx| {
|
||||
Box::pin(async {
|
||||
html! {
|
||||
div class="wrapper" {
|
||||
div style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh" {
|
||||
p style="font-weight:bold;font-size:50pt;margin:0;" { "404" }
|
||||
p style="font-size:13pt;margin:0;color:var(--grey);" { "(page not found)" }
|
||||
a style="font-size:12pt;margin:10pt;padding:5px;" href="/" {"<- Back to site"}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
.with_code(StatusCode::NOT_FOUND)
|
||||
});
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
use maud::html;
|
||||
use page::servable::{Page, PageMetadata};
|
||||
use reqwest::StatusCode;
|
||||
|
||||
use crate::pages::MAIN_TEMPLATE;
|
||||
|
||||
pub fn notfound() -> Page {
|
||||
MAIN_TEMPLATE.derive(
|
||||
PageMetadata {
|
||||
title: "Page not found".into(),
|
||||
author:None,
|
||||
description: None,
|
||||
image: Some("/assets/img/icon.png".to_owned()),
|
||||
},
|
||||
move |_page, _ctx| {
|
||||
Box::pin(async {
|
||||
html! {
|
||||
div class="wrapper" {
|
||||
div style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh" {
|
||||
p style="font-weight:bold;font-size:50pt;margin:0;" { "404" }
|
||||
p style="font-size:13pt;margin:0;color:var(--grey);" { "(page not found)" }
|
||||
a style="font-size:12pt;margin:10pt;padding:5px;" href="/" {"<- Back to site"}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
).response_code(StatusCode::NOT_FOUND)
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
use axum::Router;
|
||||
use macro_sass::sass;
|
||||
use page::{
|
||||
ServableRoute,
|
||||
servable::{Redirect, StaticAsset},
|
||||
use servable::{
|
||||
CACHE_BUST_STR, Redirect, ServableRouter, ServableWithRoute, StaticAsset, mime::MimeType,
|
||||
};
|
||||
use toolbox::mime::MimeType;
|
||||
use tower_http::compression::{CompressionLayer, DefaultPredicate};
|
||||
|
||||
use crate::pages;
|
||||
@@ -20,184 +17,270 @@ pub(super) fn router() -> Router<()> {
|
||||
build_server().into_router().layer(compression)
|
||||
}
|
||||
|
||||
fn build_server() -> ServableRoute {
|
||||
ServableRoute::new()
|
||||
.with_404(pages::notfound())
|
||||
.add_page("/", pages::index())
|
||||
.add_page("/links", pages::links())
|
||||
.add_page("/whats-a-betalupi", pages::betalupi())
|
||||
.add_page("/handouts", pages::handouts())
|
||||
pub static HTMX: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htmx-2.0.8.js".into(),
|
||||
servable::HTMX_2_0_8.with_ttl(None),
|
||||
);
|
||||
|
||||
pub static HTMX_JSON: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htmx-json-1.19.12.js".into(),
|
||||
servable::EXT_JSON_1_19_12,
|
||||
);
|
||||
|
||||
pub static MAIN_CSS: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| format!("/assets/{}/css/main.css", *CACHE_BUST_STR),
|
||||
StaticAsset {
|
||||
bytes: grass::include!("css/main.scss").as_bytes(),
|
||||
mime: MimeType::Css,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static IMG_COVER_SMALL: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/img/cover-small.jpg".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/images/cover-small.jpg"),
|
||||
mime: MimeType::Jpg,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static IMG_BETALUPI: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/img/betalupi.png".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/images/betalupi-map.png"),
|
||||
mime: MimeType::Png,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static IMG_ICON: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/img/icon.png".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/images/icon.png"),
|
||||
mime: MimeType::Png,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
//
|
||||
// MARK: fonts
|
||||
//
|
||||
|
||||
pub static FONT_FIRACODE_BOLD: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/FiraCode-Bold.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Bold.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FIRACODE_LIGHT: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/FiraCode-Light.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Light.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FIRACODE_MEDIUM: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/FiraCode-Medium.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Medium.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FIRACODE_REGULAR: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/FiraCode-Regular.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Regular.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FIRACODE_SEMIBOLD: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/FiraCode-SemiBold.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-SemiBold.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FIRACODE_VF: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/FiraCode-VF.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-VF.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
//
|
||||
// MARK: icons
|
||||
//
|
||||
pub static FONT_FA_BRANDS_WOFF2: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/fa/fa-brands-400.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-brands-400.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FA_REGULAR_WOFF2: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/fa/fa-regular-400.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-regular-400.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FA_SOLID_WOFF2: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/fa/fa-solid-900.woff2".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-solid-900.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FA_BRANDS_TTF: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/fa/fa-brands-400.ttf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-brands-400.ttf"),
|
||||
mime: MimeType::Ttf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FA_REGULAR_TTF: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/fa/fa-regular-400.ttf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-regular-400.ttf"),
|
||||
mime: MimeType::Ttf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static FONT_FA_SOLID_TTF: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/fonts/fa/fa-solid-900.ttf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-solid-900.ttf"),
|
||||
mime: MimeType::Ttf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
//
|
||||
// MARK: htwah
|
||||
//
|
||||
pub static HTWAH_DEFINITIONS: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htwah/definitions.pdf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/definitions.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static HTWAH_NUMBERING: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htwah/numbering.pdf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/numbering.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static HTWAH_SOLS_A: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htwah/sols-a.pdf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/sols-a.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static HTWAH_SOLS_B: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htwah/sols-b.pdf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/sols-b.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static HTWAH_SPACING_A: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htwah/spacing-a.pdf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/spacing-a.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
pub static HTWAH_SPACING_B: ServableWithRoute<StaticAsset> = ServableWithRoute::new(
|
||||
|| "/assets/htwah/spacing-b.pdf".into(),
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/spacing-b.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
ttl: StaticAsset::DEFAULT_TTL,
|
||||
},
|
||||
);
|
||||
|
||||
fn build_server() -> ServableRouter {
|
||||
ServableRouter::new()
|
||||
.with_404(&pages::NOT_FOUND)
|
||||
.add_page("/", &pages::INDEX)
|
||||
.add_page("/links", pages::LINKS)
|
||||
.add_page("/whats-a-betalupi", pages::BETALUPI)
|
||||
.add_page("/handouts", &pages::HANDOUTS)
|
||||
.add_page("/htwah", {
|
||||
#[expect(clippy::unwrap_used)]
|
||||
Redirect::new("/handouts").unwrap()
|
||||
})
|
||||
.add_page("/htwah/typesetting", pages::htwah_typesetting())
|
||||
.add_page("/assets/htmx.js", page::HTMX_2_0_8)
|
||||
.add_page("/assets/htmx-json.js", page::EXT_JSON_1_19_12)
|
||||
.add_page("/htwah/typesetting", pages::HTWAH_TYPESETTING)
|
||||
.add_page_with_route(&HTMX)
|
||||
.add_page_with_route(&HTMX_JSON)
|
||||
//
|
||||
.add_page(
|
||||
"/assets/css/main.css",
|
||||
StaticAsset {
|
||||
bytes: sass!("css/main.scss").as_bytes(),
|
||||
mime: MimeType::Css,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/img/cover-small.jpg",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/images/cover-small.jpg"),
|
||||
mime: MimeType::Jpg,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/img/betalupi.png",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/images/betalupi-map.png"),
|
||||
mime: MimeType::Png,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/img/icon.png",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/images/icon.png"),
|
||||
mime: MimeType::Png,
|
||||
},
|
||||
)
|
||||
.add_page_with_route(&MAIN_CSS)
|
||||
.add_page_with_route(&IMG_COVER_SMALL)
|
||||
.add_page_with_route(&IMG_BETALUPI)
|
||||
.add_page_with_route(&IMG_ICON)
|
||||
//
|
||||
// MARK: fonts
|
||||
//
|
||||
.add_page(
|
||||
"/assets/fonts/FiraCode-Bold.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Bold.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/FiraCode-Light.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Light.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/FiraCode-Medium.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Medium.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/FiraCode-Regular.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-Regular.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/FiraCode-SemiBold.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-SemiBold.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/FiraCode-VF.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fira/FiraCode-VF.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page_with_route(&FONT_FIRACODE_BOLD)
|
||||
.add_page_with_route(&FONT_FIRACODE_LIGHT)
|
||||
.add_page_with_route(&FONT_FIRACODE_MEDIUM)
|
||||
.add_page_with_route(&FONT_FIRACODE_REGULAR)
|
||||
.add_page_with_route(&FONT_FIRACODE_SEMIBOLD)
|
||||
.add_page_with_route(&FONT_FIRACODE_VF)
|
||||
//
|
||||
// MARK: icons
|
||||
//
|
||||
.add_page(
|
||||
"/assets/fonts/fa/fa-brands-400.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-brands-400.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/fa/fa-regular-400.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-regular-400.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/fa/fa-solid-900.woff2",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-solid-900.woff2"),
|
||||
mime: MimeType::Woff2,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/fa/fa-brands-400.ttf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-brands-400.ttf"),
|
||||
mime: MimeType::Ttf,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/fa/fa-regular-400.ttf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-regular-400.ttf"),
|
||||
mime: MimeType::Ttf,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/fonts/fa/fa-solid-900.ttf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/fonts/fa/fa-solid-900.ttf"),
|
||||
mime: MimeType::Ttf,
|
||||
},
|
||||
)
|
||||
.add_page_with_route(&FONT_FA_BRANDS_WOFF2)
|
||||
.add_page_with_route(&FONT_FA_REGULAR_WOFF2)
|
||||
.add_page_with_route(&FONT_FA_SOLID_WOFF2)
|
||||
.add_page_with_route(&FONT_FA_BRANDS_TTF)
|
||||
.add_page_with_route(&FONT_FA_REGULAR_TTF)
|
||||
.add_page_with_route(&FONT_FA_SOLID_TTF)
|
||||
//
|
||||
// MARK: htwah
|
||||
//
|
||||
.add_page(
|
||||
"/assets/htwah/definitions.pdf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/definitions.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/htwah/numbering.pdf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/numbering.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/htwah/sols-a.pdf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/sols-a.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/htwah/sols-b.pdf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/sols-b.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/htwah/spacing-a.pdf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/spacing-a.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
},
|
||||
)
|
||||
.add_page(
|
||||
"/assets/htwah/spacing-b.pdf",
|
||||
StaticAsset {
|
||||
bytes: include_bytes!("../../assets/htwah/spacing-b.pdf"),
|
||||
mime: MimeType::Pdf,
|
||||
},
|
||||
)
|
||||
.add_page_with_route(&HTWAH_DEFINITIONS)
|
||||
.add_page_with_route(&HTWAH_NUMBERING)
|
||||
.add_page_with_route(&HTWAH_SOLS_A)
|
||||
.add_page_with_route(&HTWAH_SOLS_B)
|
||||
.add_page_with_route(&HTWAH_SPACING_A)
|
||||
.add_page_with_route(&HTWAH_SPACING_B)
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user