1use crate::{Context, data::Store, routing::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 store: Arc<Store>,
10}
11
12impl App {
13 pub fn new(router: Router, store: Store) -> Self {
14 Self {
15 handlebars: Handlebars::default(),
16 router: Arc::new(router),
17 store: Arc::new(store),
18 }
19 }
20
21 pub fn handlebars(&mut self) -> &mut Handlebars<'static> {
22 &mut self.handlebars
23 }
24
25 pub fn router(&self) -> Arc<Router> {
26 self.router.clone()
27 }
28
29 pub fn start(&self) -> anyhow::Result<()> {
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}
55
56impl Context for App {
57 fn router(&self) -> Arc<Router> {
58 self.router.clone()
59 }
60
61 fn store(&self) -> Arc<Store> {
62 self.store.clone()
63 }
64}