//! # Rust Letter Backend
//!
//! `rust_letter_be` handles the backend execution using Rocket.
#[macro_use]
extern crate rocket;
/// A module that handles the backend for the site.
pub mod web_app_backend {
use rocket::fs::FileServer;
use rocket::http::{Cookie, CookieJar};
use rocket::response::Redirect;
use rocket::{Build, Rocket};
use rocket_dyn_templates::{context, Template};
use void_fe::void_app::{self, DarkModeProps, PoemRequest, VirtualDom};
#[get("/")]
async fn index(cookies: &CookieJar<'_>) -> Template {
let dark_mode = match cookies.get("dark-mode") {
Some(c) => {
if c.value() == "true" {
true
} else if c.value() == "false" {
false
} else {
false
}
}
None => false,
};
let mut vdom = VirtualDom::new_with_props(
void_app::HomePage,
DarkModeProps {
slug: Some("/".to_string()),
dark_mode,
},
);
let _ = vdom.rebuild();
let output = dioxus_ssr::render(&vdom);
Template::render(
"index",
context! {
app_title: "A Letter to the Void",
style_include: "",
test: &output,
dark_mode: match dark_mode {
true => "dark",
false => ""
},
},
)
}
#[get("/?dark_mode&")]
async fn dark_mode(cookies: &CookieJar<'_>, callback: &str) -> Redirect {
match cookies.get("dark-mode") {
Some(_) => cookies.remove(Cookie::named("dark-mode")),
None => cookies.add(Cookie::new("dark-mode", "true")),
};
let callback_uri = format!("{callback}");
Redirect::to(callback_uri)
}
#[get("/")]
async fn poem_list(cookies: &CookieJar<'_>) -> Template {
let dark_mode = match cookies.get("dark-mode") {
Some(c) => {
if c.value() == "true" {
true
} else if c.value() == "false" {
false
} else {
false
}
}
None => false,
};
let mut vdom = VirtualDom::new_with_props(
void_app::PoemListPage,
DarkModeProps {
slug: Some(String::from("/poems")),
dark_mode,
},
);
let _ = vdom.rebuild();
let output = dioxus_ssr::render(&vdom);
Template::render(
"index",
context! {
app_title: "A Letter to the Void",
style_include: "",
test: &output,
dark_mode: match dark_mode {
true => "dark",
false => ""
},
},
)
}
#[get("/")]
async fn poem(cookies: &CookieJar<'_>, entry: &str) -> Template {
let dark_mode = match cookies.get("dark-mode") {
Some(c) => {
if c.value() == "true" {
true
} else if c.value() == "false" {
false
} else {
false
}
}
None => false,
};
let mut vdom = VirtualDom::new_with_props(
void_app::PoemPage,
PoemRequest {
slug: format!("{entry}"),
dark_mode: Some(dark_mode),
},
);
let _ = vdom.rebuild();
let output = dioxus_ssr::render(&vdom);
Template::render(
"index",
context! {
app_title: "A Letter to the Void",
style_include: "",
test: &output,
dark_mode: match dark_mode {
true => "dark",
false => ""
},
},
)
}
/// This runs `rocket::build()` with the needed mounts and routes.
pub async fn build_rocket() -> Rocket {
rocket::build()
.mount("/images", FileServer::from("public/images"))
.mount("/styles", FileServer::from("public/styles"))
.mount("/fonts", FileServer::from("public/fonts"))
.mount("/poems", routes![poem_list, poem])
.mount("/", routes![dark_mode, index])
.attach(Template::fairing())
}
}