diff --git a/Cargo.lock b/Cargo.lock
index 755c5a8..e1a6c6f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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",
]
diff --git a/Cargo.toml b/Cargo.toml
index 0d992d5..0a49cc3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -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",
+#] }
#
diff --git a/README.md b/README.md
index 2cba312..dda3ebd 100644
--- a/README.md
+++ b/README.md
@@ -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
diff --git a/crates/lib/page/Cargo.toml b/crates/lib/page/Cargo.toml
deleted file mode 100644
index 0ede90c..0000000
--- a/crates/lib/page/Cargo.toml
+++ /dev/null
@@ -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 }
diff --git a/crates/lib/page/htmx/htmx-2.0.8.min.js b/crates/lib/page/htmx/htmx-2.0.8.min.js
deleted file mode 100644
index faafa3e..0000000
--- a/crates/lib/page/htmx/htmx-2.0.8.min.js
+++ /dev/null
@@ -1 +0,0 @@
-var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.8"};Q.onLoad=V;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Ln;Q.find=f;Q.findAll=x;Q.closest=g;Q.remove=_;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=ze;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=j;Q.logNone=$;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:X,findThisElement:Se,filterValues:yn,swap:ze,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:q,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:D,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Te,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function y(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function q(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function D(e){const t=e.replace(/
]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L(''+t+"");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function P(e){return typeof e==="function"}function k(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function B(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function X(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function U(e){const t=new URL(e,"http://x");if(t){e=t.pathname+t.search}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function V(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function j(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function $(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(te(),e)}}function b(){return window}function _(e,t){e=w(e);if(t){b().setTimeout(function(){_(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function z(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ce(w(e));if(!e){return}if(n){b().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ce(w(e));if(!r){return}if(n){b().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=w(e);e.classList.toggle(t)}function Z(e,t){e=w(e);ie(e.parentElement.children,function(e){G(e,t)});K(ce(e),t)}function g(e,t){e=ce(w(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function pe(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=w(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=pe(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ce(t),pe(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),pe(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ce(t).nextElementSibling}else if(r.indexOf("next ")===0){e=ge(t,pe(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ce(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,pe(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=y(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(y(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var ge=function(t,e,n){const r=p(y(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ue(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function w(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function ye(e,t,n,r){if(P(t)){return{target:te().body,event:J(e),listener:t,options:n}}else{return{target:w(e),event:J(t),listener:n,options:r}}}function xe(t,n,r,o){Gn(function(){const e=ye(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=P(n);return e?n:r}function be(t,n,r){Gn(function(){const e=ye(t,n,r);e.target.removeEventListener(e.event,e.listener)});return P(n)?n:r}const ve=te().createElement("output");function we(t,n){const e=ne(t,n);if(e){if(e==="this"){return[Se(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ce(q(t,function(e){return e!==t&&s(ce(e),n)}));if(i){r.push(...we(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ce(q(e,function(e){return a(ce(e),t)!=null}))}function Ee(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ue(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ce(e){return Q.config.attributesToSettle.includes(e)}function Oe(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function He(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);$e(s,e,e,t,i);Re()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Re(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){ie(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Ae(l,e,c){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=p(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Le(e){return function(){G(e,Q.config.addedClass);Ft(ce(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=z(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Ae(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Le(o))}}}function Ie(e,t){let n=0;while(n0}function ze(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=w(h);const r=g.contextElement?y(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=D(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){b().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){b().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(k(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,E)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,C);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,C);u.pollInterval=d(O(o,/[,\[\s]/));O(o,C);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const f={trigger:c};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,C);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,E))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,E);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,E))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,E)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,E)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ct(e,t,n){const r=oe(e);r.timeout=b().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,c,e,u,f){const a=oe(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(u)){a.lastValue.set(u,new WeakMap)}a.lastValue.get(u).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(u,l,e)){return}const t=oe(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");c(l,e);a.throttle=b().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=b().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&F(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){b().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ue(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=Nt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ce(e),"button, input[type='submit']")}function Lt(e){return e.form||g(e,"form")}function Nt(e){const t=At(e.target);if(!t){return}const n=Lt(t);if(!n){return}return oe(n)}function It(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){Pe(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!X()){return null}t=U(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);ze(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){ze(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function nn(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function un(e){if(e instanceof HTMLSelectElement&&e.multiple){return M(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return M(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,un(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){cn(e.name,un(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Lt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const f=ee(u,"name");ln(f,u.value,o)}const c=we(e,"hx-include");ie(c,function(e){fn(n,r,i,ce(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=B(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ue(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){b().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ue(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c in n){if(n.hasOwnProperty(c)){if(i[c]==null){i[c]=n[c]}}}}return Cn(ce(u(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Ln(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:w(r)||ve,returnPromise:true})}else{let e=w(r.target);if(r.target&&!e||r.source&&!e&&!w(r.source)){e=ve}return he(t,n,w(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function Nn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function In(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const c=i.targetOverride||ce(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let u=oe(r);const f=u.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const L=ee(f,"formmethod");if(L!=null){if(de.includes(L.toLowerCase())){t=L}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ce(ue(r,I))}d=(N[1]||"drop").trim();u=oe(h);if(d==="drop"&&u.xhr&&u.abortable!==true){re(s);return e}else if(d==="abort"){if(u.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=B;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,c,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!In(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:c,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=Nn(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=t.etc.push||ne(e,"hx-push-url");const c=t.etc.replace||ne(e,"hx-replace-url");const u=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(c){f="replace";a=c}else if(u){f="push";a=s||i}if(a){if(a==="false"){return{}}if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};b().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}();
\ No newline at end of file
diff --git a/crates/lib/page/htmx/json-enc-1.9.12.js b/crates/lib/page/htmx/json-enc-1.9.12.js
deleted file mode 100644
index f37a9c5..0000000
--- a/crates/lib/page/htmx/json-enc-1.9.12.js
+++ /dev/null
@@ -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));
- }
-});
\ No newline at end of file
diff --git a/crates/lib/page/src/lib.rs b/crates/lib/page/src/lib.rs
deleted file mode 100644
index 314daa7..0000000
--- a/crates/lib/page/src/lib.rs
+++ /dev/null
@@ -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,
-};
diff --git a/crates/lib/page/src/route.rs b/crates/lib/page/src/route.rs
deleted file mode 100644
index 0853478..0000000
--- a/crates/lib/page/src/route.rs
+++ /dev/null
@@ -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> + '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> + '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>>,
- notfound: Arc,
-}
-
-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(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(mut self, route: impl Into, 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(self) -> Router {
- Router::new().fallback_service(self)
- }
-}
-
-//
-// MARK: impl Service
-//
-
-impl Service> for ServableRoute {
- type Response = Response;
- type Error = Infallible;
- type Future =
- Pin> + Send + 'static>>;
-
- fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {
- Poll::Ready(Ok(()))
- }
-
- fn call(&mut self, req: Request) -> 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::().copied();
- let route = req.uri().path().to_owned();
- let headers = req.headers().clone();
- let query: BTreeMap =
- serde_urlencoded::from_str(req.uri().query().unwrap_or("")).unwrap_or_default();
-
- let start = Instant::now();
- let client_info = ClientInfo::from_headers(&headers);
- let ua = headers
- .get("user-agent")
- .and_then(|x| x.to_str().ok())
- .unwrap_or("");
-
- trace!(
- message = "Serving route",
- route,
- addr = ?addr,
- user_agent = ua,
- device_type = ?client_info.device_type
- );
-
- // Normalize url with redirect
- if (route.ends_with('/') && route != "/") || route.contains("//") {
- let mut new_route = route.clone();
- while new_route.contains("//") {
- new_route = new_route.replace("//", "/");
- }
- let new_route = new_route.trim_matches('/');
-
- trace!(
- message = "Redirecting",
- route,
- new_route,
- addr = ?addr,
- user_agent = ua,
- device_type = ?client_info.device_type
- );
-
- let mut headers = HeaderMap::with_capacity(1);
- match HeaderValue::from_str(&format!("/{new_route}")) {
- Ok(x) => headers.append(header::LOCATION, x),
- Err(_) => return Ok(StatusCode::BAD_REQUEST.into_response()),
- };
- return Ok((StatusCode::PERMANENT_REDIRECT, headers).into_response());
- }
-
- let ctx = RenderContext {
- client_info,
- route,
- query,
- };
-
- let page = pages.get(&ctx.route).unwrap_or(¬found);
- let mut rend = match req.method() == Method::HEAD {
- true => page.head(&ctx).await.with_body(RenderedBody::Empty),
- false => page.render(&ctx).await,
- };
-
- // Tweak headers
- {
- if !rend.headers.contains_key(header::CACHE_CONTROL) {
- let max_age = rend.ttl.map(|x| x.num_seconds()).unwrap_or(1).max(1);
-
- let mut value = String::new();
- if rend.immutable {
- value.push_str("immutable, ");
- }
-
- value.push_str("public, ");
- value.push_str(&format!("max-age={}, ", max_age));
-
- #[expect(clippy::unwrap_used)]
- rend.headers.insert(
- header::CACHE_CONTROL,
- HeaderValue::from_str(value.trim().trim_end_matches(',')).unwrap(),
- );
- }
-
- if !rend.headers.contains_key("Accept-CH") {
- rend.headers
- .insert("Accept-CH", HeaderValue::from_static("Sec-CH-UA-Mobile"));
- }
-
- if !rend.headers.contains_key(header::CONTENT_TYPE)
- && let Some(mime) = &rend.mime
- {
- #[expect(clippy::unwrap_used)]
- rend.headers.insert(
- header::CONTENT_TYPE,
- HeaderValue::from_str(&mime.to_string()).unwrap(),
- );
- }
- }
-
- trace!(
- message = "Served route",
- route = ctx.route,
- addr = ?addr,
- user_agent = ua,
- device_type = ?client_info.device_type,
- time_ns = start.elapsed().as_nanos()
- );
-
- Ok(match rend.body {
- RenderedBody::Markup(m) => (rend.code, rend.headers, m.0).into_response(),
- RenderedBody::Static(d) => (rend.code, rend.headers, d).into_response(),
- RenderedBody::Bytes(d) => (rend.code, rend.headers, d).into_response(),
- RenderedBody::String(s) => (rend.code, rend.headers, s).into_response(),
- RenderedBody::Empty => (rend.code, rend.headers).into_response(),
- })
- })
- }
-}
diff --git a/crates/lib/page/src/servable/asset.rs b/crates/lib/page/src/servable/asset.rs
deleted file mode 100644
index 5739a4a..0000000
--- a/crates/lib/page/src/servable/asset.rs
+++ /dev/null
@@ -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> + '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> + '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()),
- };
- }
- }
- })
- }
-}
diff --git a/crates/lib/page/src/servable/mod.rs b/crates/lib/page/src/servable/mod.rs
deleted file mode 100644
index a550c20..0000000
--- a/crates/lib/page/src/servable/mod.rs
+++ /dev/null
@@ -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> + 'a + Send + Sync>>;
-
- /// Render this page
- fn render<'a>(
- &'a self,
- ctx: &'a crate::RenderContext,
- ) -> std::pin::Pin<
- Box> + 'a + Send + Sync>,
- >;
-}
diff --git a/crates/lib/page/src/servable/page.rs b/crates/lib/page/src/servable/page.rs
deleted file mode 100644
index 1f07482..0000000
--- a/crates/lib/page/src/servable/page.rs
+++ /dev/null
@@ -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,
- pub description: Option,
- pub image: Option,
-}
-
-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,
-
- /// A function that generates this page's html.
- ///
- /// This should return the contents of this page's tag,
- /// or the contents of a wrapper element (defined in the page server struct).
- ///
- /// This closure must never return `` or ``.
- pub generate_html: Arc<
- dyn Send
- + Sync
- + 'static
- + for<'a> Fn(
- &'a Page,
- &'a RenderContext,
- ) -> Pin + Send + Sync + 'a>>,
- >,
-
- pub response_code: StatusCode,
-
- pub scripts_inline: Vec,
- pub scripts_linked: Vec,
- pub styles_linked: Vec,
- pub styles_inline: Vec,
-
- /// `name`, `content` for extra `` 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) -> 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) -> Self {
- self.scripts_inline.push(script.into());
- self
- }
-
- pub fn with_script_linked(mut self, url: impl Into) -> Self {
- self.scripts_linked.push(url.into());
- self
- }
-
- pub fn with_style_inline(mut self, style: impl Into) -> Self {
- self.styles_inline.push(style.into());
- self
- }
-
- pub fn with_style_linked(mut self, url: impl Into) -> Self {
- self.styles_linked.push(url.into());
- self
- }
-
- pub fn with_extra_meta(mut self, key: impl Into, value: impl Into) -> Self {
- self.extra_meta.push((key.into(), value.into()));
- self
- }
-}
-
-impl Servable for Page {
- fn head<'a>(
- &'a self,
- _ctx: &'a RenderContext,
- ) -> Pin> + '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> + '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,
- 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 + 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),
- }
- }
-}
diff --git a/crates/lib/page/src/servable/redirect.rs b/crates/lib/page/src/servable/redirect.rs
deleted file mode 100644
index c6f044b..0000000
--- a/crates/lib/page/src/servable/redirect.rs
+++ /dev/null
@@ -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) -> Result {
- Ok(Self {
- to: HeaderValue::from_str(&to.into())?,
- })
- }
-}
-
-impl Servable for Redirect {
- fn head<'a>(
- &'a self,
- _ctx: &'a RenderContext,
- ) -> Pin> + '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> + 'a + Send + Sync>> {
- Box::pin(async { self.head(ctx).await.with_body(RenderedBody::Empty) })
- }
-}
diff --git a/crates/lib/page/src/types.rs b/crates/lib/page/src/types.rs
deleted file mode 100644
index c08a139..0000000
--- a/crates/lib/page/src/types.rs
+++ /dev/null
@@ -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),
- String(String),
- Empty,
-}
-
-pub trait RenderedBodyType {}
-impl RenderedBodyType for () {}
-impl RenderedBodyType for RenderedBody {}
-
-#[derive(Clone)]
-pub struct Rendered {
- pub code: StatusCode,
- pub headers: HeaderMap,
- pub body: T,
- pub mime: Option,
-
- /// How long to cache this response.
- /// If none, don't cache.
- pub ttl: Option,
- pub immutable: bool,
-}
-
-impl Rendered<()> {
- /// Turn this [Rendered] into a [Rendered] with a body.
- pub fn with_body(self, body: RenderedBody) -> Rendered {
- 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,
-}
-
-//
-// 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(),
- }
- }
-}
diff --git a/crates/lib/pixel-transform/Cargo.toml b/crates/lib/pixel-transform/Cargo.toml
deleted file mode 100644
index 10b09f3..0000000
--- a/crates/lib/pixel-transform/Cargo.toml
+++ /dev/null
@@ -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 }
diff --git a/crates/lib/pixel-transform/src/chain.rs b/crates/lib/pixel-transform/src/chain.rs
deleted file mode 100644
index d962940..0000000
--- a/crates/lib/pixel-transform/src/chain.rs
+++ /dev/null
@@ -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,
-}
-
-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 {
- 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), 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 {
- 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(deserializer: D) -> Result
- 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(&self, state: &mut H) {
- self.to_string().hash(state);
- }
-}
diff --git a/crates/lib/pixel-transform/src/lib.rs b/crates/lib/pixel-transform/src/lib.rs
deleted file mode 100644
index b2cb573..0000000
--- a/crates/lib/pixel-transform/src/lib.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-mod pixeldim;
-
-pub mod transformers;
-
-mod chain;
-pub use chain::*;
diff --git a/crates/lib/pixel-transform/src/pixeldim.rs b/crates/lib/pixel-transform/src/pixeldim.rs
deleted file mode 100644
index b742c21..0000000
--- a/crates/lib/pixel-transform/src/pixeldim.rs
+++ /dev/null
@@ -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 {
- 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(deserializer: D) -> Result
- 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"),
- }
- }
-}
diff --git a/crates/lib/pixel-transform/src/transformers/crop.rs b/crates/lib/pixel-transform/src/transformers/crop.rs
deleted file mode 100644
index 05943f7..0000000
--- a/crates/lib/pixel-transform/src/transformers/crop.rs
+++ /dev/null
@@ -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 {
- 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::()?;
- let h = args[1].trim().parse::()?;
-
- 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);
- }
- }
-}
diff --git a/crates/lib/pixel-transform/src/transformers/maxdim.rs b/crates/lib/pixel-transform/src/transformers/maxdim.rs
deleted file mode 100644
index ccefca8..0000000
--- a/crates/lib/pixel-transform/src/transformers/maxdim.rs
+++ /dev/null
@@ -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 {
- 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::()?;
- let h = args[1].parse::()?;
-
- 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);
- }
- }
-}
diff --git a/crates/lib/pixel-transform/src/transformers/mod.rs b/crates/lib/pixel-transform/src/transformers/mod.rs
deleted file mode 100644
index 95ef77d..0000000
--- a/crates/lib/pixel-transform/src/transformers/mod.rs
+++ /dev/null
@@ -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;
-}
-
-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 {
- 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(deserializer: D) -> Result
- 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])
- }
- }
- }
-}
diff --git a/crates/lib/toolbox/Cargo.toml b/crates/lib/toolbox/Cargo.toml
index 04a3c57..fb60695 100644
--- a/crates/lib/toolbox/Cargo.toml
+++ b/crates/lib/toolbox/Cargo.toml
@@ -12,7 +12,6 @@ tokio = { workspace = true }
[dependencies]
serde = { workspace = true }
-tracing = { workspace = true }
num = { workspace = true }
thiserror = { workspace = true }
envy = { workspace = true }
diff --git a/crates/lib/toolbox/src/lib.rs b/crates/lib/toolbox/src/lib.rs
index 036ddc5..c654cea 100644
--- a/crates/lib/toolbox/src/lib.rs
+++ b/crates/lib/toolbox/src/lib.rs
@@ -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")]
diff --git a/crates/lib/toolbox/src/logging.rs b/crates/lib/toolbox/src/logging.rs
index 52f9cdc..8e43cb5 100644
--- a/crates/lib/toolbox/src/logging.rs
+++ b/crates/lib/toolbox/src/logging.rs
@@ -70,6 +70,8 @@ impl From for EnvFilter {
format!("tower={}", conf.silence),
format!("reqwest={}", conf.silence),
format!("axum={}", conf.silence),
+ format!("selectors={}", conf.silence),
+ format!("html5ever={}", conf.silence),
//
// Libs
//
diff --git a/crates/lib/toolbox/src/mime.rs b/crates/lib/toolbox/src/mime.rs
deleted file mode 100644
index 4d99a82..0000000
--- a/crates/lib/toolbox/src/mime.rs
+++ /dev/null
@@ -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::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(&self, serializer: S) -> Result
- where
- S: Serializer,
- {
- serializer.serialize_str(&self.to_string())
- }
-}
-
-impl<'de> Deserialize<'de> for MimeType {
- fn deserialize(deserializer: D) -> Result
- 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 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::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 {
- 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 {
- 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,
- }
- }
-}
diff --git a/crates/lib/toolbox/src/misc.rs b/crates/lib/toolbox/src/misc.rs
deleted file mode 100644
index 68cb553..0000000
--- a/crates/lib/toolbox/src/misc.rs
+++ /dev/null
@@ -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()
-}
-*/
diff --git a/crates/macro/macro-sass/Cargo.toml b/crates/macro/macro-sass/Cargo.toml
deleted file mode 100644
index c2f54ad..0000000
--- a/crates/macro/macro-sass/Cargo.toml
+++ /dev/null
@@ -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 }
diff --git a/crates/macro/macro-sass/src/lib.rs b/crates/macro/macro-sass/src/lib.rs
deleted file mode 100644
index a991723..0000000
--- a/crates/macro/macro-sass/src/lib.rs
+++ /dev/null
@@ -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)
-}
diff --git a/crates/service/service-webpage/Cargo.toml b/crates/service/service-webpage/Cargo.toml
index 732ccc7..f8c90d9 100644
--- a/crates/service/service-webpage/Cargo.toml
+++ b/crates/service/service-webpage/Cargo.toml
@@ -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 }
diff --git a/crates/service/service-webpage/assets/lockhart.pdf b/crates/service/service-webpage/assets/lockhart.pdf
new file mode 100644
index 0000000..a0a41a2
Binary files /dev/null and b/crates/service/service-webpage/assets/lockhart.pdf differ
diff --git a/crates/service/service-webpage/src/components/md/mod.rs b/crates/service/service-webpage/src/components/md/mod.rs
index 61eb482..5512b27 100644
--- a/crates/service/service-webpage/src/components/md/mod.rs
+++ b/crates/service/service-webpage/src/components/md/mod.rs
@@ -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};
diff --git a/crates/service/service-webpage/src/pages/handouts.rs b/crates/service/service-webpage/src/pages/handouts.rs
index 0281bc1..b9e1772 100644
--- a/crates/service/service-webpage/src/pages/handouts.rs
+++ b/crates/service/service-webpage/src/pages/handouts.rs
@@ -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 = 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, reqwest::Error>>>,
- _page: &'a Page,
+ _page: &'a HtmlPage,
ctx: &'a RenderContext,
) -> Pin + Send + Sync + 'a>> {
Box::pin(async move {
diff --git a/crates/service/service-webpage/src/pages/index.rs b/crates/service/service-webpage/src/pages/index.rs
index a52c25e..65108f8 100644
--- a/crates/service/service-webpage/src/pages/index.rs
+++ b/crates/service/service-webpage/src/pages/index.rs
@@ -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 = 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 + Send + Sync + 'a>> {
Box::pin(async {
diff --git a/crates/service/service-webpage/src/pages/mod.rs b/crates/service/service-webpage/src/pages/mod.rs
index c6f2431..6dc34d2 100644
--- a/crates/service/service-webpage/src/pages/mod.rs
+++ b/crates/service/service-webpage/src/pages/mod.rs
@@ -1,57 +1,29 @@
use chrono::TimeDelta;
use maud::{Markup, PreEscaped, html};
-use page::{
- RenderContext,
- servable::{Page, PageMetadata, PageTemplate},
-};
+use reqwest::StatusCode;
+use servable::{HtmlPage, PageMetadata, RenderContext};
+use std::sync::LazyLock;
-use crate::components::{
- fa::FAIcon,
- md::{Markdown, meta_from_markdown},
- misc::FarLink,
+use crate::{
+ components::{
+ fa::FAIcon,
+ md::{Markdown, meta_from_markdown},
+ misc::FarLink,
+ },
+ routes::{IMG_ICON, MAIN_CSS},
};
mod handouts;
mod index;
-mod notfound;
-pub use handouts::handouts;
-pub use index::index;
-pub use notfound::notfound;
-
-pub fn links() -> Page {
- /*
- Dead links:
-
- https://www.commitstrip.com/en/
- http://www.3dprintmath.com/
- */
-
- page_from_markdown(
- include_str!("links.md"),
- Some("/assets/img/icon.png".to_owned()),
- )
-}
-
-pub fn betalupi() -> Page {
- page_from_markdown(
- include_str!("betalupi.md"),
- Some("/assets/img/icon.png".to_owned()),
- )
-}
-
-pub fn htwah_typesetting() -> Page {
- page_from_markdown(
- include_str!("htwah-typesetting.md"),
- Some("/assets/img/icon.png".to_owned()),
- )
-}
+pub use handouts::HANDOUTS;
+pub use index::INDEX;
//
// MARK: md
//
-fn page_from_markdown(md: impl Into, default_image: Option) -> Page {
+fn page_from_markdown(md: impl Into, default_image: Option) -> HtmlPage {
let md: String = md.into();
let md = Markdown::parse(&md);
@@ -68,8 +40,11 @@ fn page_from_markdown(md: impl Into, default_image: Option) -> P
let html = PreEscaped(md.render());
- MAIN_TEMPLATE
- .derive(meta, move |_page, ctx| {
+ HtmlPage::default()
+ .with_script_inline(LAZY_IMAGE_JS)
+ .with_style_linked(MAIN_CSS.route())
+ .with_meta(meta)
+ .with_render(move |_page, ctx| {
let html = html.clone();
Box::pin(async move {
@@ -86,48 +61,46 @@ fn page_from_markdown(md: impl Into, default_image: Option) -> P
}
})
})
- .html_ttl(Some(TimeDelta::days(1)))
- .immutable(true)
+ .with_ttl(Some(TimeDelta::days(1)))
}
//
// MARK: components
//
+const LAZY_IMAGE_JS: &str = "
+ window.onload = function() {
+ var imgs = document.querySelectorAll('.img-placeholder');
+
+ imgs.forEach(img => {
+ img.style.border = 'none';
+ img.style.filter = 'blur(10px)';
+ img.style.transition = 'filter 0.3s';
+
+ var lg = new Image();
+ lg.src = img.dataset.large;
+ lg.onload = function () {
+ img.src = img.dataset.large;
+ img.style.filter = 'blur(0px)';
+ };
+ })
+ }
+ ";
+
+/*
const MAIN_TEMPLATE: PageTemplate = PageTemplate {
// Order matters, base htmx goes first
- scripts_linked: &["/assets/htmx.js", "/assets/htmx-json.js"],
-
- // TODO: use htmx for this
- scripts_inline: &["
- window.onload = function() {
- var imgs = document.querySelectorAll('.img-placeholder');
-
- imgs.forEach(img => {
- img.style.border = 'none';
- img.style.filter = 'blur(10px)';
- img.style.transition = 'filter 0.3s';
-
- var lg = new Image();
- lg.src = img.dataset.large;
- lg.onload = function () {
- img.src = img.dataset.large;
- img.style.filter = 'blur(0px)';
- };
- })
- }
- "],
-
- styles_inline: &[],
- styles_linked: &["/assets/css/main.css"],
+ scripts: &[
+ ScriptSource::Linked(&"/assets/htmx-2.0.8.js"),
+ ScriptSource::Linked(&"/assets/htmx-json-1.19.12.js"),
+ ],
extra_meta: &[(
"viewport",
"width=device-width,initial-scale=1,user-scalable=no",
)],
-
- ..PageTemplate::const_default()
};
+*/
pub fn backlinks(ctx: &RenderContext) -> Option {
let mut backlinks = vec![("/", "home")];
@@ -184,3 +157,56 @@ pub fn footer() -> Markup {
}
)
}
+
+//
+// MARK: pages
+//
+
+pub const LINKS: LazyLock = 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 = LazyLock::new(|| {
+ page_from_markdown(include_str!("betalupi.md"), Some(IMG_ICON.route().into()))
+});
+
+pub const HTWAH_TYPESETTING: LazyLock = LazyLock::new(|| {
+ page_from_markdown(
+ include_str!("htwah-typesetting.md"),
+ Some(IMG_ICON.route().into()),
+ )
+});
+
+pub static NOT_FOUND: LazyLock = 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)
+});
diff --git a/crates/service/service-webpage/src/pages/notfound.rs b/crates/service/service-webpage/src/pages/notfound.rs
deleted file mode 100644
index 4f0d64a..0000000
--- a/crates/service/service-webpage/src/pages/notfound.rs
+++ /dev/null
@@ -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)
-}
diff --git a/crates/service/service-webpage/src/routes/mod.rs b/crates/service/service-webpage/src/routes/mod.rs
index e1dd814..417501e 100644
--- a/crates/service/service-webpage/src/routes/mod.rs
+++ b/crates/service/service-webpage/src/routes/mod.rs
@@ -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 = ServableWithRoute::new(
+ || "/assets/htmx-2.0.8.js".into(),
+ servable::HTMX_2_0_8.with_ttl(None),
+);
+
+pub static HTMX_JSON: ServableWithRoute = ServableWithRoute::new(
+ || "/assets/htmx-json-1.19.12.js".into(),
+ servable::EXT_JSON_1_19_12,
+);
+
+pub static MAIN_CSS: ServableWithRoute = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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]
diff --git a/crates/service/service-webpage/css/blocks.scss b/css/blocks.scss
similarity index 100%
rename from crates/service/service-webpage/css/blocks.scss
rename to css/blocks.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_animated.scss b/css/fontawesome/_animated.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_animated.scss
rename to css/fontawesome/_animated.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_bordered-pulled.scss b/css/fontawesome/_bordered-pulled.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_bordered-pulled.scss
rename to css/fontawesome/_bordered-pulled.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_core.scss b/css/fontawesome/_core.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_core.scss
rename to css/fontawesome/_core.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_fixed-width.scss b/css/fontawesome/_fixed-width.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_fixed-width.scss
rename to css/fontawesome/_fixed-width.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_functions.scss b/css/fontawesome/_functions.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_functions.scss
rename to css/fontawesome/_functions.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_icons.scss b/css/fontawesome/_icons.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_icons.scss
rename to css/fontawesome/_icons.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_list.scss b/css/fontawesome/_list.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_list.scss
rename to css/fontawesome/_list.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_mixins.scss b/css/fontawesome/_mixins.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_mixins.scss
rename to css/fontawesome/_mixins.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_rotated-flipped.scss b/css/fontawesome/_rotated-flipped.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_rotated-flipped.scss
rename to css/fontawesome/_rotated-flipped.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_screen-reader.scss b/css/fontawesome/_screen-reader.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_screen-reader.scss
rename to css/fontawesome/_screen-reader.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_shims.scss b/css/fontawesome/_shims.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_shims.scss
rename to css/fontawesome/_shims.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_sizing.scss b/css/fontawesome/_sizing.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_sizing.scss
rename to css/fontawesome/_sizing.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_stacked.scss b/css/fontawesome/_stacked.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_stacked.scss
rename to css/fontawesome/_stacked.scss
diff --git a/crates/service/service-webpage/css/fontawesome/_variables.scss b/css/fontawesome/_variables.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/_variables.scss
rename to css/fontawesome/_variables.scss
diff --git a/crates/service/service-webpage/css/fontawesome/brands.scss b/css/fontawesome/brands.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/brands.scss
rename to css/fontawesome/brands.scss
diff --git a/crates/service/service-webpage/css/fontawesome/fontawesome.scss b/css/fontawesome/fontawesome.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/fontawesome.scss
rename to css/fontawesome/fontawesome.scss
diff --git a/crates/service/service-webpage/css/fontawesome/regular.scss b/css/fontawesome/regular.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/regular.scss
rename to css/fontawesome/regular.scss
diff --git a/crates/service/service-webpage/css/fontawesome/solid.scss b/css/fontawesome/solid.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/solid.scss
rename to css/fontawesome/solid.scss
diff --git a/crates/service/service-webpage/css/fontawesome/v4-shims.scss b/css/fontawesome/v4-shims.scss
similarity index 100%
rename from crates/service/service-webpage/css/fontawesome/v4-shims.scss
rename to css/fontawesome/v4-shims.scss
diff --git a/crates/service/service-webpage/css/images.scss b/css/images.scss
similarity index 100%
rename from crates/service/service-webpage/css/images.scss
rename to css/images.scss
diff --git a/crates/service/service-webpage/css/main.scss b/css/main.scss
similarity index 100%
rename from crates/service/service-webpage/css/main.scss
rename to css/main.scss
diff --git a/crates/service/service-webpage/css/special.scss b/css/special.scss
similarity index 100%
rename from crates/service/service-webpage/css/special.scss
rename to css/special.scss
diff --git a/crates/service/service-webpage/css/text.scss b/css/text.scss
similarity index 100%
rename from crates/service/service-webpage/css/text.scss
rename to css/text.scss