use {
crate::{
dom::{Handle, Node, NodeData, NodeExt},
Charset, LanguageTag,
},
html5ever::{namespace_url, ns, tendril::Tendril, Attribute, LocalName, QualName},
log::error,
std::{cell::RefCell, rc::Rc},
};
pub struct NodeCreator;
impl NodeCreator {
pub fn element(tag_name: &str, attributes: Vec<Attribute>) -> Rc<Node> {
Node::new(NodeData::Element {
name: QualName::new(None, ns!(html), LocalName::from(tag_name)),
attrs: RefCell::new(attributes),
template_contents: None,
mathml_annotation_xml_integration_point: false,
})
}
pub fn element_ext(
tag_name: &str,
attributes: Vec<Attribute>,
template_contents: Option<Handle>,
mathml_annotation_xml_integration_point: bool,
) -> Rc<Node> {
Node::new(NodeData::Element {
name: QualName::new(None, ns!(html), LocalName::from(tag_name)),
attrs: RefCell::new(attributes),
template_contents,
mathml_annotation_xml_integration_point,
})
}
pub fn attribute(name: &str, value: &str) -> Attribute {
Attribute {
name: QualName::new(None, ns!(), LocalName::from(name)),
value: Tendril::from(value),
}
}
pub fn text(content: &str) -> Rc<Node> {
Node::new(NodeData::Text {
contents: RefCell::new(Tendril::from(content)),
})
}
pub fn doctype_html() -> Rc<Node> {
Node::new(NodeData::Doctype {
name: Tendril::from("html"),
public_id: Tendril::from(""),
system_id: Tendril::from(""),
})
}
pub fn html(language: LanguageTag) -> Rc<Node> {
let language = match language.language() {
Some(v) => v.primary().as_str().to_owned(),
None => {
error!("Could not find language for creating <html> tag");
"".to_owned()
}
};
NodeCreator::element("html", vec![NodeCreator::attribute("lang", &language)])
}
pub fn title(title: &str) -> Rc<Node> {
let title_tag = NodeCreator::element("title", vec![]);
title_tag
.children
.borrow_mut()
.push(NodeCreator::text(title));
title_tag
}
pub fn description(description: &str) -> Rc<Node> {
NodeCreator::element(
"meta",
vec![
NodeCreator::attribute("name", "description"),
NodeCreator::attribute("content", description),
],
)
}
pub fn viewport() -> Rc<Node> {
NodeCreator::element(
"meta",
vec![
NodeCreator::attribute("name", "viewport"),
NodeCreator::attribute(
"content",
"width=device-width, initial-scale=1.0, user-scalable=no",
),
],
)
}
pub fn charset(charset: &Charset) -> Rc<Node> {
NodeCreator::element(
"meta",
vec![NodeCreator::attribute("charset", &charset.to_string())],
)
}
pub fn headline(level: u8, content: &str, attributes: Vec<Attribute>) -> Rc<Node> {
let level = match level {
0 => 1,
1..=6 => level,
_ => 6,
};
let h = Self::element(&format!("h{}", level), attributes);
h.add_text(content);
h
}
pub fn paragraph(content: &str, attributes: Vec<Attribute>) -> Rc<Node> {
let p = Self::element("p", attributes);
p.add_text(content);
p
}
}