stawege-html-plugin 0.1.2

HTML template engine plugin for Stawege.
Documentation
use stawege_log::error;

use crate::Item;

#[derive(Default, Debug)]
pub struct Template {
    pub items: Vec<Item>,
    depth: usize,
    pub opened_items: Vec<Item>,
}

impl Template {
    pub fn new() -> Template {
        Template::default()
    }

    pub fn clear(&mut self) {
        self.items.clear();
        self.depth = 0;
        self.opened_items.clear();
    }

    pub fn push_opened_item(&mut self, item: Item) {
        self.opened_items.push(item.clone_empty());
        self.push_item(item);
        self.depth += 1;
    }

    pub fn close_opened_item(&mut self) {
        self.opened_items.pop();
        self.depth -= 1;
    }

    pub fn push_item(&mut self, item: Item) {
        if self.depth == 0 {
            self.items.push(item);
        } else {
            Template::push_item_at_depth(&mut self.items, item, self.depth - 1);
        }
    }

    fn push_item_at_depth(items: &mut [Item], item: Item, depth: usize) {
        match items.last_mut() {
            Some(Item::Tag { items, .. }) => {
                if depth == 0 {
                    items.push(item);
                } else {
                    Template::push_item_at_depth(items, item, depth - 1);
                }
            }
            None => error!("No open item"),
            _ => {}
        };
    }

    pub fn matches_open_item(&self, other_item: &Item) -> bool {
        if let Some(open_item) = self.opened_items.last() {
            return open_item.matches(other_item);
        }
        false
    }
}