use super::{selector_arms, vocabulary};
use crate::Emit;
use crate::css_lex::{is_ident, matching_close, top_level};
use std::collections::BTreeSet;
pub const ELEMENT_CLASSES: &[(&str, &[&str])] = &[
(
"a",
&[
"link",
"button",
"tab",
"chip",
"badge",
"card",
"row-activate",
"figure-act",
"chrome-place",
"facet-take",
"facet-prune",
"facet-join-word",
],
),
(
"button",
&[
"button",
"chip",
"segment",
"toggle",
"tab",
"link",
"badge",
"card",
"facet-take",
"facet-prune",
"facet-join-word",
"chip-remove",
"row-activate",
],
),
("details", &["ask"]),
("summary", &["button", "ask-open", "ask-body"]),
("input", &["field", "toggle", "row-select"]),
("select", &["field"]),
("textarea", &["field"]),
(
"label",
&[
"form-label",
"form-checkbox-label",
"form-radio-label",
"toggle",
"card",
],
),
("form", &["form"]),
("progress", &["progress"]),
("p", &["text", "facet-name", "placeholder-text"]),
("ul", &["list", "facet-values"]),
("ol", &["list"]),
("li", &["facet-value"]),
("table", &["table"]),
("thead", &["table-head"]),
("tr", &["table-row"]),
("td", &["cell", "cell-value", "cell-content"]),
("th", &["table-heading"]),
("figure", &["picture", "figure"]),
("img", &["picture-img"]),
("figcaption", &["picture-caption", "figure-caption"]),
("nav", &["chrome-nav"]),
];
#[must_use]
pub fn classes_for_element(element: &str, opts: &Emit) -> BTreeSet<String> {
if element == UNIVERSAL {
return vocabulary(opts);
}
ELEMENT_CLASSES
.iter()
.find(|(name, _)| *name == element)
.map(|(_, classes)| classes.iter().map(|c| crate::class(c, opts)).collect())
.unwrap_or_default()
}
pub const UNIVERSAL: &str = "*";
pub(super) fn bare_element(arm: &str) -> Option<String> {
let mut flat = String::with_capacity(arm.len());
let mut depth = 0usize;
for c in arm.chars() {
match c {
'[' | '(' => depth += 1,
']' | ')' => depth = depth.saturating_sub(1),
_ if depth == 0 => flat.push(c),
_ => {}
}
}
let flat = flat.trim();
if let Some(rest) = flat.strip_prefix('*') {
let bare = !rest.contains(['.', '#', '>', '+', '~', '*'])
&& !rest.chars().any(char::is_whitespace)
&& !rest.contains("::");
return bare.then(|| UNIVERSAL.to_string());
}
if flat.is_empty() || flat.contains(['.', '#', '>', '+', '~', '*']) {
return None;
}
if flat.chars().any(char::is_whitespace) {
return None;
}
let name: String = flat
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '-')
.collect();
if !name.starts_with(|c: char| c.is_ascii_alphabetic()) {
return None;
}
Some(name.to_ascii_lowercase())
}
pub(super) fn classes_in_selector(selector: &str) -> Vec<String> {
let chars: Vec<char> = selector.chars().collect();
let mut names = Vec::new();
let mut i = 0;
while i < chars.len() {
if chars[i] == '.'
&& chars
.get(i + 1)
.is_some_and(|c| c.is_alphabetic() || *c == '_')
{
let start = i + 1;
let mut end = start;
while end < chars.len() && is_ident(chars[end]) {
end += 1;
}
names.push(chars[start..end].iter().collect());
i = end;
} else {
i += 1;
}
}
names
}
pub(super) fn classes_matched_by(selector: &str) -> Vec<String> {
let subjects: Vec<String> = selector_arms(selector)
.into_iter()
.filter(|arm| !arm.contains("::"))
.map(|arm| without_pseudo(&without_pseudo(subject_of(arm), ":not("), ":has("))
.collect();
classes_in_selector(&subjects.join(","))
}
fn subject_of(arm: &str) -> &str {
let arm = arm.trim();
let start = top_level(arm)
.filter(|&(_, c)| c.is_whitespace() || matches!(c, '>' | '+' | '~'))
.last()
.map_or(0, |(i, c)| i + c.len_utf8());
&arm[start..]
}
fn without_pseudo(compound: &str, pseudo: &str) -> String {
let mut kept = String::with_capacity(compound.len());
let mut rest = compound;
while let Some(at) = rest.find(pseudo) {
kept.push_str(&rest[..at]);
let end = matching_close(rest.as_bytes(), at + pseudo.len() - 1, b'(', b')')
.map_or(rest.len(), |k| k + 1);
rest = &rest[end..];
}
kept.push_str(rest);
kept
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_subject_is_what_follows_the_last_combinator() {
assert_eq!(subject_of(".a > .b"), ".b");
assert_eq!(subject_of(">.b"), ".b");
assert_eq!(subject_of("~.b"), ".b");
assert_eq!(subject_of(".b"), ".b");
}
}