use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::sync::Arc;
use crate::util::Utf16String;
use super::DecoupledInjectedAttribute;
pub struct DecoupledTemplateLogic {
injected_attributes: HashMap<Utf16String, Vec<Arc<DecoupledInjectedAttribute>>>,
}
impl DecoupledTemplateLogic {
#[must_use]
pub fn new() -> Self {
Self {
injected_attributes: HashMap::with_capacity(20),
}
}
#[must_use]
pub fn has_injected_attributes(&self) -> bool {
!self.injected_attributes.is_empty()
}
#[must_use]
pub fn get_all_injected_attribute_selectors(&self) -> Vec<&Utf16String> {
self.injected_attributes.keys().collect()
}
#[must_use]
pub fn get_injected_attributes_for_selector(
&self,
selector: &Utf16String,
) -> Option<&[Arc<DecoupledInjectedAttribute>]> {
self.injected_attributes.get(selector).map(Vec::as_slice)
}
pub fn add_injected_attribute(
&mut self,
selector: Utf16String,
injected_attribute: Arc<DecoupledInjectedAttribute>,
) {
self.injected_attributes
.entry(selector)
.or_insert_with(|| Vec::with_capacity(2))
.push(injected_attribute);
}
}
impl Default for DecoupledTemplateLogic {
fn default() -> Self {
Self::new()
}
}
impl Display for DecoupledTemplateLogic {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
let mut keys: Vec<&Utf16String> = self.injected_attributes.keys().collect();
keys.sort_by(|left, right| left.as_utf16().cmp(right.as_utf16()));
formatter.write_str("{")?;
for (index, key) in keys.into_iter().enumerate() {
if index > 0 {
formatter.write_str(", ")?;
}
write!(formatter, "{}=[", key.to_string_lossy())?;
if let Some(attributes) = self.injected_attributes.get(key) {
for (attribute_index, attribute) in attributes.iter().enumerate() {
if attribute_index > 0 {
formatter.write_str(", ")?;
}
formatter.write_str(&attribute.to_utf16_string().to_string_lossy())?;
}
}
formatter.write_str("]")?;
}
formatter.write_str("}")
}
}