From 0617663b249f9ca488e5de652108b17d67fbaf45 Mon Sep 17 00:00:00 2001 From: Vika Date: Sat, 29 Jul 2023 21:59:56 +0300 Subject: Moved the entire Kittybox tree into the root --- templates/Cargo.toml | 33 ++ templates/assets/jslicense.html | 31 ++ templates/assets/onboarding.css | 33 ++ templates/assets/style.css | 236 ++++++++++++ templates/build.rs | 90 +++++ templates/javascript/dist/indieauth.js | 118 ++++++ templates/javascript/dist/webauthn/register.js | 1 + templates/javascript/src/indieauth.ts | 150 ++++++++ templates/javascript/src/lib.ts | 3 + templates/javascript/src/onboarding.ts | 120 +++++++ templates/javascript/src/webauthn/register.ts | 0 templates/javascript/tsconfig.json | 104 ++++++ templates/src/indieauth.rs | 201 +++++++++++ templates/src/lib.rs | 367 +++++++++++++++++++ templates/src/login.rs | 17 + templates/src/mf2.rs | 478 +++++++++++++++++++++++++ templates/src/onboarding.rs | 196 ++++++++++ templates/src/templates.rs | 168 +++++++++ 18 files changed, 2346 insertions(+) create mode 100644 templates/Cargo.toml create mode 100644 templates/assets/jslicense.html create mode 100644 templates/assets/onboarding.css create mode 100644 templates/assets/style.css create mode 100644 templates/build.rs create mode 100644 templates/javascript/dist/indieauth.js create mode 100644 templates/javascript/dist/webauthn/register.js create mode 100644 templates/javascript/src/indieauth.ts create mode 100644 templates/javascript/src/lib.ts create mode 100644 templates/javascript/src/onboarding.ts create mode 100644 templates/javascript/src/webauthn/register.ts create mode 100644 templates/javascript/tsconfig.json create mode 100644 templates/src/indieauth.rs create mode 100644 templates/src/lib.rs create mode 100644 templates/src/login.rs create mode 100644 templates/src/mf2.rs create mode 100644 templates/src/onboarding.rs create mode 100644 templates/src/templates.rs (limited to 'templates') diff --git a/templates/Cargo.toml b/templates/Cargo.toml new file mode 100644 index 0000000..38e73b3 --- /dev/null +++ b/templates/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "kittybox-frontend-renderer" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[build-dependencies] +libflate = "^2.0.0" +walkdir = "^2.3.2" + +[dev-dependencies] +faker_rand = "^0.1.1" +rand = "^0.8.5" +[dev-dependencies.microformats] +version="^0.3.0" + +[dependencies] +ellipse = "^0.2.0" +http = "^0.2.7" +markup = "^0.13.1" +serde_json = "^1.0.64" +include_dir = "^0.7.2" +axum = "^0.6.18" +[dependencies.chrono] +version = "^0.4.19" +features = ["serde"] +[dependencies.kittybox-util] +version = "0.1.0" +path = "../util" +[dependencies.kittybox-indieauth] +version = "0.1.0" +path = "../indieauth" \ No newline at end of file diff --git a/templates/assets/jslicense.html b/templates/assets/jslicense.html new file mode 100644 index 0000000..90c681c --- /dev/null +++ b/templates/assets/jslicense.html @@ -0,0 +1,31 @@ + + + + JavaScript licensing information for Kittybox + + +

All JavaScript included with Kittybox is licensed as free software, most of it under AGPL-3.0.

