Nine interface languages. The system's language is picked up; Portuguese notation has its own piece letters (R D T B C), Uzbek and Kazakh keep the Latin ones (the 'letters of the language' choice is not offered for them). Uzbek o'/g' are written with U+2018 on the desktop, whose font has no U+02BB. Comment translation targets the new languages too. The shelf's two side cards widen for a longer label. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
421 lines
16 KiB
Rust
421 lines
16 KiB
Rust
//! Pages of the site: one HTML template, a translation file per language, the data of
|
||
//! the latest release filled in on every request (so the download buttons are right
|
||
//! without JavaScript).
|
||
|
||
use std::collections::HashMap;
|
||
use std::path::Path;
|
||
|
||
use serde_json::{Value, json};
|
||
|
||
use crate::Release;
|
||
|
||
/// Languages of the site: code, own name, Open Graph locale. English is at `/`, the
|
||
/// others at `/<code>/`.
|
||
pub const LANGS: &[(&str, &str, &str)] = &[
|
||
("en", "English", "en_US"),
|
||
("ru", "Русский", "ru_RU"),
|
||
("fr", "Français", "fr_FR"),
|
||
("de", "Deutsch", "de_DE"),
|
||
("es", "Español", "es_ES"),
|
||
("it", "Italiano", "it_IT"),
|
||
("pt", "Português", "pt_BR"),
|
||
("uz", "Oʻzbekcha", "uz_UZ"),
|
||
("kk", "Қазақша", "kk_KZ"),
|
||
];
|
||
|
||
/// Screenshots in gallery order (file stem); the first one is shown in the hero.
|
||
const SHOTS: &[&str] = &[
|
||
"01-game",
|
||
"02-engine",
|
||
"03-reference",
|
||
"04-translation",
|
||
"05-variations",
|
||
"06-review",
|
||
"07-marks",
|
||
"08-preview",
|
||
"09-library",
|
||
"10-filters",
|
||
"11-position-search",
|
||
"12-online",
|
||
"13-looks",
|
||
];
|
||
|
||
/// Strings the page script needs (download panel, buttons, lightbox).
|
||
const CLIENT_KEYS: &[&str] = &[
|
||
"btn_windows",
|
||
"btn_macos",
|
||
"btn_linux",
|
||
"btn_version",
|
||
"btn_latest",
|
||
"apple_silicon",
|
||
"mac_requires",
|
||
"mac_intel_warning",
|
||
"chromeos",
|
||
"copy_link",
|
||
"mail_copy",
|
||
"mail_copied",
|
||
"link_copied",
|
||
"share_link",
|
||
"started",
|
||
"try_again",
|
||
"choose_another",
|
||
"close",
|
||
"next_windows",
|
||
"next_macos_title",
|
||
"mac_step1",
|
||
"mac_warn_title",
|
||
"mac_warn_text",
|
||
"mac_way1",
|
||
"mac_open1",
|
||
"mac15_step2",
|
||
"mac15_step3",
|
||
"mac_open4",
|
||
"mac_way2",
|
||
"mac_way2_text",
|
||
"next_linux",
|
||
"copy",
|
||
"copied",
|
||
"lb_count",
|
||
"meta_title",
|
||
"btn_android",
|
||
"and_light_title",
|
||
"and_requires",
|
||
"and_alpha",
|
||
"next_android",
|
||
];
|
||
|
||
pub struct Site {
|
||
template: String,
|
||
strings: HashMap<String, HashMap<String, String>>,
|
||
/// Public address without a trailing slash (`https://chesspenguin.example`).
|
||
pub url: String,
|
||
asset_version: String,
|
||
}
|
||
|
||
impl Site {
|
||
pub fn load(dir: &Path, url: String) -> Site {
|
||
let template = std::fs::read_to_string(dir.join("index.html")).expect("site/index.html");
|
||
let mut strings = HashMap::new();
|
||
for (code, _, _) in LANGS {
|
||
let path = dir.join("i18n").join(format!("{code}.json"));
|
||
let map: HashMap<String, String> = std::fs::read_to_string(&path)
|
||
.ok()
|
||
.and_then(|s| serde_json::from_str(&s).ok())
|
||
.unwrap_or_else(|| {
|
||
eprintln!("no translations in {}", path.display());
|
||
HashMap::new()
|
||
});
|
||
strings.insert(code.to_string(), map);
|
||
}
|
||
// Changes with every start: browsers fetch the new CSS and JS after a deploy.
|
||
let asset_version = format!(
|
||
"{:x}",
|
||
std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.map_or(0, |d| d.as_secs())
|
||
);
|
||
Site {
|
||
template,
|
||
strings,
|
||
url: url.trim_end_matches('/').to_string(),
|
||
asset_version,
|
||
}
|
||
}
|
||
|
||
pub fn has_lang(&self, code: &str) -> bool {
|
||
LANGS.iter().any(|(c, _, _)| *c == code)
|
||
}
|
||
|
||
/// A string in `lang`, else in English, else the key.
|
||
fn t<'a>(&'a self, lang: &str, key: &'a str) -> &'a str {
|
||
self.strings
|
||
.get(lang)
|
||
.and_then(|m| m.get(key))
|
||
.or_else(|| self.strings.get("en").and_then(|m| m.get(key)))
|
||
.map_or(key, String::as_str)
|
||
}
|
||
|
||
fn path(lang: &str) -> String {
|
||
if lang == "en" {
|
||
"/".to_string()
|
||
} else {
|
||
format!("/{lang}/")
|
||
}
|
||
}
|
||
|
||
/// The page in `lang` with the release's version, sizes and file names.
|
||
pub fn page(&self, lang: &str, release: Option<&Release>) -> String {
|
||
let mut html = self.translate(&self.template, lang);
|
||
let page_url = format!("{}{}", self.url, Self::path(lang));
|
||
let alternates: String = LANGS
|
||
.iter()
|
||
.map(|(c, _, _)| {
|
||
format!(
|
||
"<link rel=\"alternate\" hreflang=\"{c}\" href=\"{}{}\">\n",
|
||
self.url,
|
||
Self::path(c)
|
||
)
|
||
})
|
||
.chain(std::iter::once(format!(
|
||
"<link rel=\"alternate\" hreflang=\"x-default\" href=\"{}/\">",
|
||
self.url
|
||
)))
|
||
.collect();
|
||
let lang_options: String = LANGS
|
||
.iter()
|
||
.map(|(c, name, _)| {
|
||
format!(
|
||
"<option value=\"{c}\"{}>{name}</option>",
|
||
if *c == lang { " selected" } else { "" }
|
||
)
|
||
})
|
||
.collect();
|
||
let lang_links: String = LANGS
|
||
.iter()
|
||
.map(|(c, name, _)| format!("<a href=\"{}\" hreflang=\"{c}\" data-lang=\"{c}\">{name}</a>", Self::path(c)))
|
||
.collect::<Vec<_>>()
|
||
.join(" · ");
|
||
let locale = LANGS
|
||
.iter()
|
||
.find(|(c, _, _)| *c == lang)
|
||
.map_or("en_US", |l| l.2);
|
||
let root_redirect = if lang == "en" { ROOT_REDIRECT } else { "" };
|
||
let gallery: String = SHOTS
|
||
.iter()
|
||
.enumerate()
|
||
.skip(1)
|
||
.map(|(i, stem)| {
|
||
let n = i + 1;
|
||
format!(
|
||
"<li><a href=\"/screenshots/{stem}.png\" data-shot=\"{n}\"><picture>\
|
||
<source type=\"image/webp\" srcset=\"/screenshots/{stem}-640.webp 640w, /screenshots/{stem}-1280.webp 1280w\" sizes=\"(min-width: 900px) 360px, (min-width: 640px) 50vw, 85vw\">\
|
||
<img src=\"/screenshots/{stem}-640.jpg\" width=\"1920\" height=\"1080\" loading=\"lazy\" alt=\"{alt}\"></picture></a>\
|
||
<p>{cap}</p></li>",
|
||
alt = attr(self.t(lang, &format!("alt{n}"))),
|
||
cap = self.t(lang, &format!("shot{n}")),
|
||
)
|
||
})
|
||
.collect();
|
||
let t: serde_json::Map<String, Value> = CLIENT_KEYS
|
||
.iter()
|
||
.map(|k| (k.to_string(), Value::String(self.t(lang, k).to_string())))
|
||
.collect();
|
||
let shots: Vec<Value> = SHOTS
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(i, stem)| {
|
||
json!({
|
||
"full": format!("/screenshots/{stem}.png"),
|
||
"src": format!("/screenshots/{stem}-1920.webp"),
|
||
"fallback": format!("/screenshots/{stem}-1280.jpg"),
|
||
"caption": self.t(lang, &format!("shot{}", i + 1)),
|
||
"alt": self.t(lang, &format!("alt{}", i + 1)),
|
||
})
|
||
})
|
||
.collect();
|
||
let assets: serde_json::Map<String, Value> = release
|
||
.map(|r| {
|
||
r.assets
|
||
.iter()
|
||
.map(|a| {
|
||
(
|
||
a.platform.to_string(),
|
||
json!({ "file": a.name, "size": size(a.size) }),
|
||
)
|
||
})
|
||
.collect()
|
||
})
|
||
.unwrap_or_default();
|
||
let client = json!({
|
||
"lang": lang,
|
||
"home": Self::path(lang),
|
||
"version": release.map(|r| r.version.clone()),
|
||
"assets": assets,
|
||
"shots": shots,
|
||
"t": t,
|
||
});
|
||
let json_ld = json!({
|
||
"@context": "https://schema.org",
|
||
"@type": "SoftwareApplication",
|
||
"name": "ChessPenguin",
|
||
"operatingSystem": "Windows, macOS, Linux, Android",
|
||
"applicationCategory": "GameApplication",
|
||
"license": "https://www.gnu.org/licenses/gpl-3.0.html",
|
||
"softwareVersion": release.map(|r| r.version.clone()),
|
||
"downloadUrl": format!("{}/#download", self.url),
|
||
"offers": { "@type": "Offer", "price": "0", "priceCurrency": "USD" },
|
||
});
|
||
for (key, value) in [
|
||
("{{lang}}", lang.to_string()),
|
||
("{{locale}}", locale.to_string()),
|
||
("{{page_url}}", page_url),
|
||
("{{site}}", self.url.clone()),
|
||
("{{home}}", Self::path(lang)),
|
||
("{{alternates}}", alternates),
|
||
("{{lang_options}}", lang_options),
|
||
("{{lang_links}}", lang_links),
|
||
("{{root_redirect}}", root_redirect.to_string()),
|
||
("{{gallery}}", gallery),
|
||
// `</` must not close the script element the JSON sits in.
|
||
("{{client_json}}", client.to_string().replace("</", "<\\/")),
|
||
("{{json_ld}}", json_ld.to_string().replace("</", "<\\/")),
|
||
("{{asset_version}}", self.asset_version.clone()),
|
||
] {
|
||
html = html.replace(key, &value);
|
||
}
|
||
self.fill_release(html, lang, release)
|
||
}
|
||
|
||
/// `{{t:key}}` → the string in `lang`.
|
||
fn translate(&self, template: &str, lang: &str) -> String {
|
||
let mut out = String::with_capacity(template.len() + 8192);
|
||
let mut rest = template;
|
||
while let Some(start) = rest.find("{{t:") {
|
||
out.push_str(&rest[..start]);
|
||
let after = &rest[start + 4..];
|
||
let Some(end) = after.find("}}") else {
|
||
out.push_str(&rest[start..]);
|
||
return out;
|
||
};
|
||
out.push_str(self.t(lang, &after[..end]));
|
||
rest = &after[end + 2..];
|
||
}
|
||
out.push_str(rest);
|
||
out
|
||
}
|
||
|
||
/// `{version}`, `{date}`, `{size:<platform>}`, `{file:<platform>}`.
|
||
fn fill_release(&self, mut html: String, lang: &str, release: Option<&Release>) -> String {
|
||
let version = release.map_or("", |r| r.version.as_str());
|
||
html = html.replace("{version}", version);
|
||
html = html.replace("{date}", &release.map(|r| date(&r.published, lang)).unwrap_or_default());
|
||
for (platform, _) in crate::PLATFORMS {
|
||
let asset = release.and_then(|r| r.assets.iter().find(|a| a.platform == *platform));
|
||
html = html.replace(
|
||
&format!("{{size:{platform}}}"),
|
||
&asset.map(|a| size(a.size)).unwrap_or_default(),
|
||
);
|
||
html = html.replace(
|
||
&format!("{{file:{platform}}}"),
|
||
&asset.map_or_else(String::new, |a| a.name.clone()),
|
||
);
|
||
}
|
||
html
|
||
}
|
||
|
||
pub fn not_found(&self, lang: &str) -> String {
|
||
format!(
|
||
"<!doctype html><html lang=\"{lang}\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
|
||
<title>{title} · ChessPenguin</title><link rel=\"stylesheet\" href=\"/css/site.css?v={v}\"></head>\
|
||
<body><main class=\"wrap nf\"><h1>{title}</h1><p>{text}</p><p><a class=\"btn btn-small btn-accent\" href=\"{home}#download\">{link}</a></p></main></body></html>",
|
||
title = self.t(lang, "nf_title"),
|
||
text = self.t(lang, "nf_text"),
|
||
link = self.t(lang, "nf_link"),
|
||
home = Self::path(lang),
|
||
v = self.asset_version,
|
||
)
|
||
}
|
||
|
||
pub fn sitemap(&self) -> String {
|
||
let mut out = String::from(
|
||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n",
|
||
);
|
||
for (code, _, _) in LANGS {
|
||
out.push_str(&format!("<url><loc>{}{}</loc>", self.url, Self::path(code)));
|
||
for (alt, _, _) in LANGS {
|
||
out.push_str(&format!(
|
||
"<xhtml:link rel=\"alternate\" hreflang=\"{alt}\" href=\"{}{}\"/>",
|
||
self.url,
|
||
Self::path(alt)
|
||
));
|
||
}
|
||
out.push_str("</url>\n");
|
||
}
|
||
out.push_str("</urlset>\n");
|
||
out
|
||
}
|
||
}
|
||
|
||
/// On `/` only, before anything is drawn: the language chosen before, else the first
|
||
/// browser language the site has, else English stays.
|
||
const ROOT_REDIRECT: &str = r#"<script>(function(){var L=["ru","fr","de","es","it","pt","uz","kk"],p=null;try{p=localStorage.getItem("lang")}catch(e){}if(!p){var ls=navigator.languages||[navigator.language||""];for(var i=0;i<ls.length;i++){var c=(ls[i]||"").slice(0,2).toLowerCase();if(c==="en"||L.indexOf(c)>=0){p=c;break}}}if(p&&p!=="en"&&L.indexOf(p)>=0){location.replace("/"+p+"/"+location.hash)}})();</script>"#;
|
||
|
||
fn attr(s: &str) -> String {
|
||
s.replace('&', "&").replace('"', """).replace('<', "<")
|
||
}
|
||
|
||
/// "14 MB", "8.4 MB" (decimal megabytes, as browsers and Finder show).
|
||
pub fn size(bytes: u64) -> String {
|
||
let mb = bytes as f64 / 1e6;
|
||
if mb < 10.0 {
|
||
format!("{mb:.1} MB")
|
||
} else {
|
||
format!("{:.0} MB", mb)
|
||
}
|
||
}
|
||
|
||
/// "October 19, 2026" in the page's language, from an RFC 3339 time.
|
||
fn date(rfc3339: &str, lang: &str) -> String {
|
||
let Some((y, rest)) = rfc3339.split_once('-') else {
|
||
return String::new();
|
||
};
|
||
let (m, rest) = rest.split_once('-').unwrap_or(("", ""));
|
||
let d: u32 = rest.get(..2).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||
let m: usize = m.parse().unwrap_or(0);
|
||
if m == 0 || m > 12 || d == 0 {
|
||
return String::new();
|
||
}
|
||
let months: [&str; 12] = match lang {
|
||
"ru" => ["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"],
|
||
"fr" => ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"],
|
||
"de" => ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
|
||
"es" => ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
|
||
"it" => ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"],
|
||
"pt" => ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
|
||
"uz" => ["yanvar", "fevral", "mart", "aprel", "may", "iyun", "iyul", "avgust", "sentabr", "oktabr", "noyabr", "dekabr"],
|
||
"kk" => ["қаңтар", "ақпан", "наурыз", "сәуір", "мамыр", "маусым", "шілде", "тамыз", "қыркүйек", "қазан", "қараша", "желтоқсан"],
|
||
_ => ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
|
||
};
|
||
let month = months[m - 1];
|
||
match lang {
|
||
"en" => format!("{month} {d}, {y}"),
|
||
"de" => format!("{d}. {month} {y}"),
|
||
"es" | "pt" => format!("{d} de {month} de {y}"),
|
||
"uz" => format!("{y}-yil {d}-{month}"),
|
||
"kk" => format!("{y} жылғы {d} {month}"),
|
||
_ => format!("{d} {month} {y}"),
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn sizes_and_dates() {
|
||
assert_eq!(size(15_673_262), "16 MB");
|
||
assert_eq!(size(8_400_000), "8.4 MB");
|
||
assert_eq!(date("2026-10-19T06:54:58Z", "en"), "October 19, 2026");
|
||
assert_eq!(date("2026-10-19T06:54:58Z", "ru"), "19 октября 2026");
|
||
assert_eq!(date("2026-10-19T06:54:58Z", "de"), "19. Oktober 2026");
|
||
assert_eq!(date("2026-10-19T06:54:58Z", "es"), "19 de octubre de 2026");
|
||
assert_eq!(date("2026-10-19T06:54:58Z", "pt"), "19 de outubro de 2026");
|
||
assert_eq!(date("2026-10-19T06:54:58Z", "uz"), "2026-yil 19-oktabr");
|
||
assert_eq!(date("2026-10-19T06:54:58Z", "kk"), "2026 жылғы 19 қазан");
|
||
assert_eq!(date("bad", "en"), "");
|
||
}
|
||
|
||
/// Every text the page script asks for is sent to it: a key left out shows as
|
||
/// itself ("btn_android") on the page.
|
||
#[test]
|
||
fn the_script_gets_every_text_it_uses() {
|
||
let script = include_str!("../../static/js/site.js");
|
||
let en: HashMap<String, String> =
|
||
serde_json::from_str(include_str!("../../site/i18n/en.json")).expect("en.json");
|
||
let quoted = script.split('"').skip(1).step_by(2);
|
||
let missing: Vec<&str> = quoted
|
||
.filter(|k| en.contains_key(*k) && !CLIENT_KEYS.contains(k))
|
||
.collect();
|
||
assert!(missing.is_empty(), "not in CLIENT_KEYS: {missing:?}");
|
||
}
|
||
}
|