use std::borrow::Cow;
use std::rc::Rc;
use simdhtml::document::Document;
use simdhtml::document::id::{DOC_ROOT, NodeId};
use simdhtml::parse::{EncodingMode, ParseOptions};
use crate::css::ast::SelectorList;
use crate::css::cache::QueryCache;
use crate::css::parser::parse_selector;
use crate::css::select::{Count, Projection, extract, select_as_within_cache, select_within_cache};
use crate::error::Error;
use crate::record::{MatchKind, MatchRecord};
#[derive(Clone, Debug)]
pub struct Selector<'a> {
doc: Rc<Document<'a>>,
roots: Vec<NodeId>,
records: Vec<MatchRecord>,
cache: Rc<QueryCache>,
}
impl<'a> Selector<'a> {
#[must_use]
pub fn new(doc: Document<'a>) -> Self {
Self {
doc: Rc::new(doc),
roots: vec![DOC_ROOT],
records: Vec::new(),
cache: Rc::new(QueryCache::root()),
}
}
pub fn from_bytes(input: &'a [u8]) -> Result<Self, Error> {
Ok(Self::new(Document::parse(input)?))
}
pub fn from_bytes_with(input: &'a [u8], options: ParseOptions) -> Result<Self, Error> {
Ok(Self::new(Document::parse_with(input, options)?))
}
pub fn from_text(text: &'a str) -> Result<Self, Error> {
Self::from_bytes_with(
text.as_bytes(),
ParseOptions {
encoding: EncodingMode::Utf8,
..Default::default()
},
)
}
#[must_use]
pub fn split(&self) -> Vec<Self> {
self.records
.iter()
.map(|record| Self {
doc: Rc::clone(&self.doc),
roots: vec![record.node],
records: vec![record.clone()],
cache: Rc::clone(&self.cache),
})
.collect()
}
#[must_use]
pub fn doc(&self) -> &Document<'a> {
&self.doc
}
#[must_use]
pub fn roots(&self) -> &[NodeId] {
&self.roots
}
#[must_use]
pub fn records(&self) -> &[MatchRecord] {
&self.records
}
#[must_use]
pub fn len(&self) -> usize {
self.records.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
fn compiled(query: &str) -> Result<Rc<SelectorList>, Error> {
use std::cell::RefCell;
use std::collections::HashMap;
thread_local! {
static CACHE: RefCell<HashMap<Box<str>, Rc<SelectorList>>> = RefCell::new(HashMap::new());
}
const MAX_ENTRIES: usize = 256;
CACHE.with(|cache| {
if let Some(parsed) = cache.borrow().get(query) {
return Ok(Rc::clone(parsed));
}
let parsed = Rc::new(parse_selector(query)?);
let mut cache = cache.borrow_mut();
if cache.len() >= MAX_ENTRIES {
cache.clear();
}
cache.insert(query.into(), Rc::clone(&parsed));
Ok(parsed)
})
}
pub fn css(&self, query: &str) -> Result<Self, Error> {
let parsed = Self::compiled(query)?;
let records = select_within_cache(&self.doc, &parsed, &self.roots, &self.cache)?;
let roots = records.iter().map(|record| record.node).collect::<Vec<_>>();
Ok(Self {
doc: Rc::clone(&self.doc),
roots,
records,
cache: Rc::clone(&self.cache),
})
}
pub fn css_as<'b, P: Projection>(&'b self, query: &str) -> Result<P::Output<'b>, Error> {
let parsed = Self::compiled(query)?;
select_as_within_cache::<P>(&self.doc, &parsed, &self.roots, &self.cache)
}
pub fn css_count(&self, query: &str) -> Result<usize, Error> {
self.css_as::<Count>(query)
}
#[must_use]
pub fn get(&self) -> Option<Cow<'_, str>> {
self.records
.first()
.map(|record| extract(&self.doc, record))
}
#[must_use]
pub fn getall(&self) -> Vec<Cow<'_, str>> {
self.records
.iter()
.map(|record| extract(&self.doc, record))
.collect()
}
#[must_use]
pub fn text(&self) -> Option<Cow<'_, str>> {
self.records
.first()
.and_then(|record| record_text(&self.doc, record))
}
#[must_use]
pub fn texts(&self) -> Vec<Cow<'_, str>> {
self.records
.iter()
.filter_map(|record| record_text(&self.doc, record))
.collect()
}
#[must_use]
pub fn attrib(&self) -> Option<Vec<(String, String)>> {
record_attrib(&self.doc, self.records.first()?)
}
}
impl Selector<'static> {
pub fn from_vec(input: Vec<u8>) -> Result<Self, Error> {
Ok(Self::new(Document::parse_owned(input)?))
}
pub fn from_vec_with(input: Vec<u8>, options: ParseOptions) -> Result<Self, Error> {
Ok(Self::new(Document::parse_owned_with(input, options)?))
}
pub fn from_string(text: String) -> Result<Self, Error> {
Self::from_vec_with(
text.into_bytes(),
ParseOptions {
encoding: EncodingMode::Utf8,
..Default::default()
},
)
}
}
impl<'a> From<Document<'a>> for Selector<'a> {
fn from(doc: Document<'a>) -> Self {
Self::new(doc)
}
}
pub fn select_query_within_cache(
doc: &Document<'_>,
roots: &[NodeId],
cache: &QueryCache,
query: &str,
) -> Result<Vec<MatchRecord>, Error> {
let parsed = Selector::compiled(query)?;
select_within_cache(doc, &parsed, roots, cache)
}
#[must_use]
pub fn record_text<'a>(doc: &'a Document<'_>, record: &MatchRecord) -> Option<Cow<'a, str>> {
match record.kind {
MatchKind::Element => Some(Cow::Owned(crate::dom::text_content(doc, record.node))),
MatchKind::Text => Some(doc.text(record.node)),
MatchKind::Attr => None,
}
}
#[must_use]
pub fn record_attrib(doc: &Document<'_>, record: &MatchRecord) -> Option<Vec<(String, String)>> {
if record.kind != MatchKind::Element {
return None;
}
let mut out = Vec::new();
let mut seen: Vec<String> = Vec::new();
for attr in crate::dom::attr_range(doc, record.node) {
let name = crate::dom::attr_name(doc, attr);
if seen
.iter()
.any(|s| s.eq_ignore_ascii_case(std::str::from_utf8(name).unwrap_or("")))
{
continue;
}
let name = String::from_utf8_lossy(name).into_owned();
seen.push(name.clone());
out.push((name, crate::dom::attr_value(doc, attr).into_owned()));
}
Some(out)
}