+ + + + + + + + + + + + + + + + + + + + + +
onboarding.jsAGPL-3.0onboarding.ts (Kittybox source code)
indieauth.jsAGPL-3.0indieauth.ts (Kittybox source code)
lib.jsAGPL-3.0lib.ts (Kittybox source code)
indieauth.jsAGPL-3.0indieauth.ts (Kittybox source code)
+ + diff --git a/templates/assets/onboarding.css b/templates/assets/onboarding.css new file mode 100644 index 0000000..6f191b9 --- /dev/null +++ b/templates/assets/onboarding.css @@ -0,0 +1,33 @@ +form.onboarding > ul#progressbar > li.active { + font-weight: bold; +} +form.onboarding > ul#progressbar { + display: flex; list-style: none; justify-content: space-around; +} + +form.onboarding > fieldset > div.switch_card_buttons { + display: flex; + justify-content: space-between; + width: 100%; +} +form.onboarding > fieldset > div.switch_card_buttons button:last-child { + margin-left: auto; +} +.form_group, .multi_input { + display: flex; + flex-direction: column; +} +.multi_input { + align-items: start; +} +.multi_input > input { + width: 100%; + align-self: stretch; +} +form.onboarding > fieldset > .form_group + * { + margin-top: .75rem; +} +form.onboarding textarea { + width: 100%; + resize: vertical; +} diff --git a/templates/assets/style.css b/templates/assets/style.css new file mode 100644 index 0000000..4cd7c09 --- /dev/null +++ b/templates/assets/style.css @@ -0,0 +1,236 @@ +@import url('https://fonts.googleapis.com/css2?family=Caveat:wght@500&family=Lato&display=swap'); + +:root { + font-family: var(--font-normal); + --font-normal: 'Lato', sans-serif; + --font-accent: 'Caveat', cursive; + --type-scale: 1.250; + + --primary-accent: purple; + --secondary-accent: gold; +} +* { + box-sizing: border-box; +} +body { + margin: 0; +} +h1, h2, h3, h4, h5, h6 { + font-family: var(--font-accent); +} +.titanic { + font-size: 3.815rem +} +h1, .xxxlarge { + margin-top: 0; + margin-bottom: 0; + font-size: 3.052rem; +} +h2, .xxlarge {font-size: 2.441rem;} +h3, .xlarge {font-size: 1.953rem;} +h4, .larger {font-size: 1.563rem;} +h5, .large {font-size: 1.25rem;} +h6, .normal {font-size: 1rem;} +small, .small { font-size: 0.8em; } + +nav#headerbar { + background: var(--primary-accent); + color: whitesmoke; + border-bottom: .75rem solid var(--secondary-accent); + padding: .3rem; + vertical-align: center; + /*position: sticky; + top: 0;*/ +} +nav#headerbar a#homepage { + font-weight: bolder; + font-family: var(--font-accent); + font-size: 2rem; +} +nav#headerbar > ul { + display: flex; + padding: inherit; + margin: inherit; + gap: .75em; +} +nav#headerbar > ul > li { + display: inline-flex; + flex-direction: column; + marker: none; + padding: inherit; + margin: inherit; + justify-content: center; +} +nav#headerbar > ul > li.shiftright { + margin-left: auto; +} +nav#headerbar a { + color: white; +} +body > main { + max-width: 60rem; + margin: auto; + padding: .75rem; +} +body > footer { + text-align: center; +} +.sidebyside { + display: flex; + flex-wrap: wrap; + gap: .75rem; + margin-top: .75rem; + margin-bottom: .75rem; +} +.sidebyside > * { + width: 100%; + margin-top: 0; + margin-bottom: 0; + border: .125rem solid black; + border-radius: .75rem; + padding: .75rem; + margin-top: 0 !important; + margin-bottom: 0 !important; + flex-basis: 28rem; + flex-grow: 1; +} +article > * + * { + margin-top: .75rem; +} +article > header { + padding-bottom: .75rem; + border-bottom: 1px solid gray; +} +article > footer { + border-top: 1px solid gray; +} +article.h-entry, article.h-feed, article.h-card, article.h-event { + border: 2px solid black; + border-radius: .75rem; + padding: .75rem; + margin-top: .75rem; + margin-bottom: .75rem; +} +.webinteractions > ul.counters { + display: inline-flex; + padding: inherit; + margin: inherit; + gap: .75em; + flex-wrap: wrap; +} +.webinteractions > ul.counters > li > .icon { + font-size: 1.5em; +} +.webinteractions > ul.counters > li { + display: inline-flex; + align-items: center; + gap: .5em; +} +article.h-entry > header.metadata ul { + padding-inline-start: unset; + margin: unset; +} +article.h-entry > header.metadata ul.categories { + flex-wrap: wrap; + display: inline-flex; + list-style-type: none; +} +article.h-entry > header.metadata ul.categories li { + display: inline; + margin-inline-start: unset; +} +article.h-entry > header.metadata ul li { + margin-inline-start: 2.5em; +} +article.h-entry .e-content pre { + border: 1px solid gray; + border-radius: 0.5em; + overflow-y: auto; + padding: 0.5em; +} +article.h-entry img.u-photo { + max-width: 80%; + max-height: 90vh; + display: block; + margin: auto; +} +article.h-entry img.u-photo + * { + margin-top: .75rem; +} +article.h-entry > header.metadata span + span::before { + content: " | " +} +li.p-category::before { + content: " #"; +} + +article.h-entry ul.categories { + gap: .2em; +} +article.h-card img.u-photo { + border-radius: 100%; + float: left; + height: 8rem; + border: 1px solid gray; + margin-right: .75em; + object-fit: cover; + aspect-ratio: 1; +} + +.mini-h-card img, #indieauth_page img { + height: 2em; + display: inline-block; + border: 2px solid gray; + border-radius: 100%; + margin-right: 0.5rem; +} + +.mini-h-card * { + vertical-align: middle; +} + +.mini-h-card a { + text-decoration: none; +} + +#indieauth_page > #introduction { + border: .125rem solid gray; + border-radius: .75rem; + margin: 1.25rem; + padding: .75rem; +} + +/* Rainbow hearts */ +/* TODO make toggleable by splitting into separate CSS file */ +@counter-style rainbow-hearts { + system: cyclic; + symbols: "❀️" "🧑" "πŸ’›" "πŸ’š" "πŸ’™" "πŸ’œ"; +} +body { + counter-reset: like-icons; +} +span.like-icon::before { + counter-increment: like-icons; + content: "" counter(like-icons, rainbow-hearts); +} +span.like-icon-label { + display: none; +} +ul.h-feed { + list-style: none; +} + +body > a#skip-to-content { + position: absolute; + width: 1px; + height: 1px; + margin: 0; + overflow: hidden; + clip: rect(1px, 1px, 1px, 1px); + background: white; + padding: 16px; +} +body > a#skip-to-content:focus { + width: auto; height: auto; clip: auto; + z-index: 999; +} diff --git a/templates/build.rs b/templates/build.rs new file mode 100644 index 0000000..ccd5b19 --- /dev/null +++ b/templates/build.rs @@ -0,0 +1,90 @@ +use std::ffi::OsStr; + +use libflate::gzip::Encoder; +use walkdir::WalkDir; + +fn main() -> Result<(), std::io::Error> { + use std::env; + let out_dir = std::path::PathBuf::from(env::var("OUT_DIR").unwrap()); + + println!("cargo::rerun-if-changed=javascript/"); + if let Ok(exit) = std::process::Command::new("tsc") + .arg("--outDir") + .arg(&out_dir) + .current_dir("javascript") + .spawn()? + .wait() + { + if !exit.success() { + std::process::exit(exit.code().unwrap_or(1)) + } + } + + println!("cargo:rerun-if-changed=assets/"); + let assets_path = std::path::Path::new("assets"); + let mut assets = WalkDir::new(&assets_path) + .into_iter(); + while let Some(Ok(entry)) = assets.next() { + if entry.file_type().is_dir() { + if let Err(err) = std::fs::create_dir(&out_dir.join(entry.path())) { + if err.kind() != std::io::ErrorKind::AlreadyExists { + return Err(err) + } + } + } else { + std::fs::copy(entry.path(), &out_dir.join(entry.path().strip_prefix(assets_path).unwrap()))?; + } + } + + let walker = WalkDir::new(&out_dir) + .into_iter() + .map(Result::unwrap) + .filter(|e| { + e.file_type().is_file() && e.path().extension().unwrap() != "gz" + }); + for entry in walker { + let normal_path = entry.path(); + let gzip_path = normal_path.with_extension({ + let mut extension = normal_path + .extension() + .unwrap() + .to_owned(); + extension.push(OsStr::new(".gz")); + extension + }); + eprintln!( + "{} -> {}", + normal_path.strip_prefix(&out_dir).unwrap().display(), + gzip_path.strip_prefix(&out_dir).unwrap().display() + ); + { + let mut out_file = std::fs::OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .open(&gzip_path)?; + + let mut in_file = std::fs::File::open(&normal_path)?; + + let mut encoder = Encoder::new(&mut out_file)?; + std::io::copy(&mut in_file, &mut encoder)?; + encoder.finish().into_result()?; + } + + let normal_len: f64 = std::fs::metadata(&normal_path).unwrap().len() as f64; + let gzipped_len: f64 = std::fs::metadata(&gzip_path).unwrap().len() as f64; + let ratio = gzipped_len / normal_len; + eprintln!("Ratio: {}", ratio); + if ratio <= 0.9 { + std::fs::remove_file(&normal_path)? + } else { + println!( + "cargo:warning={} compression ratio is {} (> 0.9), leaving as is", + entry.path().display(), + ratio + ); + std::fs::remove_file(&gzip_path)? + } + } + Ok(()) +} diff --git a/templates/javascript/dist/indieauth.js b/templates/javascript/dist/indieauth.js new file mode 100644 index 0000000..297b4b5 --- /dev/null +++ b/templates/javascript/dist/indieauth.js @@ -0,0 +1,118 @@ +"use strict"; +const WEBAUTHN_TIMEOUT = 60 * 1000; +async function webauthn_create_credential() { + const response = await fetch("/.kittybox/webauthn/pre_register"); + const { challenge, rp, user } = await response.json(); + return await navigator.credentials.create({ + publicKey: { + challenge: Uint8Array.from(challenge, (c) => c.charCodeAt(0)), + rp: rp, + user: { + id: Uint8Array.from(user.cred_id, (c) => c.charCodeAt(0)), + name: user.name, + displayName: user.displayName + }, + pubKeyCredParams: [{ alg: -7, type: "public-key" }], + authenticatorSelection: {}, + timeout: WEBAUTHN_TIMEOUT, + attestation: "none" + } + }); +} +async function webauthn_authenticate() { + const response = await fetch("/.kittybox/webauthn/pre_auth"); + const { challenge, credentials } = await response.json(); + try { + return await navigator.credentials.get({ + publicKey: { + challenge: Uint8Array.from(challenge, (c) => c.charCodeAt(0)), + allowCredentials: credentials.map(cred => ({ + id: Uint8Array.from(cred.id, c => c.charCodeAt(0)), + type: cred.type + })), + timeout: WEBAUTHN_TIMEOUT + } + }); + } + catch (e) { + console.error("WebAuthn authentication failed:", e); + alert("Using your authenticator failed. (Check the DevTools for details)"); + throw e; + } +} +async function submit_handler(e) { + e.preventDefault(); + if (e.target != null && e.target instanceof HTMLFormElement) { + const form = e.target; + let scopes; + if (form.elements.namedItem("scope") === undefined) { + scopes = []; + } + else if (form.elements.namedItem("scope") instanceof Node) { + scopes = [form.elements.namedItem("scope")] + .filter((e) => e.checked) + .map((e) => e.value); + } + else { + scopes = Array.from(form.elements.namedItem("scope")) + .filter((e) => e.checked) + .map((e) => e.value); + } + const authorization_request = { + response_type: form.elements.namedItem("response_type").value, + client_id: form.elements.namedItem("client_id").value, + redirect_uri: form.elements.namedItem("redirect_uri").value, + state: form.elements.namedItem("state").value, + code_challenge: form.elements.namedItem("code_challenge").value, + code_challenge_method: form.elements.namedItem("code_challenge_method").value, + // I would love to leave that as a list, but such is the form of + // IndieAuth. application/x-www-form-urlencoded doesn't have + // lists, so scopes are space-separated instead. It is annoying. + scope: scopes.length > 0 ? scopes.join(" ") : undefined, + }; + let credential = null; + switch (form.elements.namedItem("auth_method").value) { + case "password": + credential = form.elements.namedItem("user_password").value; + if (credential.length == 0) { + alert("Please enter a password."); + return; + } + break; + case "webauthn": + // credential = await webauthn_authenticate(); + alert("WebAuthn isn't implemented yet!"); + return; + break; + default: + alert("Please choose an authentication method."); + return; + } + console.log("Authorization request:", authorization_request); + console.log("Authentication method:", credential); + const body = JSON.stringify({ + request: authorization_request, + authorization_method: credential + }); + console.log(body); + const response = await fetch(form.action, { + method: form.method, + body: body, + headers: { + "Content-Type": "application/json" + } + }); + if (response.ok) { + let location = response.headers.get("Location"); + if (location != null) { + window.location.href = location; + } + else { + throw "Error: didn't return a location"; + } + } + } + else { + return; + } +} diff --git a/templates/javascript/dist/webauthn/register.js b/templates/javascript/dist/webauthn/register.js new file mode 100644 index 0000000..3918c74 --- /dev/null +++ b/templates/javascript/dist/webauthn/register.js @@ -0,0 +1 @@ +"use strict"; diff --git a/templates/javascript/src/indieauth.ts b/templates/javascript/src/indieauth.ts new file mode 100644 index 0000000..01732b7 --- /dev/null +++ b/templates/javascript/src/indieauth.ts @@ -0,0 +1,150 @@ +import { unreachable } from "./lib.js"; + +const WEBAUTHN_TIMEOUT = 60 * 1000; + +interface KittyboxWebauthnPreRegistrationData { + challenge: string, + rp: PublicKeyCredentialRpEntity, + user: { + cred_id: string, + name: string, + displayName: string + } +} + +async function webauthn_create_credential() { + const response = await fetch("/.kittybox/webauthn/pre_register"); + const { challenge, rp, user }: KittyboxWebauthnPreRegistrationData = await response.json(); + + return await navigator.credentials.create({ + publicKey: { + challenge: Uint8Array.from(challenge, (c) => c.charCodeAt(0)), + rp: rp, + user: { + id: Uint8Array.from(user.cred_id, (c) => c.charCodeAt(0)), + name: user.name, + displayName: user.displayName + }, + pubKeyCredParams: [{alg: -7, type: "public-key"}], + authenticatorSelection: {}, + timeout: WEBAUTHN_TIMEOUT, + attestation: "none" + } + }); +} + +interface KittyboxWebauthnCredential { + id: string, + type: "public-key" +} + +interface KittyboxWebauthnPreAuthenticationData { + challenge: string, + credentials: KittyboxWebauthnCredential[] +} + +async function webauthn_authenticate() { + const response = await fetch("/.kittybox/webauthn/pre_auth"); + const { challenge, credentials } = await response.json() as unknown as KittyboxWebauthnPreAuthenticationData; + + try { + return await navigator.credentials.get({ + publicKey: { + challenge: Uint8Array.from(challenge, (c) => c.charCodeAt(0)), + allowCredentials: credentials.map(cred => ({ + id: Uint8Array.from(cred.id, c => c.charCodeAt(0)), + type: cred.type + })), + timeout: WEBAUTHN_TIMEOUT + } + }) + } catch (e) { + console.error("WebAuthn authentication failed:", e); + alert("Using your authenticator failed. (Check the DevTools for details)"); + throw e; + } +} + +export async function submit_handler(e: SubmitEvent) { + e.preventDefault(); + if (e.target != null && e.target instanceof HTMLFormElement) { + const form = e.target as HTMLFormElement; + + let scopes: Array; + let scope_elem = form.elements.namedItem("scope"); + if (scope_elem == null) { + scopes = [] + } else if (scope_elem instanceof Element) { + scopes = ([scope_elem] as Array) + .filter((e: HTMLInputElement) => e.checked) + .map((e: HTMLInputElement) => e.value); + } else if (scope_elem instanceof RadioNodeList) { + scopes = (Array.from(scope_elem) as Array) + .filter((e: HTMLInputElement) => e.checked) + .map((e: HTMLInputElement) => e.value); + } else { + unreachable("HTMLFormControlsCollection returned something that's not null, Element or RadioNodeList") + } + + const authorization_request = { + response_type: (form.elements.namedItem("response_type") as HTMLInputElement).value, + client_id: (form.elements.namedItem("client_id") as HTMLInputElement).value, + redirect_uri: (form.elements.namedItem("redirect_uri") as HTMLInputElement).value, + state: (form.elements.namedItem("state") as HTMLInputElement).value, + code_challenge: (form.elements.namedItem("code_challenge") as HTMLInputElement).value, + code_challenge_method: (form.elements.namedItem("code_challenge_method") as HTMLInputElement).value, + // I would love to leave that as a list, but such is the form of + // IndieAuth. application/x-www-form-urlencoded doesn't have + // lists, so scopes are space-separated instead. It is annoying. + scope: scopes.length > 0 ? scopes.join(" ") : undefined, + }; + + let credential = null; + switch ((form.elements.namedItem("auth_method") as HTMLInputElement).value) { + case "password": + credential = (form.elements.namedItem("user_password") as HTMLInputElement).value; + if (credential.length == 0) { + alert("Please enter a password.") + return + } + break; + case "webauthn": + // credential = await webauthn_authenticate(); + alert("WebAuthn isn't implemented yet!") + return + break + default: + alert("Please choose an authentication method.") + return + } + + console.log("Authorization request:", authorization_request); + console.log("Authentication method:", credential); + + const body = JSON.stringify({ + request: authorization_request, + authorization_method: credential + }); + console.log(body); + + const response = await fetch(form.action, { + method: form.method, + body: body, + headers: { + "Content-Type": "application/json" + } + }); + + if (response.ok) { + let location = response.headers.get("Location"); + if (location != null) { + window.location.href = location + } else { + throw "Error: didn't return a location" + } + } + } else { + return + } + +} diff --git a/templates/javascript/src/lib.ts b/templates/javascript/src/lib.ts new file mode 100644 index 0000000..38ba65b --- /dev/null +++ b/templates/javascript/src/lib.ts @@ -0,0 +1,3 @@ +export function unreachable(msg: string): never { + throw new Error(msg); +} diff --git a/templates/javascript/src/onboarding.ts b/templates/javascript/src/onboarding.ts new file mode 100644 index 0000000..0b455eb --- /dev/null +++ b/templates/javascript/src/onboarding.ts @@ -0,0 +1,120 @@ +const firstOnboardingCard = "intro"; + +function switchOnboardingCard(card: string) { + (Array.from(document.querySelectorAll("form.onboarding > fieldset")) as HTMLElement[]) + .map((node: HTMLElement) => { + if (node.id == card) { + node.style.display = "block"; + } else { + node.style.display = "none"; + } + }); + + (Array.from(document.querySelectorAll("form.onboarding > ul#progressbar > li")) as HTMLElement[]) + .map(node => { + if (node.id == card) { + node.classList.add("active") + } else { + node.classList.remove("active") + } + }); +}; + +interface Window { + kittybox_onboarding: { + switchOnboardingCard: (card: string) => void + } +} + +window.kittybox_onboarding = { + switchOnboardingCard +}; + +(document.querySelector("form.onboarding > ul#progressbar") as HTMLElement).style.display = ""; +switchOnboardingCard(firstOnboardingCard); + +function switchCardOnClick(event: MouseEvent) { + if (event.target instanceof HTMLElement) { + if (event.target.dataset.card !== undefined) { + switchOnboardingCard(event.target.dataset.card) + } + } +} + +function multiInputAddMore(event: (MouseEvent | { target: HTMLElement })) { + if (event.target instanceof HTMLElement) { + let parent = event.target.parentElement; + if (parent !== null) { + let template = (parent.querySelector("template") as HTMLTemplateElement).content.cloneNode(true); + parent.prepend(template); + } + } +} + +(Array.from( + document.querySelectorAll( + "form.onboarding > fieldset button.switch_card" + ) +) as HTMLButtonElement[]) + .map(button => { + button.addEventListener("click", switchCardOnClick) + }); + +(Array.from( + document.querySelectorAll( + "form.onboarding > fieldset div.multi_input > button.add_more" + ) +) as HTMLButtonElement[]) + .map(button => { + button.addEventListener("click", multiInputAddMore) + multiInputAddMore({ target: button }); + }); + +const form = document.querySelector("form.onboarding") as HTMLFormElement; +console.log(form); +form.onsubmit = async (event: SubmitEvent) => { + console.log(event); + event.preventDefault(); + const form = event.target as HTMLFormElement; + const json = { + user: { + type: ["h-card"], + properties: { + name: [(form.querySelector("#hcard_name") as HTMLInputElement).value], + pronoun: (Array.from( + form.querySelectorAll("#hcard_pronouns") + ) as HTMLInputElement[]) + .map(input => input.value).filter(i => i != ""), + url: (Array.from(form.querySelectorAll("#hcard_url")) as HTMLInputElement[]) + .map(input => input.value).filter(i => i != ""), + note: [(form.querySelector("#hcard_note") as HTMLInputElement).value] + } + }, + first_post: { + type: ["h-entry"], + properties: { + content: [(form.querySelector("#first_post_content") as HTMLTextAreaElement).value] + } + }, + blog_name: (form.querySelector("#blog_name") as HTMLInputElement).value, + feeds: (Array.from( + form.querySelectorAll(".multi_input#custom_feeds > fieldset.feed") + ) as HTMLElement[]) + .map(form => { + return { + name: (form.querySelector("#feed_name") as HTMLInputElement).value, + slug: (form.querySelector("#feed_slug") as HTMLInputElement).value + } + }).filter(feed => feed.name == "" || feed.slug == "") + }; + + await fetch("/.kittybox/onboarding", { + method: "POST", + body: JSON.stringify(json), + headers: { "Content-Type": "application/json" } + }).then(response => { + if (response.status == 201) { + window.location.href = window.location.href; + } + }) +} diff --git a/templates/javascript/src/webauthn/register.ts b/templates/javascript/src/webauthn/register.ts new file mode 100644 index 0000000..e69de29 diff --git a/templates/javascript/tsconfig.json b/templates/javascript/tsconfig.json new file mode 100644 index 0000000..18b94c7 --- /dev/null +++ b/templates/javascript/tsconfig.json @@ -0,0 +1,104 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "es2022", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + "outDir": "./dist", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + // "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "include": ["src/**/*"] +} diff --git a/templates/src/indieauth.rs b/templates/src/indieauth.rs new file mode 100644 index 0000000..6a46773 --- /dev/null +++ b/templates/src/indieauth.rs @@ -0,0 +1,201 @@ +use kittybox_indieauth::{AuthorizationRequest, Scope}; +use kittybox_util::auth::EnrolledCredential; + +markup::define! { + AuthorizationRequestPage( + request: AuthorizationRequest, + credentials: Vec, + app: Option, + user: serde_json::Value + ) { + script[type="module"] { + @markup::raw(r#"import { submit_handler } from "/.kittybox/static/indieauth.js"; + +document.getElementById("indieauth_page").addEventListener("submit", submit_handler); +"#) + } + main { + form #indieauth_page[action="/.kittybox/indieauth/auth/confirm", method="POST"] { + noscript { + p {"I know how annoyed you can be about scripts." } + p { "But WebAuthn doesn't work without JavaScript. And passwords are horribly insecure, and everyone knows it deep inside their heart." } + p { b { "Please enable JavaScript for this page to work properly 😭" } } + } + div #introduction { + h1."mini-h-card" { + "Hi, " + @if let Some(photo) = user["properties"]["photo"][0].as_str() { + img.user_avatar[src=photo]; + } else if let Some(photo) = user["properties"]["photo"][0].as_object() { + img[ + src=photo["value"].as_str().unwrap(), + alt=photo["alt"].as_str().unwrap(), + loading="lazy" + ]; + } + @user["properties"]["name"][0].as_str().unwrap_or("administrator") + } + + p."mini-h-card" { + @if let Some(icon) = app + .as_ref() + .and_then(|app| app["properties"]["logo"][0].as_str()) + { + img.app_icon[src=icon]; + } else if let Some(icon) = app + .as_ref() + .and_then(|app| app["properties"]["logo"][0].as_object()) + { + img.app_icon[src=icon["src"].as_str().unwrap(), alt=icon["alt"].as_str().unwrap()]; + } + span { + a[href=app + .as_ref() + .and_then(|app| app["properties"]["url"][0].as_str()) + .unwrap_or_else(|| request.client_id.as_str()) + ] { + @app + .as_ref() + .and_then(|app| app["properties"]["name"][0].as_str()) + .unwrap_or_else(|| request.client_id.as_str()) + } + " wants to confirm your identity." + } + } + } + + @if request.scope.is_some() { + p { + "An application just requested access to your website. This can give access to your data, including private content." + } + + p { + "You can review the permissions the application requested below. You are free to not grant any permissions that the application requested if you don't trust it, at the cost of potentially reducing its functionality." + } + } + + fieldset #scopes { + legend { "Permissions to grant the app:" } + div { + input[type="checkbox", disabled="true", checked="true"]; + label[for="identify"] { + "Identify you as the owner of " + @user["properties"]["uid"][0].as_str().unwrap() + } + } + @if let Some(scopes) = &request.scope { + @for scope in scopes.iter() { + div { + input[type="checkbox", name="scope", id=scope.as_ref(), value=scope.as_ref()]; + label[for=scope.as_ref()] { + @match scope { + Scope::Profile => { + "Access your publicly visible profile information" + } + Scope::Email => { + "Access your email address" + } + Scope::Create => { + "Create new content on your website" + } + Scope::Update => { + "Modify content on your website" + } + Scope::Delete => { + "Delete content on your website" + } + Scope::Media => { + "Interact with your media storage" + } + other => { + @markup::raw(format!( + "(custom or unknown scope) {}", + other.as_ref() + )) + } + } + } + } + } + } + } + + fieldset { + legend { "Choose your preferred authentication method:" } + div { + input[type="radio", + name="auth_method", + id="auth_with_webauthn", + disabled=!credentials.iter().any(|e| *e == EnrolledCredential::WebAuthn), + checked=credentials.iter().any(|e| *e == EnrolledCredential::WebAuthn) + ]; + label[for="auth_with_webauthn"] { "Use an authenticator device to log in" } + } + div { + input[type="radio", + name="auth_method", value="password", + id="auth_with_password", + disabled=!credentials.iter().any(|e| *e == EnrolledCredential::Password), + checked=credentials.iter().all(|e| *e == EnrolledCredential::Password) + ]; + label[for="auth_with_password"] { "Password" } + br; + input[type="password", name="user_password", id="user_password"]; + } + } + + input[type="submit", value="Authenticate"]; + br; + + details { + summary { "View detailed data about this request" } + + p { + "More info about meanings of these fields can be found in " + a[href="https://indieauth.spec.indieweb.org/20220212/#authorization-request"] { + "the IndieAuth specification" + } ", which this webpage uses." + } + fieldset { + div { + label[for="response_type"] { "Response type (will most likely be \"code\")" } + br; + input[name="response_type", id="response_type", readonly, + value=request.response_type.as_str()]; + } + div { + label[for="state"] { "Request state" } + br; + input[name="state", id="state", readonly, + value=request.state.as_ref()]; + } + div { + label[for="client_id"] { "Client ID" } + br; + input[name="client_id", id="client_id", readonly, + value=request.client_id.as_str()]; + } + div { + label[for="redirect_uri"] { "Redirect URI" } + br; + input[name="redirect_uri", id="redirect_uri", readonly, + value=request.redirect_uri.as_str()]; + } + div { + label[for="code_challenge"] { "PKCE code challenge" } + br; + input[name="code_challenge", id="code_challenge", readonly, + value=request.code_challenge.as_str()]; + } + div { + label[for="code_challenge_method"] { "PKCE method (should be S256)" } + br; + input[name="code_challenge_method", id="code_challenge_method", readonly, + value=request.code_challenge.method().as_str()]; + } + } + } + } + } + } +} diff --git a/templates/src/lib.rs b/templates/src/lib.rs new file mode 100644 index 0000000..8d5d5fa --- /dev/null +++ b/templates/src/lib.rs @@ -0,0 +1,367 @@ +mod templates; +pub use templates::{ErrorPage, MainPage, Template}; +mod onboarding; +pub use onboarding::OnboardingPage; +mod indieauth; +pub use indieauth::AuthorizationRequestPage; +mod login; +pub use login::LoginPage; +mod mf2; +pub use mf2::{Entry, VCard, Feed, Food, POSTS_PER_PAGE}; + +pub mod assets { + use axum::response::{IntoResponse, Response}; + use axum::extract::Path; + use axum::http::StatusCode; + use axum::http::header::{CONTENT_TYPE, CONTENT_ENCODING, CACHE_CONTROL}; + + const ASSETS: include_dir::Dir<'static> = include_dir::include_dir!("$OUT_DIR/"); + const CACHE_FOR_A_DAY: &str = "max-age=86400"; + const GZIP: &str = "gzip"; + + pub async fn statics( + Path(path): Path + ) -> Response { + let content_type: &'static str = if path.ends_with(".js") { + "application/javascript" + } else if path.ends_with(".css") { + "text/css" + } else if path.ends_with(".html") { + "text/html; charset=\"utf-8\"" + } else { + "application/octet-stream" + }; + + match ASSETS.get_file(path.clone() + ".gz") { + Some(file) => (StatusCode::OK, + [(CONTENT_TYPE, content_type), + (CONTENT_ENCODING, GZIP), + (CACHE_CONTROL, CACHE_FOR_A_DAY)], + file.contents()).into_response(), + None => match ASSETS.get_file(path) { + Some(file) => (StatusCode::OK, + [(CONTENT_TYPE, content_type), + (CACHE_CONTROL, CACHE_FOR_A_DAY)], + file.contents()).into_response(), + None => StatusCode::NOT_FOUND.into_response() + } + } + } +} + +#[cfg(test)] +mod tests { + use faker_rand::en_us::internet::Domain; + use faker_rand::lorem::Word; + use microformats::types::{Document, Item, PropertyValue, Url}; + use serde_json::json; + use std::cell::RefCell; + use std::rc::Rc; + + enum PostType { + Note, + Article, + ReplyTo(serde_json::Value), + ReplyToLink(String), + LikeOf(serde_json::Value), + LikeOfLink(String), + } + + fn gen_hcard(domain: &str) -> serde_json::Value { + use faker_rand::en_us::names::FirstName; + + json!({ + "type": ["h-card"], + "properties": { + "name": [rand::random::().to_string()], + "photo": [format!("https://{domain}/media/me.png")], + "uid": [format!("https://{domain}/")], + "url": [format!("https://{domain}/")] + } + }) + } + + fn gen_random_post(domain: &str, kind: PostType) -> serde_json::Value { + use faker_rand::lorem::{Paragraph, Sentence}; + + fn html(content: Paragraph) -> serde_json::Value { + json!({ + "html": format!("

