add the contains attribute and the nth child

master
kirbylife 2021-03-07 19:39:03 -06:00
parent f6866dd7e6
commit 45d9bd306b
1 changed files with 37 additions and 2 deletions

View File

@ -1,6 +1,7 @@
use regex::Regex;
fn cssifier(xpath: &'static str) -> Option<String> {
// Ultra magic regex to parse XPath selectors
let reg = Regex::new(r#"(?P<node>(^id\(["']?(?P<idvalue>\s*[\w/:][-/\w\s,:;.]*)["']?\)|(?P<nav>//?)(?P<tag>([a-zA-Z][a-zA-Z0-9]{0,10}|\*))(\[((?P<matched>(?P<mattr>@?[.a-zA-Z_:][-\w:.]*(\(\))?)=["'](?P<mvalue>\s*[\w/:][-/\w\s,:;.]*))["']|(?P<contained>contains\((?P<cattr>@?[.a-zA-Z_:][-\w:.]*(\(\))?),\s*["'](?P<cvalue>\s*[\w/:][-/\w\s,:;.]*)["']\)))\])?(\[(?P<nth>\d)\])?))"#).unwrap();
let mut css = String::new();
let mut position = 0;
@ -9,6 +10,7 @@ fn cssifier(xpath: &'static str) -> Option<String> {
let node = reg.captures(&xpath[position..])?;
let find = reg.find(&xpath[position..])?;
// See the nav identifier
let nav = match position {
0 => "",
_ => {
@ -20,6 +22,7 @@ fn cssifier(xpath: &'static str) -> Option<String> {
}
};
// See the tag name
let tag = if node.name("tag")?.as_str() == "*" {
""
} else {
@ -29,6 +32,7 @@ fn cssifier(xpath: &'static str) -> Option<String> {
}
};
// See the idenfitier attribute of the tag
let attr = if node.name("idvalue").is_some() {
format!("#{}", node.name("idvalue")?.as_str().replace(" ", "#"))
} else if node.name("matched").is_some() {
@ -41,13 +45,40 @@ fn cssifier(xpath: &'static str) -> Option<String> {
format!(".{}", mvalue.replace(" ", "."))
} else if mattr == "text()" || mattr == "." {
format!(":contains(^{}$)", mvalue)
} else if mattr != "" {
let new_mvalue = if mvalue.find(" ").is_some() {
format!("\"{}\"", mvalue)
} else {
mvalue.to_string()
};
format!("[{}={}]", mattr.replace("@", ""), new_mvalue)
} else {
String::from("")
}
} else if node.name("contained").is_some() {
let cattr = node.name("cattr")?.as_str();
let cvalue = node.name("cvalue")?.as_str();
if cattr.starts_with("@") {
format!("{}*={}", cattr.replace("@", ""), cvalue)
} else if cattr == "text()" {
format!(":contains({})", cvalue)
} else {
String::from("")
}
} else {
String::from("")
};
css = format!("{}{}{}{}", css, nav, tag, attr);
// See the child type
let nth = if node.name("nth").is_some() {
format!(":nth-of-type({})", node.name("nth")?.as_str())
} else {
String::from("")
};
// Paste all the magic :sparkles:
css = format!("{}{}{}{}{}", css, nav, tag, attr, nth);
position += find.end();
}
@ -56,11 +87,15 @@ fn cssifier(xpath: &'static str) -> Option<String> {
#[cfg(test)]
mod tests {
use crate::cssifier;
use super::cssifier;
#[test]
fn it_works() {
assert_eq!(cssifier("//a/b").unwrap(), "a b");
assert_eq!(cssifier("//a/b[@id='hello']").unwrap(), "a b#hello");
assert_eq!(
cssifier("//a/b[contains(text(), 'hello')]").unwrap(),
"a b:contains(hello)"
);
}
}