use std::borrow::Cow;
use std::sync::OnceLock;
pub type ClassNames = &'static [(&'static str, &'static str)];
static CLASS_NAMES: OnceLock<ClassNames> = OnceLock::new();
static KNOWN_CLASSES: OnceLock<&'static [&'static str]> = OnceLock::new();
pub fn set_class_names(names: ClassNames) {
if !names.is_empty() {
debug_assert!(names.is_sorted_by(|a, b| a.0 < b.0), "class names must be sorted");
let _ = CLASS_NAMES.set(names);
}
}
pub fn set_known_classes(classes: &'static [&'static str]) {
if !classes.is_empty() {
debug_assert!(classes.is_sorted(), "known classes must be sorted");
let _ = KNOWN_CLASSES.set(classes);
}
}
pub fn is_dropped(class: &str) -> bool {
KNOWN_CLASSES.get().is_some_and(|known| looks_generated(class) && known.binary_search(&class).is_err())
}
pub fn looks_generated(class: &str) -> bool {
let name = class.strip_prefix('!').unwrap_or(class);
let special = name.contains([':', '[', '/']) || class.starts_with('!');
if !special
|| !name.starts_with(|c: char| c.is_ascii_lowercase())
|| !name.contains(['-', ':'])
|| name.ends_with([':', '/', '-'])
|| name.contains("//")
|| name.as_bytes().windows(2).any(|w| w[0] == b'.' && w[1].is_ascii_alphabetic())
{
return false;
}
let mut depth = 0i32;
for c in name.chars() {
match c {
'[' => depth += 1,
']' => depth -= 1,
'_' | '(' | ')' | ',' | '%' if depth == 0 => return false,
c if c.is_ascii_alphanumeric() || "-_:/[]().%,#+".contains(c) => {}
_ => return false,
}
if depth < 0 {
return false;
}
}
if depth != 0 {
return false;
}
let mut segments = Vec::new();
let (mut depth, mut start) = (0, 0);
for (i, c) in name.char_indices() {
match c {
'[' => depth += 1,
']' => depth -= 1,
':' if depth == 0 => {
segments.push(&name[start..i]);
start = i + 1;
}
_ => {}
}
}
segments.push(&name[start..]);
let Some((utility, variants)) = segments.split_last() else { return false };
if utility.is_empty()
|| utility.starts_with(|c: char| c.is_ascii_digit() || c == '-')
|| variants.iter().any(|v| v.is_empty() || !v.starts_with(|c: char| c.is_ascii_lowercase() || c == '['))
{
return false;
}
let bytes = utility.as_bytes();
bytes
.iter()
.enumerate()
.all(|(i, b)| *b != b'/' || bytes.get(i + 1).is_some_and(|n| n.is_ascii_digit() || *n == b'['))
}
fn table() -> Option<ClassNames> {
CLASS_NAMES.get().copied()
}
fn lookup(names: ClassNames, class: &str) -> Option<&'static str> {
names.binary_search_by(|(original, _)| (*original).cmp(class)).ok().map(|i| names[i].1)
}
pub fn short_class_name(class: &str) -> Option<&'static str> {
lookup(table()?, class)
}
pub(crate) fn map_class_list(list: &str) -> Cow<'_, str> {
map_list(table(), list)
}
fn map_list<'a>(names: Option<ClassNames>, list: &'a str) -> Cow<'a, str> {
let changes = |c: &str| names.is_some_and(|n| lookup(n, c).is_some()) || is_dropped(c);
if !list.split_ascii_whitespace().any(changes) {
return Cow::Borrowed(list);
}
let mut out = String::with_capacity(list.len());
for class in list.split_ascii_whitespace() {
if is_dropped(class) {
continue;
}
if !out.is_empty() {
out.push(' ');
}
out.push_str(names.and_then(|n| lookup(n, class)).unwrap_or(class));
}
Cow::Owned(out)
}
pub(crate) fn map_raw_html(html: &str) -> Cow<'_, str> {
if table().is_none() && KNOWN_CLASSES.get().is_none() {
return Cow::Borrowed(html);
}
map_html(table(), html)
}
fn map_html<'a>(names: Option<ClassNames>, html: &'a str) -> Cow<'a, str> {
let b = html.as_bytes();
let mut out: Option<String> = None;
let mut copied = 0;
let mut search = 0;
while let Some(found) = html[search..].find("class=") {
let at = search + found;
search = at + 6;
let attr_start = at > 0 && b[at - 1].is_ascii_whitespace();
let Some("e) = b.get(at + 6) else { break };
if !attr_start || (quote != b'"' && quote != b'\'') {
continue;
}
let value_start = at + 7;
let Some(len) = html[value_start..].find(quote as char) else { break };
let value = &html[value_start..value_start + len];
if let Cow::Owned(mapped) = map_list(names, value) {
let out = out.get_or_insert_with(|| String::with_capacity(html.len()));
out.push_str(&html[copied..value_start]);
out.push_str(&mapped);
copied = value_start + len;
}
search = value_start + len;
}
match out {
Some(mut out) => {
out.push_str(&html[copied..]);
Cow::Owned(out)
}
None => Cow::Borrowed(html),
}
}
#[cfg(test)]
mod tests {
use super::*;
const NAMES: ClassNames = &[("hover:underline", "b"), ("mt-4", "a"), ("text-[13px]", "c")];
#[test]
fn maps_known_classes_and_keeps_the_rest() {
assert_eq!(map_list(Some(NAMES), "mt-4 card hover:underline"), "a card b");
assert!(matches!(map_list(Some(NAMES), "card tk"), Cow::Borrowed("card tk")));
assert_eq!(map_list(Some(NAMES), " mt-4\ttext-[13px] "), "a c");
}
#[test]
fn maps_class_attributes_in_raw_html() {
let html = r#"<p class="mt-4 x">class="mt-4"</p><span data-class="mt-4" class='text-[13px]'>"#;
assert_eq!(map_html(Some(NAMES), html), r#"<p class="a x">class="mt-4"</p><span data-class="mt-4" class='c'>"#);
assert!(matches!(map_html(Some(NAMES), "<b class=\"tk\">"), Cow::Borrowed(_)));
}
#[test]
fn drops_generated_looking_classes_nothing_knows() {
set_known_classes(&["hover:underline", "mt-4", "sm:flex", "text-[13px]"]);
assert_eq!(
map_list(None, "mt-4 sm:flex sm:flexx bg-[x] w-1/3 !p-0 card g-recaptcha"),
"mt-4 sm:flex card g-recaptcha"
);
assert_eq!(map_list(Some(NAMES), "aria-pressed:glass mt-4"), "a");
assert_eq!(map_html(None, r#"<p class="card md:x">"#), r#"<p class="card">"#);
for kept in ["%H:%M", "$20/month", "*/*", "src/page.rs", "a/b", "hero", "g-recaptcha", "https://x.y/z", "v1.0"]
{
assert!(!looks_generated(kept), "{kept}");
}
for generated in ["sm:flexx", "bg-[var(--x)]", "w-1/2", "!p-0", "aria-pressed:glass", "text-[1.5rem]"] {
assert!(looks_generated(generated), "{generated}");
}
}
}