Skip to content
Snippets Groups Projects
formatting.rs 1.41 KiB
Newer Older
use std::fmt::{Display, Formatter};

pub struct Attribute {
	key: String,
	value: String,
}

impl Display for Attribute {
	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}=\"{}\"", self.key, self.value.replace('"', "\\\""))
	}
}

impl<A, B> From<(A, B)> for Attribute
where
	A: ToString,
	B: ToString,
{
	fn from(item: (A, B)) -> Self {
		Attribute {
			key: item.0.to_string(),
			value: item.1.to_string(),
		}
	}
}

fn format_attr_list(list: &[Attribute]) -> String {
	list.iter()
		.map(|attr| format!("{}", attr))
		.reduce(|prev, cur| format!("{} {}", prev, cur))
		.unwrap_or_default()
}

fn format_child_list(list: &[String]) -> String {
	list.iter()
		.fold(String::new(), |prev, cur| format!("{}\n{}", prev, cur))
}

pub struct El;

impl El {
	pub fn open(tag: impl ToString, attributes: &[Attribute]) -> String {
		format!("<{} {}>", tag.to_string(), format_attr_list(attributes))
	}

	pub fn close(tag: impl ToString) -> String {
		format!("</{}>", tag.to_string())
	}

	pub fn create(tag: impl ToString, attributes: &[Attribute]) -> String {
		format!("<{} {} />", tag.to_string(), format_attr_list(attributes))
	}

	pub fn with_children(
		tag: impl ToString,
		attributes: Vec<Attribute>,
		children: Vec<String>,
	) -> String {
		format!(
			"<{tag} {attr}>{children}</{tag}>",
			tag = tag.to_string(),
			attr = format_attr_list(&attributes),
			children = format_child_list(&children)
		)
	}
}