use crate::config::CollectionConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
Index,
Feed,
Category,
Tag,
Show,
}
impl Kind {
pub const ALL: [Kind; 5] = [Kind::Index, Kind::Feed, Kind::Category, Kind::Tag, Kind::Show];
pub fn as_str(self) -> &'static str {
match self {
Self::Index => "index",
Self::Feed => "feed",
Self::Category => "category",
Self::Tag => "tag",
Self::Show => "show",
}
}
pub fn parse(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|kind| kind.as_str() == name)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Route {
pub name: String,
pub kind: Kind,
pub locale: String,
pub uri: String,
}
pub fn route_name(collection: &str, kind: &str, locale: &str) -> String {
format!("{locale}.{collection}.{kind}")
}
fn prefix<'a>(locale: &'a str, app_locale: &str) -> &'a str {
if locale == app_locale { "" } else { locale }
}
pub fn uri(
collection: &str,
kind: Kind,
locale: &str,
settings: &CollectionConfig,
locales: &[String],
app_locale: &str,
) -> String {
let path = settings
.paths
.get(locale)
.or_else(|| locales.first().and_then(|first| settings.paths.get(first)))
.map_or(collection, String::as_str)
.trim_matches('/');
let base = [prefix(locale, app_locale), path]
.iter()
.filter(|part| !part.is_empty())
.copied()
.collect::<Vec<_>>()
.join("/");
let category = settings
.segments
.category
.get(locale)
.map_or("category", String::as_str);
let tag = settings.segments.tag.get(locale).map_or("tag", String::as_str);
let rest = match kind {
Kind::Index => String::new(),
Kind::Feed => "feed".to_owned(),
Kind::Category => format!("{category}/{{category}}"),
Kind::Tag => format!("{tag}/{{tag}}"),
Kind::Show => "{slug}".to_owned(),
};
let joined = [base.as_str(), rest.as_str()]
.iter()
.filter(|part| !part.is_empty())
.copied()
.collect::<Vec<_>>()
.join("/");
format!("/{joined}")
}
pub fn definitions(collection: &str, settings: &CollectionConfig, locales: &[String], app_locale: &str) -> Vec<Route> {
let mut routes = Vec::new();
for locale in locales {
for kind in Kind::ALL {
routes.push(Route {
name: route_name(collection, kind.as_str(), locale),
kind,
locale: locale.clone(),
uri: uri(collection, kind, locale, settings, locales, app_locale),
});
}
}
routes
}
pub fn fill(uri: &str, parameters: &[(&str, &str)]) -> String {
let mut path = uri.to_owned();
let mut query = Vec::new();
for (key, value) in parameters {
let placeholder = format!("{{{key}}}");
if path.contains(&placeholder) {
path = path.replace(&placeholder, &rawurlencode(value));
} else {
query.push(format!("{}={}", rawurlencode(key), rawurlencode(value)));
}
}
if query.is_empty() {
path
} else {
format!("{path}?{}", query.join("&"))
}
}
pub fn rawurlencode(text: &str) -> String {
let mut encoded = String::with_capacity(text.len());
for byte in text.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
encoded.push(char::from(byte));
} else {
encoded.push_str(&format!("%{byte:02X}"));
}
}
encoded
}