use std::collections::HashSet;
use crate::css_constants::{is_valid_html_element, is_valid_pseudo_class};
use crate::parsing_utils::{extract_identifier, skip_string_literal, skip_comment, is_color_code, css_to_rust_ident};
#[derive(Debug, Clone)]
pub enum SelectorInfo {
Class(String), Id(String), Element(String), Pseudo(String), }
impl SelectorInfo {
pub fn name(&self) -> &str {
match self {
SelectorInfo::Class(n) => n,
SelectorInfo::Id(n) => n,
SelectorInfo::Element(n) => n,
SelectorInfo::Pseudo(n) => n,
}
}
}
pub fn extract_class_names(css: &str) -> Vec<SelectorInfo> {
let mut classes = HashSet::new();
let mut ids = HashSet::new();
let mut elements = HashSet::new();
let mut pseudo_classes = HashSet::new();
let mut chars = css.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'.' => {
if let Some(name) = extract_identifier(&mut chars) {
classes.insert(css_to_rust_ident(&name));
}
}
'#' => {
if !is_color_code(&mut chars.clone()) {
if let Some(name) = extract_identifier(&mut chars) {
ids.insert(css_to_rust_ident(&name));
}
}
}
':' => {
if chars.peek() != Some(&':') {
if let Some(name) = extract_identifier(&mut chars) {
if is_valid_pseudo_class(&name) {
pseudo_classes.insert(css_to_rust_ident(&name));
}
}
} else {
chars.next(); }
}
'"' | '\'' => {
skip_string_literal(ch, &mut chars);
}
'/' if chars.peek() == Some(&'*') => {
skip_comment(&mut chars);
}
_ if ch.is_alphabetic() => {
let mut element_name = String::new();
element_name.push(ch);
while let Some(&next_ch) = chars.peek() {
if next_ch.is_alphanumeric() || next_ch == '-' {
element_name.push(chars.next().unwrap());
} else {
break;
}
}
let next = chars.peek();
if next == Some(&'{') || next == Some(&' ') || next == Some(&'.') ||
next == Some(&'#') || next == Some(&':') {
if is_valid_html_element(&element_name) {
elements.insert(css_to_rust_ident(&element_name));
}
}
}
_ => {}
}
}
let mut all_selectors = Vec::new();
for class in sorted_vec(classes) {
all_selectors.push(SelectorInfo::Class(class));
}
for id in sorted_vec(ids) {
all_selectors.push(SelectorInfo::Id(id));
}
for element in sorted_vec(elements) {
all_selectors.push(SelectorInfo::Element(format!("el_{}", element)));
}
for pseudo in sorted_vec(pseudo_classes) {
all_selectors.push(SelectorInfo::Pseudo(format!("pseudo_{}", pseudo)));
}
all_selectors
}
fn sorted_vec(set: HashSet<String>) -> Vec<String> {
let mut vec: Vec<String> = set.into_iter().collect();
vec.sort();
vec
}