1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use crate::errors::*;
use crate::serve::PageData;
use crate::template::TemplateFn;
use std::collections::HashMap;
use sycamore::prelude::Template as SycamoreTemplate;
use sycamore::prelude::*;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
pub(crate) async fn fetch(url: &str) -> Result<Option<String>> {
let js_err_handler = |err: JsValue| ErrorKind::JsErr(format!("{:?}", err));
let mut opts = RequestInit::new();
opts.method("GET").mode(RequestMode::Cors);
let request = Request::new_with_str_and_init(url, &opts).map_err(js_err_handler)?;
let window = web_sys::window().unwrap();
let res_value = JsFuture::from(window.fetch_with_request(&request))
.await
.map_err(js_err_handler)?;
let res: Response = res_value.dyn_into().unwrap();
if res.status() == 404 {
return Ok(None);
}
let body_promise = res.text().map_err(js_err_handler)?;
let body = JsFuture::from(body_promise).await.map_err(js_err_handler)?;
let body_str = body.as_string();
let body_str = match body_str {
Some(body_str) => body_str,
None => bail!(ErrorKind::AssetNotString(url.to_string())),
};
if res.status() == 200 {
Ok(Some(body_str))
} else {
bail!(ErrorKind::AssetNotOk(
url.to_string(),
res.status(),
body_str
))
}
}
pub type ErrorPageTemplate<G> = Box<dyn Fn(&str, &u16, &str) -> SycamoreTemplate<G>>;
pub struct ErrorPages {
status_pages: HashMap<u16, ErrorPageTemplate<DomNode>>,
fallback: ErrorPageTemplate<DomNode>,
}
impl ErrorPages {
pub fn new(fallback: ErrorPageTemplate<DomNode>) -> Self {
Self {
status_pages: HashMap::default(),
fallback,
}
}
pub fn add_page(&mut self, status: u16, page: ErrorPageTemplate<DomNode>) {
self.status_pages.insert(status, page);
}
pub fn render_page(&self, url: &str, status: &u16, err: &str, container: &NodeRef<DomNode>) {
let template_fn = match self.status_pages.contains_key(status) {
true => self.status_pages.get(status).unwrap(),
false => &self.fallback,
};
sycamore::render_to(
|| template_fn(url, status, err),
&container.get::<DomNode>().inner_element(),
);
}
pub fn get_template_for_page(
&self,
url: &str,
status: &u16,
err: &str,
) -> SycamoreTemplate<DomNode> {
let template_fn = match self.status_pages.contains_key(status) {
true => self.status_pages.get(status).unwrap(),
false => &self.fallback,
};
template_fn(url, status, err)
}
}
pub fn app_shell(
path: String,
template_fn: TemplateFn<DomNode>,
error_pages: ErrorPages,
) -> Template<DomNode> {
let container = NodeRef::new();
wasm_bindgen_futures::spawn_local(cloned!((container) => async move {
let asset_url = format!("/.perseus/page/{}", path.to_string());
let page_data_str = fetch(&asset_url).await;
match page_data_str {
Ok(page_data_str) => match page_data_str {
Some(page_data_str) => {
let page_data = serde_json::from_str::<PageData>(&page_data_str);
match page_data {
Ok(page_data) => {
let container_elem = container.get::<DomNode>().unchecked_into::<web_sys::Element>();
container_elem.set_inner_html(&page_data.content);
sycamore::hydrate_to(
|| template_fn(page_data.state),
&container.get::<DomNode>().inner_element()
);
},
Err(err) => panic!("page data couldn't be serialized: '{}'", err)
};
},
None => error_pages.render_page(&asset_url, &404, "page not found", &container),
},
Err(err) => match err.kind() {
ErrorKind::AssetNotOk(url, status, err) => error_pages.render_page(url, status, err, &container),
_ => panic!("expected 'AssetNotOk' error, found other unacceptable error")
}
};
}));
template! {
div(ref = container)
}
}