{}

", content), + "value": content.to_string() + }) + } + + let uid = format!( + "https://{domain}/posts/{}-{}-{}", + rand::random::(), + rand::random::(), + rand::random::() + ); + let dt = chrono::offset::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); + + match kind { + PostType::Note => { + let content = rand::random::(); + + json!({ + "type": ["h-entry"], + "properties": { + "content": [html(content)], + "published": [dt], + "uid": [&uid], "url": [&uid], + "author": [gen_hcard(domain)] + } + }) + } + PostType::Article => { + let content = rand::random::(); + let name = rand::random::(); + + json!({ + "type": ["h-entry"], + "properties": { + "content": [html(content)], + "published": [dt], + "uid": [&uid], "url": [&uid], + "author": [gen_hcard(domain)], + "name": [name.to_string()] + } + }) + } + PostType::ReplyTo(ctx) => { + let content = rand::random::(); + + json!({ + "type": ["h-entry"], + "properties": { + "content": [html(content)], + "published": [dt], + "uid": [&uid], "url": [&uid], + "author": [gen_hcard(domain)], + "in-reply-to": [{ + "type": ["h-cite"], + "properties": ctx["properties"] + }] + } + }) + } + PostType::ReplyToLink(link) => { + let content = rand::random::(); + + json!({ + "type": ["h-entry"], + "properties": { + "content": [html(content)], + "published": [dt], + "uid": [&uid], "url": [&uid], + "author": [gen_hcard(domain)], + "in-reply-to": [link] + } + }) + } + PostType::LikeOf(ctx) => { + json!({ + "type": ["h-entry"], + "properties": { + "published": [dt], + "author": [gen_hcard(domain)], + "uid": [&uid], "url": [&uid], + "like-of": [{ + "type": ["h-cite"], + "properties": ctx["properties"] + }] + } + }) + } + PostType::LikeOfLink(link) => { + json!({ + "type": ["h-entry"], + "properties": { + "published": [dt], + "author": [gen_hcard(domain)], + "uid": [&uid], "url": [&uid], + "like-of": [link] + } + }) + } + } + } + + fn check_dt_published(mf2: &serde_json::Value, item: &Rc>) { + use microformats::types::temporal::Value as TemporalValue; + + let _item = item.borrow(); + let props = _item.properties.borrow(); + assert!(props.contains_key("published")); + + if let Some(PropertyValue::Temporal(TemporalValue::Timestamp(item))) = + props.get("published").and_then(|v| v.first()) + { + use chrono::{DateTime, FixedOffset, NaiveDateTime}; + + // Faithfully reconstruct the original datetime + // I wonder why not just have an Enum that would + // get you either date, time or a datetime, + // potentially with an offset? + let offset = item.as_offset().unwrap().data; + let ndt: NaiveDateTime = item.as_date().unwrap().data + .and_time(item.as_time().unwrap().data) + // subtract the offset here, since we will add it back + - offset; + let dt = DateTime::::from_utc(ndt, offset); + + let expected: DateTime = chrono::DateTime::parse_from_rfc3339( + mf2["properties"]["published"][0].as_str().unwrap(), + ) + .unwrap(); + + assert_eq!(dt, expected); + } else { + unreachable!() + } + } + + fn check_e_content(mf2: &serde_json::Value, item: &Rc>) { + let _item = item.borrow(); + let props = _item.properties.borrow(); + assert!(props.contains_key("content")); + + if let Some(PropertyValue::Fragment(content)) = props.get("content").and_then(|v| v.first()) + { + assert_eq!( + content.html, + mf2["properties"]["content"][0]["html"].as_str().unwrap() + ); + } else { + unreachable!() + } + } + + #[test] + #[ignore = "see https://gitlab.com/maxburon/microformats-parser/-/issues/7"] + fn test_note() { + let mf2 = gen_random_post(&rand::random::().to_string(), PostType::Note); + + let html = crate::mf2::Entry { post: &mf2 }.to_string(); + + let url: Url = mf2 + .pointer("/properties/uid/0") + .and_then(|i| i.as_str()) + .and_then(|u| u.parse().ok()) + .unwrap(); + let parsed: Document = microformats::from_html(&html, url.clone()).unwrap(); + + if let Some(PropertyValue::Item(item)) = parsed.get_item_by_url(&url) { + let _item = item.borrow(); + let props = _item.properties.borrow(); + + check_e_content(&mf2, &item); + check_dt_published(&mf2, &item); + assert!(props.contains_key("uid")); + assert!(props.contains_key("url")); + assert!(props + .get("url") + .unwrap() + .iter() + .any(|i| i == props.get("uid").and_then(|v| v.first()).unwrap())); + // XXX: fails because of https://gitlab.com/maxburon/microformats-parser/-/issues/7 + assert!(!props.contains_key("name")); + } else { + unreachable!() + } + } + + #[test] + fn test_article() { + let mf2 = gen_random_post(&rand::random::().to_string(), PostType::Article); + let html = crate::mf2::Entry { post: &mf2 }.to_string(); + let url: Url = mf2 + .pointer("/properties/uid/0") + .and_then(|i| i.as_str()) + .and_then(|u| u.parse().ok()) + .unwrap(); + let parsed: Document = microformats::from_html(&html, url.clone()).unwrap(); + + if let Some(PropertyValue::Item(item)) = parsed.get_item_by_url(&url) { + let _item = item.borrow(); + let props = _item.properties.borrow(); + + check_e_content(&mf2, &item); + check_dt_published(&mf2, &item); + assert!(props.contains_key("uid")); + assert!(props.contains_key("url")); + assert!(props + .get("url") + .unwrap() + .iter() + .any(|i| i == props.get("uid").and_then(|v| v.first()).unwrap())); + assert!(props.contains_key("name")); + if let Some(PropertyValue::Plain(name)) = props.get("name").and_then(|v| v.first()) { + assert_eq!( + name, + mf2.pointer("/properties/name/0") + .and_then(|v| v.as_str()) + .unwrap() + ); + } else { + panic!("Name wasn't a plain property!"); + } + } else { + unreachable!() + } + } + + #[test] + fn test_like_of() { + for likeof in [ + PostType::LikeOf(gen_random_post( + &rand::random::().to_string(), + PostType::Note, + )), + PostType::LikeOfLink(format!( + "https://{}/posts/{}-{}-{}", + &rand::random::(), + &rand::random::(), + &rand::random::(), + &rand::random::(), + )), + ] { + let mf2 = gen_random_post(&rand::random::().to_string(), likeof); + let url: Url = mf2 + .pointer("/properties/uid/0") + .and_then(|i| i.as_str()) + .and_then(|u| u.parse().ok()) + .unwrap(); + let html = crate::mf2::Entry { post: &mf2 }.to_string(); + let parsed: Document = microformats::from_html(&html, url.clone()).unwrap(); + + if let Some(item) = parsed.items.get(0) { + let _item = item.borrow(); + let props = _item.properties.borrow(); + + check_dt_published(&mf2, item); + assert!(props.contains_key("like-of")); + match props.get("like-of").and_then(|v| v.first()) { + Some(PropertyValue::Url(url)) => { + assert_eq!( + url, + &mf2.pointer("/properties/like-of/0") + .and_then(|i| i.as_str()) + .or_else(|| mf2 + .pointer("/properties/like-of/0/properties/uid/0") + .and_then(|i| i.as_str())) + .and_then(|u| u.parse::().ok()) + .unwrap() + ); + } + Some(PropertyValue::Item(_cite)) => { + todo!() + } + other => panic!("Unexpected value in like-of: {:?}", other), + } + } else { + unreachable!() + } + } + } +} diff --git a/templates/src/login.rs b/templates/src/login.rs new file mode 100644 index 0000000..042c308 --- /dev/null +++ b/templates/src/login.rs @@ -0,0 +1,17 @@ +markup::define! { + LoginPage { + form[method="POST"] { + h1 { "Sign in with your website" } + p { + "Signing in to Kittybox might allow you to view private content " + "intended for your eyes only." + } + + section { + label[for="url"] { "Your website URL" } + input[id="url", name="url", placeholder="https://example.com/"]; + input[type="submit"]; + } + } + } +} diff --git a/templates/src/mf2.rs b/templates/src/mf2.rs new file mode 100644 index 0000000..33cd84a --- /dev/null +++ b/templates/src/mf2.rs @@ -0,0 +1,478 @@ +use ellipse::Ellipse; + +pub static POSTS_PER_PAGE: usize = 20; + +/// Return a pretty location specifier from a geo: URI. +fn decode_geo_uri(uri: &str) -> String { + if let Some(part) = uri.split(':').collect::>().get(1) { + if let Some(part) = part.split(';').next() { + let mut parts = part.split(','); + let lat = parts.next().unwrap(); + let lon = parts.next().unwrap(); + + // TODO - format them as proper latitude and longitude + format!("{}, {}", lat, lon) + } else { + uri.to_string() + } + } else { + uri.to_string() + } +} + +markup::define! { + Entry<'a>(post: &'a serde_json::Value) { + @if post.pointer("/properties/like-of").is_none() && post.pointer("/properties/bookmark-of").is_none() { + @FullEntry { post } + } else { + // Show a mini-post. + @MiniEntry { post } + } + } + MiniEntry<'a>(post: &'a serde_json::Value) { + article."h-entry mini-entry" { + @if let Some(author) = post["properties"]["author"][0].as_object() { + span."mini-h-card"."u-author" { + a."u-author"[href=author["properties"]["uid"][0].as_str().unwrap()] { + @if let Some(photo) = author["properties"]["photo"][0].as_str() { + img[src=photo, loading="lazy"]; + } else if author["properties"]["photo"][0].is_object() { + img[ + src=author["properties"]["photo"][0]["value"].as_str().unwrap(), + alt=author["properties"]["photo"][0]["alt"].as_str().unwrap(), + loading="lazy" + ]; + } + @author["properties"]["name"][0].as_str().unwrap() + } + } + @if let Some(likeof) = post["properties"]["like-of"][0].as_str() { + " " + span."like-icon"["aria-label"="liked"] { + span."like-icon-label"["aria-hidden"="true"] { + "❀️" + } + } + " " + a."u-like-of"[href=likeof] { @likeof } + } else if let Some(likeof) = post["properties"]["like-of"][0].as_object() { + a."u-like-of"[href=likeof["properties"]["url"][0].as_str().unwrap()] { + @likeof["properties"]["name"][0] + .as_str() + .unwrap_or_else(|| likeof["properties"]["url"][0].as_str().unwrap()) + } + } + @if let Some(bookmarkof) = post["properties"]["bookmark-of"][0].as_str() { + " πŸ”– " + a."u-bookmark-of"[href=bookmarkof] { @bookmarkof } + } else if let Some(bookmarkof) = post["properties"]["bookmark-of"][0].as_object() { + a."u-bookmark-of"[href=bookmarkof["properties"]["url"][0].as_str().unwrap()] { + @bookmarkof["properties"]["name"][0] + .as_str() + .unwrap_or_else(|| bookmarkof["properties"]["url"][0].as_str().unwrap()) + } + } + " " + a."u-url"."u-uid"[href=post["properties"]["uid"][0].as_str().unwrap()] { + @if let Some(published) = post["properties"]["published"][0].as_str() { + time."dt-published"[datetime=published] { + @chrono::DateTime::parse_from_rfc3339(published) + .map(|dt| dt.format("on %a %b %e %T %Y").to_string()) + .unwrap_or("sometime in the past".to_string()) + } + } else { + "sometime in the past" + } + } + } + } + } + FullEntry<'a>(post: &'a serde_json::Value) { + article."h-entry" { + header.metadata { + @if let Some(name) = post["properties"]["name"][0].as_str() { + h1."p-name" { @name } + } + @if let Some(author) = post["properties"]["author"][0].as_object() { + section."mini-h-card" { + a.larger."u-author"[href=author["properties"]["uid"][0].as_str().unwrap()] { + @if let Some(photo) = author["properties"]["photo"][0].as_str() { + img[src=photo, loading="lazy"]; + } else if let Some(photo) = author["properties"]["photo"][0].as_object() { + img[ + src=photo["value"].as_str().unwrap(), + alt=photo["alt"].as_str().unwrap(), + loading="lazy" + ]; + } + + @author["properties"]["name"][0].as_str().unwrap() + } + } + } + div { + span { + a."u-url"."u-uid"[href=post["properties"]["uid"][0].as_str().unwrap()] { + @if let Some(published) = post["properties"]["published"][0].as_str() { + time."dt-published"[datetime=published] { + @chrono::DateTime::parse_from_rfc3339(published) + .map(|dt| dt.format("%a %b %e %T %Y").to_string()) + .unwrap_or("sometime in the past".to_string()) + } + } + } + } + @if post["properties"]["visibility"][0].as_str().unwrap_or("public") != "public" { + span."p-visibility"[value=post["properties"]["visibility"][0].as_str().unwrap()] { + @post["properties"]["visibility"][0].as_str().unwrap() + } + } + @if post["properties"]["category"].is_array() { + span { + ul.categories { + "Tagged: " + @for cat in post["properties"]["category"].as_array().unwrap() { + li."p-category" { @cat.as_str().unwrap() } + } + } + } + } + @if post["properties"]["in-reply-to"].is_array() { + span { + "In reply to: " + ul.replyctx { + @for ctx in post["properties"]["in-reply-to"].as_array().unwrap() { + @if let Some(ctx) = ctx.as_str() { + li { + a."u-in-reply-to"[href=ctx] { + @ctx.truncate_ellipse(48).as_ref() + } + } + } else if let Some(ctx) = ctx.as_object() { + li { + a."u-in-reply-to"[href=ctx["properties"]["uid"][0] + .as_str() + .unwrap_or_else(|| ctx["properties"]["url"][0].as_str().unwrap())] + { + @ctx["properties"]["uid"][0] + .as_str() + .unwrap_or_else(|| ctx["properties"]["url"][0].as_str().unwrap()) + .truncate_ellipse(48) + .as_ref() + } + } + } + } + } + } + } + } + @if post["properties"]["url"].as_array().unwrap().len() > 1 { + hr; + ul { + "Pretty permalinks for this post:" + @for url in post["properties"]["url"].as_array().unwrap().iter().filter(|i| **i != post["properties"]["uid"][0]).map(|i| i.as_str().unwrap()) { + li { + a."u-url"[href=url] { @url } + } + } + } + } + @if let Some(links) = post["properties"]["syndication"].as_array() { + @if !links.is_empty() { + hr; + ul { + "Also published on:" + @for url in links.iter().filter_map(|i| i.as_str()) { + li { a."u-syndication"[href=url] { @url } } + } + } + } + } + @if post["properties"]["location"].is_array() || post["properties"]["checkin"].is_array() { + div { + @if post["properties"]["checkin"].is_array() { + span { + "Check-in to: " + @if post["properties"]["checkin"][0].is_string() { + // It's a URL + a."u-checkin"[href=post["properties"]["checkin"][0].as_str().unwrap()] { + @post["properties"]["checkin"][0].as_str().unwrap().truncate_ellipse(24).as_ref() + } + } else { + a."u-checkin"[href=post["properties"]["checkin"][0]["properties"]["uid"][0].as_str().unwrap()] { + @post["properties"]["checkin"][0]["properties"]["name"][0].as_str().unwrap() + } + } + } + } + @if post["properties"]["location"].is_array() { + span { + "Location: " + @if post["properties"]["location"][0].is_string() { + // It's a geo: URL + // We need to decode it + a."u-location"[href=post["properties"]["location"][0].as_str().unwrap()] { + @decode_geo_uri(post["properties"]["location"][0].as_str().unwrap()) + } + } else { + // It's an inner h-geo object + a."u-location"[href=post["properties"]["location"][0]["value"].as_str().map(|x| x.to_string()).unwrap_or(format!("geo:{},{}", post["properties"]["location"][0]["properties"]["latitude"][0].as_str().unwrap(), post["properties"]["location"][0]["properties"]["longitude"][0].as_str().unwrap()))] { + // I'm a lazy bitch + @decode_geo_uri(&post["properties"]["location"][0]["value"].as_str().map(|x| x.to_string()).unwrap_or(format!("geo:{},{}", post["properties"]["location"][0]["properties"]["latitude"][0].as_str().unwrap(), post["properties"]["location"][0]["properties"]["longitude"][0].as_str().unwrap()))) + } + } + } + } + } + } + @if post["properties"]["ate"].is_array() || post["properties"]["drank"].is_array() { + div { + @if post["properties"]["ate"].is_array() { + span { ul { + "Ate:" + @for food in post["properties"]["ate"].as_array().unwrap() { + li { + @if food.is_string() { + // If this is a string, it's a URL. + a."u-ate"[href=food.as_str().unwrap()] { + @food.as_str().unwrap().truncate_ellipse(24).as_ref() + } + } else { + // This is a rich food object (mm, sounds tasty! I wanna eat something tasty) + a."u-ate"[href=food["properties"]["uid"][0].as_str().unwrap_or("#")] { + @food["properties"]["name"][0].as_str() + .unwrap_or(food["properties"]["uid"][0].as_str().unwrap_or("#").truncate_ellipse(24).as_ref()) + } + } + } + } + } } + } + @if post["properties"]["drank"].is_array() { + span { ul { + "Drank:" + @for food in post["properties"]["drank"].as_array().unwrap() { + li { + @if food.is_string() { + // If this is a string, it's a URL. + a."u-drank"[href=food.as_str().unwrap()] { + @food.as_str().unwrap().truncate_ellipse(24).as_ref() + } + } else { + // This is a rich food object (mm, sounds tasty! I wanna eat something tasty) + a."u-drank"[href=food["properties"]["uid"][0].as_str().unwrap_or("#")] { + @food["properties"]["name"][0].as_str() + .unwrap_or(food["properties"]["uid"][0].as_str().unwrap_or("#").truncate_ellipse(24).as_ref()) + } + } + } + } + } } + } + } + } + } + @PhotoGallery { photos: post["properties"]["photo"].as_array() } + @if post["properties"]["content"][0]["html"].is_string() { + main."e-content" { + @markup::raw(post["properties"]["content"][0]["html"].as_str().unwrap().trim()) + } + } + @WebInteractions { post } + } + } + VCard<'a>(card: &'a serde_json::Value) { + article."h-card" { + @if card["properties"]["photo"][0].is_string() { + img."u-photo"[src=card["properties"]["photo"][0].as_str().unwrap()]; + } else if card["properties"]["photo"][0].is_object() { + img."u-photo"[ + src=card["properties"]["photo"][0]["value"].as_str().unwrap(), + alt=card["properties"]["photo"][0]["alt"].as_str().unwrap() + ]; + } + h1 { + a."u-url"."u-uid"."p-name"[href=card["properties"]["uid"][0].as_str().unwrap()] { + @card["properties"]["name"][0].as_str().unwrap() + } + } + @if card["properties"]["pronoun"].is_array() { + span { + "(" + @for (i, pronoun) in card["properties"]["pronoun"].as_array().unwrap().iter().filter_map(|v| v.as_str()).enumerate() { + span."p-pronoun" { + @pronoun + } + // Insert commas between multiple sets of pronouns + @if i < (card["properties"]["pronoun"].as_array().unwrap().len() - 1) {", "} + } + ")" + } + } + @if card["properties"]["note"].is_array() { + p."p-note" { + @card["properties"]["note"][0]["value"].as_str().unwrap_or_else(|| card["properties"]["note"][0].as_str().unwrap()) + } + } + @if card["properties"]["url"].is_array() { + ul { + "Can be found elsewhere at:" + @for url in card["properties"]["url"] + .as_array() + .unwrap() + .iter() + .filter_map(|v| v.as_str()) + .filter(|v| v != &card["properties"]["uid"][0].as_str().unwrap()) + .filter(|v| !card["properties"]["author"][0].as_str().is_some_and(|a| v.starts_with(a))) + { + li { a."u-url"[href=url, rel="me"] { @url } } + } + } + } + } + } + Food<'a>(food: &'a serde_json::Value) { + article."h-food" { + header.metadata { + h1 { + a."p-name"."u-url"[href=food["properties"]["url"][0].as_str().unwrap()] { + @food["properties"]["name"][0].as_str().unwrap() + } + } + } + @PhotoGallery { photos: food["properties"]["photo"].as_array() } + } + } + Feed<'a>(feed: &'a serde_json::Value, cursor: Option<&'a str>) { + div."h-feed" { + div.metadata { + @if feed["properties"]["name"][0].is_string() { + h1."p-name".titanic { + a[href=feed["properties"]["uid"][0].as_str().unwrap(), rel="feed"] { + @feed["properties"]["name"][0].as_str().unwrap() + } + } + } + } + @if feed["children"].is_array() { + @for child in feed["children"].as_array().unwrap() { + @match child["type"][0].as_str().unwrap() { + "h-entry" => { @Entry { post: child } } + "h-feed" => { @Feed { feed: child, cursor: None } } + "h-food" => { @Food { food: child } } + //"h-event" => { } + "h-card" => { @VCard { card: child } } + something_else => { + p { + "There's supposed to be an " + @something_else + " object here. But Kittybox can't render it right now." + small { "Sorry! TToTT" } + } + } + } + } + } + @if let Some(cursor) = cursor { + a[rel="prev", href=format!("{}?after={}", feed["properties"]["uid"][0].as_str().unwrap(), cursor)] { + "Older posts" + } + } else { + p { + "Looks like you reached the end. Wanna jump back to the " + a[href=feed["properties"]["uid"][0].as_str().unwrap()] { + "beginning" + } "?" + } + } + } + } + + //======================================= + // Components library + //======================================= + PhotoGallery<'a>(photos: Option<&'a Vec>) { + @if let Some(photos) = photos { + @for photo in photos.iter() { + @if let Some(photo) = photo.as_str() { + img."u-photo"[src=photo, loading="lazy"]; + } else if photo.is_object() { + @if let Some(thumbnail) = photo["thumbnail"].as_str() { + a."u-photo"[href=photo["value"].as_str().unwrap()] { + img[src=thumbnail, + loading="lazy", + alt=photo["alt"].as_str().unwrap_or("") + ]; + } + } else { + img."u-photo"[src=photo["value"].as_str().unwrap(), + loading="lazy", + alt=photo["alt"].as_str().unwrap_or("") + ]; + } + } + } + } + } + WebInteractions<'a>(post: &'a serde_json::Value) { + footer.webinteractions { + p[style="display: none", "aria-hidden"="false"] { + "Webmention counters:" + } + ul.counters { + li { + span."icon like-icon"["aria-label"="likes"] { + span."like-icon-label"["aria-hidden"="true"] { + "❀️" + } + } + span.counter { @post["properties"]["like"].as_array().map(|a| a.len()).unwrap_or(0) } + } + li { + span.icon["aria-label"="replies"] { "πŸ’¬" } + span.counter { @post["properties"]["comment"].as_array().map(|a| a.len()).unwrap_or(0) } + } + li { + span.icon["aria-label"="reposts"] { "πŸ”„" } + span.counter { @post["properties"]["repost"].as_array().map(|a| a.len()).unwrap_or(0) } + } + li { + span.icon["aria-label"="bookmarks"] { "πŸ”–" } + span.counter { @post["properties"]["bookmark"].as_array().map(|a| a.len()).unwrap_or(0) } + } + } + /*@if ( + post["properties"]["like"].as_array().map(|a| a.len()).unwrap_or(0) + + post["properties"]["bookmark"].as_array().map(|a| a.len()).unwrap_or(0) + + post["properties"]["repost"].as_array().map(|a| a.len()).unwrap_or(0) + + post["properties"]["comment"].as_array().map(|a| a.len()).unwrap_or(0) + ) > 0 { + details { + summary { "Show comments and reactions" } + // TODO actually render facepiles and comments + @if let Some(likes) = post["properties"]["like"].as_array() { + @if !likes.is_empty() { + // Show a facepile of likes for a post + } + } + @if let Some(bookmarks) = post["properties"]["bookmark"].as_array() { + @if !bookmarks.is_empty() { + // Show a facepile of bookmarks for a post + } + } + @if let Some(reposts) = post["properties"]["repost"].as_array() { + @if !reposts.is_empty() { + // Show a facepile of reposts for a post + } + } + @if let Some(comments) = post["properties"]["comment"].as_array() { + @for comment in comments.iter() { + // Show all the comments recursively (so we could do Salmention with them) + } + } + } + }*/ + } + } +} diff --git a/templates/src/onboarding.rs b/templates/src/onboarding.rs new file mode 100644 index 0000000..e2f07df --- /dev/null +++ b/templates/src/onboarding.rs @@ -0,0 +1,196 @@ +markup::define! { + OnboardingPage { + h1[style="text-align: center"] { + "Welcome to Kittybox" + } + script[type="module", src="/.kittybox/static/onboarding.js"] {} + link[rel="stylesheet", href="/.kittybox/static/onboarding.css"]; + form.onboarding[action="", method="POST"] { + noscript { + p { + "Ok, let's be honest. Most of this software doesn't require JS to be enabled " + "to view pages (and in some cases, even edit them if logged in)." + } + p { "This page is a little bit different. It uses JavaScript to provide interactive features, such as:" } + ul { + li { "Multiple-input questions" } + li { "Answers spanning multiple fields" } + li { "Preview of files being uploaded" } + li { "Pretty pagination so you won't feel overwhelmed" } + } + p { + "Sadly, it's very hard or even impossible to recreate this without any JavaScript. " + "Good news though - the code is " b { "open-source AND free software" } + " (under GNU AGPLv3) " + "and I promise to not obfuscate it or minify it. " + a[href="/.kittybox/static/onboarding.js"] { "Here" } + "'s the link - you can try reading it so you'll be 200% sure " + "it won't steal your cookies or turn your kitty into a soulless monster." + @markup::raw("") + } + hr; + p { + "In other words: " + b { "please enable JavaScript for this page to work properly." } + small { "sorry T__T" } + } + } + ul #progressbar[style="display: none"] { + li #intro { "Introduction" } + li #hcard { "Your profile" } + li #settings { "Your website" } + li #firstpost { "Your first post" } + } + fieldset #intro[style="display: none"] { + legend { "Introduction" } + p { + "Kittybox is a CMS that can act as a member of the IndieWeb. " + "IndieWeb is a global distributed social network built on top of open Web standards " + "and composed of blogs around the Internet supporting these standards." + } + p { "There is no registration or centralized database of any sort - everyone owns their data and is responsible for it." } + p { "If you're seeing this page, it looks like your configuration is correct and we can proceed with the setup." } + + div.switch_card_buttons { + button.switch_card.next_card[type="button", "data-card"="hcard"] { "Next" } + } + } + + fieldset #hcard[style="display: none"] { + legend { "Your profile" } + p { "An h-card is an IndieWeb social profile, and we're gonna make you one!" } + p { "Thanks to some clever markup, it will be readable by both humans and machines looking at your homepage."} + p { + "If you make a mistake, don't worry, you're gonna be able to edit this later." + "The only mandatory field is your name." + } + + div.form_group { + label[for="hcard_name"] { "Your name" } + input #hcard_name[name="hcard_name", placeholder="Your name"]; + small { + "No need to write the name as in your passport, this is not a legal document " + "- just write how you want to be called on the network. This name will be also " + "shown whenever you leave a comment on someone else's post using your website." + } + } + + div.form_group { + label[for="pronouns"] { "Your pronouns" } + div.multi_input #pronouns { + template { + input #hcard_pronouns[name="hcard_pronouns", placeholder="they/them?"]; + } + button.add_more[type="button", "aria-label"="Add more"] { "[+] Add more" } + } + small { + "Write which pronouns you use for yourself. It's a free-form field " + "so don't feel constrained - but keep it compact, as it'll be shown in a lot of places." + } + } + + div.form_group { + label[for="urls"] { "Links to other pages of you" } + div.multi_input #urls { + template { + input #hcard_url[name="hcard_url", placeholder="https://example.com/"]; + } + button.add_more[type="button", "aria-label"="Add more"] { "[+] Add more" } + } + small { + "These URLs will help your readers find you elsewhere and will help you that whoever owns these pages owns your website too" + " in case the links are mutual. So make sure to put a link to your site in your other social profiles!" + } + } + + div.form_group { + label[for="hcard_note"] { "A little about yourself" } + textarea #hcard_note[name="hcard_note", placeholder="Loves cooking, plants, cats, dogs and racoons."] {} + small { "A little bit of introduction. Just one paragraph, and note, you can't use HTML here (yet)." } + // TODO: HTML e-note instead of p-note + } + + // TODO: u-photo upload - needs media endpoint cooperation + + div.switch_card_buttons { + button.switch_card.prev_card[type="button", "data-card"="intro"] { "Previous" } + button.switch_card.next_card[type="button", "data-card"="settings"] { "Next" } + } + } + + fieldset #settings[style="display: none"] { + legend { "Your website" } + p { "Ok, it's nice to know you more. Tell me about what you'll be writing and how you want to name your blog." } + // TODO: site-name, saved to settings + + div.form_group { + label[for="blog_name"] { "Your website's name"} + input #blog_name[name="blog_name", placeholder="Kitty Box!"]; + small { "It'll get shown in the title of your blog, in the upper left corner!" } + } + + div.form_group { + label[for="custom_feeds"] { "Custom feeds" } + small { + p { + "You can set up custom feeds to post your stuff to. " + "This is a nice way to organize stuff into huge folders, like all your trips or your quantified-self data." + } + p { + "Feeds can be followed individually, which makes it easy for users who are interested in certain types " + "of content you produce to follow your adventures in certain areas of your life without cluttering their " + "readers." + } + p { + "We will automatically create some feeds for you aside from these so you won't have to - including a main feed, " + "address book (for venues you go to and people you talk about), a cookbook for your recipes and some more." + // TODO: Put a link to documentation explaining feeds in more detail. + } + } + div.multi_input #custom_feeds { + template { + fieldset.feed { + div.form_group { + label[for="feed_name"] { "Name" } + input #feed_name[name="feed_name", placeholder="My cool feed"]; + small { "This is a name that will identify this feed to the user. Make it short and descriptive!" } + } + div.form_group { + label[for="feed_slug"] { "Slug" } + input #feed_slug[name="feed_slug", placeholder="my-cool-feed"]; + small { "This will form a pretty URL for the feed. For example: https://example.com/feeds/my-cool-feed" } + } + } + } + button.add_more[type="button", "aria-label"="Add more"] { "[+] Add More" } + } + } + + div.switch_card_buttons { + button.switch_card.prev_card[type="button", "data-card"="hcard"] { "Previous" } + button.switch_card.next_card[type="button", "data-card"="firstpost"] { "Next" } + } + } + + fieldset #firstpost[style="display: none"] { + legend { "Your first post" } + p { "Maybe you should start writing your first posts now. How about a short note?" } + p { "A note is a short-form post (not unlike a tweet - but without the actual character limit) that doesn't bear a title." } + p { + "Consider telling more about yourself, your skills and interests in this note " + @markup::raw("—") + " though you're free to write anything you want. (By the way, you can use " + a[href="https://daringfireball.net/projects/markdown/syntax"] { "Markdown" } + " here to spice up your note!)" + } + + textarea #first_post_content[style="width: 100%; height: 8em", placeholder="Hello! I am really excited about #IndieWeb"] {} + + div.switch_card_buttons { + button.switch_card.prev_card[type="button", "data-card"="settings"] { "Previous" } + button[type="submit"] { "Finish" } + } + } + } + } +} diff --git a/templates/src/templates.rs b/templates/src/templates.rs new file mode 100644 index 0000000..63c67c5 --- /dev/null +++ b/templates/src/templates.rs @@ -0,0 +1,168 @@ +use http::StatusCode; +use kittybox_util::MicropubChannel; + +use crate::{Feed, VCard}; + +markup::define! { + Template<'a>(title: &'a str, blog_name: &'a str, feeds: Vec, user: Option, content: String) { + @markup::doctype() + html { + head { + title { @title } + link[rel="preconnect", href="https://fonts.gstatic.com"]; + link[rel="stylesheet", href="/.kittybox/static/style.css"]; + meta[name="viewport", content="initial-scale=1, width=device-width"]; + + link[rel="micropub", href="/.kittybox/micropub"]; + link[rel="micropub_media", href="/.kittybox/media"]; + link[rel="indieauth_metadata", href="/.kittybox/indieauth/metadata"]; + link[rel="webmention", href="/.kittybox/webmention"]; + // legacy links for some dumb clients + link[rel="authorization_endpoint", href="/.kittybox/indieauth/auth"]; + link[rel="token_endpoint", href="/.kittybox/indieauth/token"]; + // LibreJS-compliant JS licensing info (because TypeScript is a bitch) + link[rel="jslicense", href="/.kittybox/static/jslicense.html"]; + /*@if let Some(endpoints) = endpoints { + @if let Some(webmention) = &endpoints.webmention { + link[rel="webmention", href=&webmention]; + } + @if let Some(microsub) = &endpoints.microsub { + link[rel="microsub", href=µsub]; + } + }*/ + } + body { + a[href="#main_content", id="skip-to-content"] { "Skip to content" } + // TODO Somehow compress headerbar into a menu when the screen space is tight + nav #headerbar { + ul { + li { a #homepage[href="/"] { @blog_name } } + @for feed in feeds.iter() { + li { a[href=&feed.uid] { @feed.name } } + } + li.shiftright { + @if user.is_none() { + a #login[href="/login"] { "Sign in" } + } else { + span { + @user.as_ref().unwrap() " - " a #logout[href="/logout"] { "Sign out" } + } + } + } + } + } + main #main_content { + @markup::raw(content) + } + footer { + p { + "Powered by " a[href="https://sr.ht/~vikanezrimaya/kittybox"] { + "Kittybox" + } + } + } + } + } + } + MainPage<'a>(feed: &'a serde_json::Value, card: &'a serde_json::Value, cursor: Option<&'a str>, webring: bool) { + .sidebyside { + @VCard { card } + #dynamicstuff { + div { + p { "This section will provide interesting statistics or tidbits about my life in this exact moment (with maybe a small delay)." } + p { "It will probably require JavaScript to self-update, but I promise to keep this widget lightweight and open-source!" } + p { small { + "JavaScript isn't a menace, stop fearing it or I will switch to WebAssembly " + "and knock your nico-nico-kneecaps so fast with its speed you won't even notice that... " + small { "omae ha mou shindeiru" } + @markup::raw("") + } } + } + @if *webring { + #webring { + a[href="https://xn--sr8hvo.ws/previous"] { "←" } + " An " + a[href="https://xn--sr8hvo.ws"] { + "IndieWeb Webring" + } + " πŸ•ΈπŸ’ " + a[href="https://xn--sr8hvo.ws/next"] { "β†’" } + } + } + } + } + @Feed { feed, cursor: *cursor } + } + ErrorPage(code: StatusCode, msg: Option) { + h1 { @format!("HTTP {code}") } + @match *code { + StatusCode::UNAUTHORIZED => { + p { "Looks like you need to authenticate yourself before seeing this page. Try logging in with IndieAuth using the Login button above!" } + } + StatusCode::FORBIDDEN => { + p { "Looks like you're forbidden from viewing this page." } + p { + "This might've been caused by being banned from viewing my website" + "or simply by trying to see what you're not supposed to see, " + "like a private post that's not intended for you. It's ok, it happens." + } + } + StatusCode::GONE => { + p { "Looks like the page you're trying to find is gone and is never coming back." } + } + StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS => { + p { "The page is there, but I can't legally provide it to you because the censorship said so." } + } + StatusCode::NOT_FOUND => { + p { "Looks like there's no such page. Maybe you or someone else mistyped a URL or my database experienced data loss." } + } + StatusCode::IM_A_TEAPOT => { + p { "Wait, do you seriously expect my website to brew you coffee? It's not a coffee machine!" } + + p { + small { + "I could brew you some coffee tho if we meet one day... " + small { + i { + "i-it's nothing personal, I just like brewing coffee, b-baka!!!~ >. { + @match msg { + None => { + p { + "There was an undescribed error in your request. " + "Please try again later or with a different request." + } + } + Some(msg) => { + p { + "There was a following error in your request:" + } + blockquote { pre { @msg } } + } + } + } + StatusCode::INTERNAL_SERVER_ERROR => { + @match msg { + None => { + p { "It seems like you have found an error. Not to worry, it has already been logged." } + } + Some(msg) => { + p { "The server encountered an error while processing your request:" } + blockquote { @msg } + p { "Don't worry, it has already been logged." } + } + } + } + _ => { + p { "It seems like you have found an error. Not to worry, it has already been logged." } + } + } + P { "For now, may I suggest to visit " a[href="/"] {"the main page"} " of this website?" } + + } +} -- cgit 1.4.1