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

This commit is contained in:
2025-11-27 21:07:52 -08:00
parent b6de727883
commit a29db858d1
60 changed files with 560 additions and 3163 deletions

305
Cargo.lock generated
View File

@@ -29,6 +29,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "aligned"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "377e4c0ba83e4431b10df45c1d4666f178ea9c552cac93e60c3a88bf32785923"
dependencies = [
"as-slice",
]
[[package]]
name = "aligned-vec"
version = "0.6.4"
@@ -165,6 +174,15 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
[[package]]
name = "as-slice"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
dependencies = [
"stable_deref_trait",
]
[[package]]
name = "ast_node"
version = "5.0.0"
@@ -201,6 +219,26 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "av-scenechange"
version = "0.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
dependencies = [
"aligned",
"anyhow",
"arg_enum_proc_macro",
"arrayvec",
"log",
"num-rational",
"num-traits",
"pastey",
"rayon",
"thiserror 2.0.17",
"v_frame",
"y4m",
]
[[package]]
name = "av1-grain"
version = "0.2.5"
@@ -226,9 +264,9 @@ dependencies = [
[[package]]
name = "axum"
version = "0.8.6"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a18ed336352031311f4e0b4dd2ff392d4fbb370777c9d18d7fc9d7359f73871"
checksum = "5b098575ebe77cb6d14fc7f32749631a6e44edbef6b796f89b020e99ba20d425"
dependencies = [
"axum-core",
"axum-macros",
@@ -342,9 +380,12 @@ checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
[[package]]
name = "bitstream-io"
version = "2.6.0"
version = "4.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2"
checksum = "60d4bd9d1db2c6bdf285e223a7fa369d5ce98ec767dec949c6ca62863ce61757"
dependencies = [
"core2",
]
[[package]]
name = "block-buffer"
@@ -378,9 +419,9 @@ dependencies = [
[[package]]
name = "built"
version = "0.7.7"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56ed6191a7e78c36abdb16ab65341eefd73d64d303fffccdbb00d51e4205967b"
checksum = "f4ad8f11f288f48ca24471bbd51ac257aaeaaa07adae295591266b792902ae64"
[[package]]
name = "bumpalo"
@@ -466,16 +507,6 @@ dependencies = [
"shlex",
]
[[package]]
name = "cfg-expr"
version = "0.15.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"
dependencies = [
"smallvec",
"target-lexicon",
]
[[package]]
name = "cfg-if"
version = "1.0.4"
@@ -640,6 +671,15 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "core2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b49ba7ef1ad6107f8824dbe97de947cbaac53c44e7f9756a1fba0d37c1eec505"
dependencies = [
"memchr",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
@@ -965,9 +1005,9 @@ dependencies = [
[[package]]
name = "exr"
version = "1.73.0"
version = "1.74.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83197f59927b46c04a183a619b7c29df34e63e63c7869320862268c0ef687e0"
checksum = "4300e043a56aa2cb633c01af81ca8f699a321879a7854d3896a0ba89056363be"
dependencies = [
"bit_field",
"half",
@@ -1222,9 +1262,9 @@ dependencies = [
[[package]]
name = "gif"
version = "0.13.3"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
checksum = "f954a9e9159ec994f73a30a12b96a702dde78f5547bcb561174597924f7d4162"
dependencies = [
"color_quant",
"weezl",
@@ -1245,6 +1285,7 @@ dependencies = [
"clap",
"getrandom 0.2.16",
"grass_compiler",
"include_sass",
]
[[package]]
@@ -1601,9 +1642,9 @@ dependencies = [
[[package]]
name = "image"
version = "0.25.8"
version = "0.25.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "529feb3e6769d234375c4cf1ee2ce713682b8e76538cb13f9fc23e1400a591e7"
checksum = "e6506c6c10786659413faa717ceebcb8f70731c0a60cbae39795fdf114519c1a"
dependencies = [
"bytemuck",
"byteorder-lite",
@@ -1619,8 +1660,8 @@ dependencies = [
"rayon",
"rgb",
"tiff",
"zune-core",
"zune-jpeg",
"zune-core 0.5.0",
"zune-jpeg 0.5.5",
]
[[package]]
@@ -1639,6 +1680,17 @@ version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c5cedc30da3a610cac6b4ba17597bdf7152cf974e8aab3afb3d54455e371c8"
[[package]]
name = "include_sass"
version = "0.13.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6090ec145f7cf645ff53998a54d3fc77ae02d71651093ee53806769eb40ea1f"
dependencies = [
"grass_compiler",
"quote",
"syn 2.0.108",
]
[[package]]
name = "indexmap"
version = "2.12.0"
@@ -1695,15 +1747,6 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itertools"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.14.0"
@@ -1886,15 +1929,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4"
[[package]]
name = "macro-sass"
version = "0.0.1"
dependencies = [
"grass",
"quote",
"syn 2.0.108",
]
[[package]]
name = "markdown-it"
version = "0.6.1"
@@ -2277,22 +2311,6 @@ version = "4.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52"
[[package]]
name = "page"
version = "0.0.1"
dependencies = [
"axum",
"chrono",
"maud",
"pixel-transform",
"serde",
"serde_urlencoded",
"tokio",
"toolbox",
"tower",
"tracing",
]
[[package]]
name = "parking_lot"
version = "0.12.5"
@@ -2322,6 +2340,12 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pastey"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -2410,17 +2434,6 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pixel-transform"
version = "0.0.1"
dependencies = [
"image",
"serde",
"strum",
"thiserror 2.0.17",
"toolbox",
]
[[package]]
name = "pkg-config"
version = "0.3.32"
@@ -2573,7 +2586,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
dependencies = [
"anyhow",
"itertools 0.14.0",
"itertools",
"proc-macro2",
"quote",
"syn 2.0.108",
@@ -2778,19 +2791,21 @@ dependencies = [
[[package]]
name = "rav1e"
version = "0.7.1"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd87ce80a7665b1cce111f8a16c1f3929f6547ce91ade6addf4ec86a8dda5ce9"
checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"
dependencies = [
"aligned-vec",
"arbitrary",
"arg_enum_proc_macro",
"arrayvec",
"av-scenechange",
"av1-grain",
"bitstream-io",
"built",
"cfg-if",
"interpolate_name",
"itertools 0.12.1",
"itertools",
"libc",
"libfuzzer-sys",
"log",
@@ -2799,23 +2814,21 @@ dependencies = [
"noop_proc_macro",
"num-derive",
"num-traits",
"once_cell",
"paste",
"profiling",
"rand 0.8.5",
"rand_chacha 0.3.1",
"rand 0.9.2",
"rand_chacha 0.9.0",
"simd_helpers",
"system-deps",
"thiserror 1.0.69",
"thiserror 2.0.17",
"v_frame",
"wasm-bindgen",
]
[[package]]
name = "ravif"
version = "0.11.20"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5825c26fddd16ab9f515930d49028a630efec172e903483c94796cfe31893e6b"
checksum = "ef69c1990ceef18a116855938e74793a5f7496ee907562bd0857b6ac734ab285"
dependencies = [
"avif-serialize",
"imgref",
@@ -3208,15 +3221,6 @@ dependencies = [
"serde_core",
]
[[package]]
name = "serde_spanned"
version = "0.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
dependencies = [
"serde",
]
[[package]]
name = "serde_spanned"
version = "1.0.3"
@@ -3238,6 +3242,26 @@ dependencies = [
"serde",
]
[[package]]
name = "servable"
version = "0.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee682f2af773f19ca10ffafc5fe367a6a4f4a0d3b53b8724487677f46df473ae"
dependencies = [
"axum",
"chrono",
"image",
"maud",
"rand 0.9.2",
"serde",
"serde_urlencoded",
"strum",
"thiserror 2.0.17",
"tokio",
"tower",
"tracing",
]
[[package]]
name = "service-webpage"
version = "0.0.1"
@@ -3245,20 +3269,19 @@ dependencies = [
"axum",
"chrono",
"emojis",
"grass",
"lazy_static",
"libservice",
"macro-sass",
"markdown-it",
"maud",
"md-footnote",
"page",
"parking_lot",
"reqwest",
"serde",
"servable",
"strum",
"tokio",
"toml 0.9.8",
"toolbox",
"toml",
"tower-http",
"tracing",
]
@@ -3592,25 +3615,6 @@ dependencies = [
"yaml-rust",
]
[[package]]
name = "system-deps"
version = "6.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
dependencies = [
"cfg-expr",
"heck",
"pkg-config",
"toml 0.8.23",
"version-compare",
]
[[package]]
name = "target-lexicon"
version = "0.12.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "tempfile"
version = "3.23.0"
@@ -3762,7 +3766,7 @@ dependencies = [
"half",
"quick-error",
"weezl",
"zune-jpeg",
"zune-jpeg 0.4.21",
]
[[package]]
@@ -3883,18 +3887,6 @@ dependencies = [
"tokio",
]
[[package]]
name = "toml"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
dependencies = [
"serde",
"serde_spanned 0.6.9",
"toml_datetime 0.6.11",
"toml_edit",
]
[[package]]
name = "toml"
version = "0.9.8"
@@ -3903,22 +3895,13 @@ checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned 1.0.3",
"toml_datetime 0.7.3",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
dependencies = [
"serde",
]
[[package]]
name = "toml_datetime"
version = "0.7.3"
@@ -3928,19 +3911,6 @@ dependencies = [
"serde_core",
]
[[package]]
name = "toml_edit"
version = "0.22.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap",
"serde",
"serde_spanned 0.6.9",
"toml_datetime 0.6.11",
"winnow",
]
[[package]]
name = "toml_parser"
version = "1.0.4"
@@ -3970,7 +3940,6 @@ dependencies = [
"serde",
"thiserror 2.0.17",
"tokio",
"tracing",
"tracing-loki",
"tracing-subscriber",
"url",
@@ -4309,12 +4278,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "version-compare"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
[[package]]
name = "version_check"
version = "0.9.5"
@@ -4484,9 +4447,9 @@ dependencies = [
[[package]]
name = "weezl"
version = "0.1.11"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "009936b22a61d342859b5f0ea64681cbb35a358ab548e2a44a8cf0dac2d980b8"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]]
name = "winapi"
@@ -4748,9 +4711,6 @@ name = "winnow"
version = "0.7.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf"
dependencies = [
"memchr",
]
[[package]]
name = "wit-bindgen"
@@ -4764,6 +4724,12 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9"
[[package]]
name = "y4m"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
[[package]]
name = "yaml-rust"
version = "0.4.5"
@@ -4948,6 +4914,12 @@ version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-core"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "111f7d9820f05fd715df3144e254d6fc02ee4088b0644c0ffd0efc9e6d9d2773"
[[package]]
name = "zune-inflate"
version = "0.2.54"
@@ -4963,5 +4935,14 @@ version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core",
"zune-core 0.4.12",
]
[[package]]
name = "zune-jpeg"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc6fb7703e32e9a07fb3f757360338b3a567a5054f21b5f52a666752e333d58e"
dependencies = [
"zune-core 0.5.0",
]

View File

@@ -1,5 +1,5 @@
[workspace]
members = ["crates/bin/*", "crates/lib/*", "crates/macro/*", "crates/service/*"]
members = ["crates/bin/*", "crates/lib/*", "crates/service/*"]
resolver = "2"
[workspace.package]
@@ -64,17 +64,13 @@ type_complexity = "allow"
#
[workspace.dependencies]
macro-sass = { path = "crates/macro/macro-sass" }
libservice = { path = "crates/lib/libservice" }
toolbox = { path = "crates/lib/toolbox" }
page = { path = "crates/lib/page" }
md-footnote = { path = "crates/lib/md-footnote" }
md-dev = { path = "crates/lib/md-dev" }
pixel-transform = { path = "crates/lib/pixel-transform" }
service-webpage = { path = "crates/service/service-webpage" }
#
# MARK: Server
#
@@ -89,7 +85,7 @@ utoipa-swagger-ui = { version = "9.0.2", features = [
"vendored",
] }
maud = { version = "0.27.0", features = ["axum"] }
grass = "0.13.4"
grass = { version = "0.13.4", features = ["macro"] }
markdown-it = "0.6.1"
emojis = "0.8.0"
reqwest = { version = "0.12.24", default-features = false, features = [
@@ -103,6 +99,11 @@ reqwest = { version = "0.12.24", default-features = false, features = [
"charset",
"blocking",
] }
servable = { version = "0.0.3", features = ["image", "htmx-2.0.8"] }
#servable = { path = "../servable/crates/servable", features = [
# "image",
# "htmx-2.0.8",
#] }
#

View File

@@ -21,3 +21,30 @@ This library decouples compiled binaries from the services they provide, and mak
- the `StaticAsset` servable serves static assets (css, images, misc files), and provides transformation parameters for image assets (via [`pixel-transform`](./crates/lib/pixel-transform)).
- [`service/service-webpage`](./crates/service/service-webpage): A `Service` that runs a `PageServer` that provides the content on [betalupi.com]
## Todo:
This web framework is nowhere near complete. Features are added as they are needed.
### Asset server
- generate asset server from dir, detect mime from file
- icon svg
- CORS,timeout, page cache
### Misc:
- reactive components with react or htmx
- handout search
- self-contained email mangler
- check asset paths at compile-time (or at least in a test)
### Content:
- TetrOS:
- https://git.betalupi.com/Mark/tetros
- https://git.betalupi.com/Mark/tetris-os
- Pick:
- https://git.betalupi.com/Mark/pick
- Minimax
- HTWAH

View File

@@ -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 }

File diff suppressed because one or more lines are too long

View File

@@ -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));
}
});

View File

@@ -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,
};

View File

@@ -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(&notfound);
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(),
})
})
}
}

View File

@@ -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()),
};
}
}
})
}
}

