1use crate::routing::{RouteDef, Router};
2use handlebars::Handlebars;
3use std::{collections::HashMap, sync::Arc};
4use web_sys::window;
5
6pub struct App {
7 handlebars: Handlebars<'static>,
8 router: Arc<Router>,
9}
10
11impl App {
12 pub fn new(route_defs: &[RouteDef]) -> Self {
13 Self {
14 handlebars: Handlebars::default(),
15 router: Arc::new(Router::new(route_defs)),
16 }
17 }
18
19 pub fn handlebars(&mut self) -> &mut Handlebars<'static> {
20 &mut self.handlebars
21 }
22
23 pub fn router(&self) -> Arc<Router> {
24 self.router.clone()
25 }
26
27 pub fn start(&self) -> anyhow::Result<()> {
28 console_error_panic_hook::set_once();
29
30 self.router.init().expect("Could not initialize router");
32
33 let data: HashMap<String, String> = HashMap::new();
35 let html = self
36 .handlebars
37 .render("application", &data)
38 .expect("Could not render application.hbs");
39
40 let document = window()
42 .and_then(|win| win.document())
43 .expect("Could not access document");
44 let body = document.body().expect("Could not access document body");
45 let main = document
46 .create_element("main")
47 .expect("Could not create a main element within the body");
48 main.set_inner_html(&html);
49 body.append_child(main.as_ref())
50 .expect("Could not append main element to body");
51
52 Ok(())
53 }
54}