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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
use core::marker::PhantomData;
use std::rc::*;
use std::any::*;
use std::cell::*;
use std::collections::*;
use serde::{Serialize, Deserialize, de::DeserializeOwned};
use wasm_bindgen::closure::Closure;
use wasm_bindgen::{JsValue, JsCast};
use js_sys::Function;
use uuid::Uuid;
use crate::backend::browser;
use crate::view_sys::dsl::View;
use crate::program_sys::instances::TickEnv;
use crate::program_sys::spec::Spec;
use crate::program_sys::effect::nav::*;
pub struct Shell<S: Spec> {
pub(crate) instance_name: String,
pub(crate) commands: RefCell<VecDeque<Command>>,
pub(crate) mark: PhantomData<S>,
pub(crate) http_client: HttpClient<S>,
}
pub(crate) enum Command {
Save,
Message(SystemMessage),
Navigate(String),
}
impl<S: Spec + 'static> Shell<S> {
pub fn save(&mut self) {
self.commands.borrow_mut().push_back(Command::Save);
}
pub fn broadcast(&mut self, msg: impl Any) {
self.commands.borrow_mut().push_back(Command::Message(
SystemMessage::Public {
from_name: self.instance_name.clone(),
from_tid: TypeId::of::<S>(),
value: Rc::new(msg),
}
));
}
pub fn message<T: Spec + 'static, V: Any>(&mut self, msg: V) {
let from_tid = TypeId::of::<S>();
let to_tid = TypeId::of::<T>();
self.commands.borrow_mut().push_back(Command::Message(SystemMessage::Private {
from_name: self.instance_name.clone(),
from_tid,
to_tid,
value: Rc::new(msg)
}));
}
pub fn navigate(&mut self, path: impl UrlString) {
self.commands.borrow_mut().push_back(Command::Navigate(path.url_string()));
}
pub fn current_url(&self) -> Url {
Url::get_current(&browser::window())
}
pub fn cache(&self) -> Cache {
Cache(())
}
pub fn http_client(&self) -> &HttpClient<S> {
&self.http_client
}
pub(crate) fn tick(&self, tick_env: &mut TickEnv<S::Msg>) where S: 'static {
tick_env.local_messages.append(
&mut self.http_client.local_queue
.borrow_mut()
.drain(..)
.collect::<Vec<_>>()
);
}
}
pub struct Cache(pub(crate) ());
impl Cache {
pub fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
browser::window()
.local_storage
.get::<T>(key)
}
pub fn insert<T: Serialize>(&self, key: &str, value: &T) {
browser::window()
.local_storage
.set::<T>(key, value);
}
pub fn remove(&self, key: &str) {
browser::window()
.local_storage
.remove(key);
}
}
pub struct HttpClient<S: Spec> {
pub(crate) mark: PhantomData<S>,
pub(crate) local_queue: Rc<RefCell<VecDeque<S::Msg>>>,
}
impl<S: Spec> HttpClient<S> {
pub fn send(
&self,
request: impl ToHttpRequest,
f: impl Fn(HttpResponse) -> S::Msg + 'static,
) -> Result<(), ()> where S::Msg: 'static {
fn parse_headers(value: String) -> Vec<(String, String)> {
value
.split("\r\n")
.map(|line| -> (String, String) {
let pos = line
.chars()
.position(|x| {
x == ':'
})
.expect("missing colon");
let (x, y) = line.split_at(pos);
let x = String::from(x);
let y = String::from(y.trim_start_matches(":"));
(x, y)
})
.collect::<Vec<_>>()
}
let HttpRequest{url,method,headers,body} = request.to_http_request();
let mut request = web_sys::XmlHttpRequest::new().expect("new XmlHttpRequest failed");
let method = method.unwrap_or(String::from("GET"));
request.open(&method, &url);
for (k, v) in headers {
request.set_request_header(&k, &v).expect("XmlHttpRequest.setRequestHeader() failed");
}
let onload_callback = Closure::once_into_js({
let local_queue = self.local_queue.clone();
let request = request.clone();
move |value: JsValue| {
let request = request;
let local_queue = local_queue;
let response_text = request
.response_text()
.expect("XmlHttpRequest.responseText getter failed");
let response_status = request
.status()
.expect("XmlHttpRequest.status getter failed");
let response_headers = request
.get_all_response_headers()
.expect("XmlHttpRequest.getAllResponseHeaders() failed");
console!("headers: {:#?}", &response_headers);
let response_headers = {
if response_headers.is_empty() {
Default::default()
} else {
parse_headers(response_headers)
}
};
let response = HttpResponse {
status: response_status,
headers: response_headers,
body: response_text.unwrap_or(Default::default()),
};
local_queue
.borrow_mut()
.push_back(f(response));
}
});
let onload_callback: js_sys::Function = From::from(onload_callback);
request.set_onloadend(Some(&onload_callback));
if let Some(body) = body {
request.send_with_opt_str(Some(&body)).expect("XmlHttpRequest.send method failed");
} else {
request.send().expect("XmlHttpRequest.send method failed");
}
Ok(())
}
pub fn send_ext(
&self,
custom: impl HttpClientExt<S::Msg> + 'static
) -> Result<(), ()> where S::Msg: 'static {
self.send(custom.to_http_request(), move |res| {
custom.on_reply(res)
})
}
}
pub trait HttpClientExt<Msg> : ToHttpRequest {
fn on_reply(&self, value: HttpResponse)->Msg;
}
pub trait ToHttpRequest {
fn to_http_request(&self) -> HttpRequest;
}
impl ToHttpRequest for HttpRequest {
fn to_http_request(&self) -> HttpRequest {
self.clone()
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct HttpRequest {
pub url: String,
pub method: Option<String>,
pub headers: Vec<(String, String)>,
pub body: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct HttpResponse {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: String,
}
thread_local! {
pub(crate) static GLOABL_MESSAGE_REGISTRY: RefCell<VecDeque<SystemMessage>> = {
RefCell::new(VecDeque::new())
};
}
#[derive(Debug, Clone)]
pub(crate) enum SystemMessage {
Public {
from_name: String,
from_tid: TypeId,
value: Rc<Any>,
},
Private {
from_name: String,
from_tid: TypeId,
to_tid: TypeId,
value: Rc<Any>,
},
}
impl SystemMessage {
pub fn is_private(&self) -> Option<TypeId> {
match self {
SystemMessage::Private{to_tid, ..} => Some(to_tid.clone()),
_ => None
}
}
pub(crate) fn value(&self) -> Rc<Any> {
match self {
SystemMessage::Private{value, ..} => value.clone(),
SystemMessage::Public{value, ..} => value.clone(),
}
}
pub(crate) fn from_name(&self) -> String {
match self {
SystemMessage::Private{from_name, ..} => from_name.clone(),
SystemMessage::Public{from_name, ..} => from_name.clone(),
}
}
pub(crate) fn from_tid(&self) -> TypeId {
match self {
SystemMessage::Private{from_tid, ..} => from_tid.clone(),
SystemMessage::Public{from_tid, ..} => from_tid.clone(),
}
}
pub(crate) fn sender_is_receiver<T: Spec + 'static>(&self, this_name: &str) -> bool {
let this_tid = TypeId::of::<T>();
let this_name = String::from(this_name);
(self.from_name() == this_name) && (self.from_tid() == this_tid)
}
}
pub(crate) fn process_system_requests<S: Spec + 'static>(name: &str, model: &S::Model, sys: &mut Shell<S>) {
for msg in sys.commands.borrow_mut().drain(..) {
match msg {
Command::Save => {
unimplemented!()
}
Command::Message(msg) => {
register_message(msg);
}
Command::Navigate(nav) => {
navigate(nav.as_str());
crate::program_sys::CURRENT_URL.with(|cell| {
let new_url = Url::get_current(&browser::window());
cell.replace(Some(new_url));
});
}
}
}
}
pub(crate) fn spec_key<S: Spec + 'static>(name: &str) -> String {
let tid = TypeId::of::<S>();
format!("{:?}-{}", tid, name)
}
pub(crate) fn save_model<S: Spec + 'static>(name: &str, model: &S::Model) {
unimplemented!()
}
pub(crate) fn load_saved_model<S: Spec + 'static>(name: &str) -> Option<S::Model> {
unimplemented!()
}
pub(crate) fn register_message(msg: SystemMessage) {
GLOABL_MESSAGE_REGISTRY.with(move |reg| {
reg.borrow_mut().push_back(msg);
});
}
pub(crate) fn navigate(route: &str) {
browser::window()
.history
.push_state(route);
}