use ego_tree::iter::Edge;
use regex::Regex;
use scraper::Node;
use scraper::{ElementRef, Html};
use crate::types::doc_node::DocNode;
static HRBR_PLACEHOLDER: &str = "hrbr";
pub fn esc_hr(hrstr: String) -> String {
let re = Regex::new(r"</?hr/?>").unwrap();
return re
.replace_all(&hrstr, format!("<{HRBR_PLACEHOLDER}></{HRBR_PLACEHOLDER}>"))
.to_string();
}
pub fn squish_surrounding_whitespace(input: &str) -> String {
let re = Regex::new(r"^\s+|\s+$").unwrap();
re.replace_all(input, " ").to_string()
}
pub fn extract_leaves(fragment: &Html) -> Vec<DocNode> {
let mut leaf_nodes: Vec<DocNode> = Vec::new();
fragment
.root_element()
.traverse()
.for_each(|edge| match edge {
Edge::Close(node) => {
if let Some(element) = ElementRef::wrap(node) {
if element.value().name() == "iframe" || element.value().name() == "img" {
leaf_nodes.push(DocNode {
name: element.value().name().trim(),
text: "".trim().to_owned(),
node,
})
} else if element.value().name() == HRBR_PLACEHOLDER {
leaf_nodes.push(DocNode {
name: "hr",
text: "".trim().to_owned(),
node,
})
}
} else if let Node::Text(text_node) = node.value() {
if !text_node.text.trim().is_empty() {
leaf_nodes.push(DocNode {
name: "text",
text: squish_surrounding_whitespace(&text_node.text),
node,
})
}
}
}
Edge::Open(_) => (),
});
leaf_nodes
}