auric-runtime 0.1.2

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

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

impl App {
    pub fn new(route_defs: &[RouteDef]) -> Self {
        Self {
            handlebars: Handlebars::default(),
            router: Arc::new(Router::new(route_defs)),
        }
    }

    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<()> {
        console_error_panic_hook::set_once();

        // 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(())
    }
}