auric-runtime 0.1.3

Runtime for the Ember-inspired Auric SPA framework
Documentation
use crate::{Context, data::Store, routing::Router};
use handlebars::Handlebars;
use std::{collections::HashMap, sync::Arc};
use web_sys::window;

pub struct App {
    handlebars: Handlebars<'static>,
    router: Arc<Router>,
    store: Arc<Store>,
}

impl App {
    pub fn new(router: Router, store: Store) -> Self {
        Self {
            handlebars: Handlebars::default(),
            router: Arc::new(router),
            store: Arc::new(store),
        }
    }

    pub fn handlebars(&mut self) -> &mut Handlebars<'static> {
        &mut self.handlebars
    }

    pub fn router(&self) -> Arc<Router> {
        self.router.clone()
    }

    pub fn start(&self) -> anyhow::Result<()> {
        // Initialize router
        self.router.init().expect("Could not initialize router");

        // Generate html for application template
        let data: HashMap<String, String> = HashMap::new();
        let html = self
            .handlebars
            .render("application", &data)
            .expect("Could not render application.hbs");

        // Add html as a main element within the body
        let document = window()
            .and_then(|win| win.document())
            .expect("Could not access document");
        let body = document.body().expect("Could not access document body");
        let main = document
            .create_element("main")
            .expect("Could not create a main element within the body");
        main.set_inner_html(&html);
        body.append_child(main.as_ref())
            .expect("Could not append main element to body");

        Ok(())
    }
}

impl Context for App {
    fn router(&self) -> Arc<Router> {
        self.router.clone()
    }

    fn store(&self) -> Arc<Store> {
        self.store.clone()
    }
}