View File

@@ -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>,
>;
}

View File

@@ -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),
}
}
}

View File

@@ -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) })
}
}

View File

@@ -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(),
}
}
}

View File

@@ -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 }

View File

@@ -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);
}
}

View File

@@ -1,6 +0,0 @@
mod pixeldim;
pub mod transformers;
mod chain;
pub use chain::*;

View File

@@ -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"),
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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])
}
}
}
}

View File

@@ -12,7 +12,6 @@ tokio = { workspace = true }
[dependencies]
serde = { workspace = true }
tracing = { workspace = true }
num = { workspace = true }
thiserror = { workspace = true }
envy = { workspace = true }

View File

@@ -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")]

View File

@@ -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
//

View File

@@ -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,
}
}
}

View File

@@ -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()
}
*/

View File

@@ -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 }

View File

@@ -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)
}

View File

@@ -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 }

Binary file not shown.

View File

@@ -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};

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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::{
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,20 +61,14 @@ 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 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: &["
const LAZY_IMAGE_JS: &str = "
window.onload = function() {
var imgs = document.querySelectorAll('.img-placeholder');
@@ -116,18 +85,22 @@ const MAIN_TEMPLATE: PageTemplate = PageTemplate {
};
})
}
"],
";
styles_inline: &[],
styles_linked: &["/assets/css/main.css"],
/*
const MAIN_TEMPLATE: PageTemplate = PageTemplate {
// Order matters, base htmx goes first
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)
});

View File

@@ -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)
}

View File

@@ -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]

View File

@@ -6,4 +6,4 @@ extend-ignore-re = [
]
[files]
extend-exclude = ["crates/service/service-webpage/css", "crates/lib/page/htmx"]
extend-exclude = ["css", "crates/lib/page/htmx"]