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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
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 futures::{Future};

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::*;


///////////////////////////////////////////////////////////////////////////////
// SHELL
///////////////////////////////////////////////////////////////////////////////


/// It’s a reincarnated-bourne-again shell for your everyday web-app
/// needs. :)
///
/// User-level commands are exposed or rather implemented as methods on
/// the `Shell` type (so from your docs navigate to “methods” section).
pub struct Shell<S: Spec> {
    pub(crate) instance_name: String,
    pub(crate) commands: RefCell<VecDeque<Command>>,
    pub(crate) mark: PhantomData<S>,
    pub(crate) tasks: Tasks<S>,
}

pub(crate) enum Command {
    Save,
    Message(SystemMessage),
    Navigate(String),
}


impl<S: Spec + 'static> Shell<S> {
    /// Internal.
    pub(crate) fn tick(&self, tick_env: &mut TickEnv<S::Msg>) where S: 'static {
        tick_env.local_messages.append(
            &mut self.tasks.local_queue
                .borrow_mut()
                .drain(..)
                .collect::<Vec<_>>()
        );
    }

    // pub fn save(&mut self) {
    //     self.commands.borrow_mut().push_back(Command::Save);
    // }

    /// Heterogeneous value broadcasting system.
    /// ```
    /// // lets broadcast some random messages (values) of different types
    /// sh.broadcast(SomeType(...));
    /// sh.broadcast(SomeOtherType(...));
    /// sh.broadcast(UrlRequest(Page::Something));
    /// ```
    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),
            }
        ));
    }
    /// Heterogeneous "component-to-component" value messaging system.
    /// ```
    /// // This is perhaps impossible without types hehe
    /// sh.message::<SomeComponentType>(message_value);
    /// ///         ^^^^^^^^^^^^^^^^^^^ sent a message to any component of the given type.
    /// ```
    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)
        }));
    }
    /// Update the browser’s URL (i.e. for SPAs).
    /// ```
    /// sh.navigate("/account");
    /// ```
    pub fn navigate(&mut self, path: impl UrlString) {
        self.commands.borrow_mut().push_back(Command::Navigate(path.url_string()));
    }
    /// Returns the current URL.
    pub fn current_url(&self) -> Url {
        Url::get_current(&browser::window())
    }
    /// Caching support.
    pub fn cache(&self) -> Cache {
        Cache(())
    }
    // /// Make http requests (e.g. for interacting with backend API services).
    // pub fn simple_http_client(&self) -> &SimpleHttpClient<S> {
    //     &self.simple_http_client
    // }
    pub fn void_task<F>(&self, future: F) where F: Future<Item = (), Error = ()> + 'static {
        wasm_bindgen_futures::spawn_local(future);
    }
    pub fn task<F>(&self, future: F) where F: Future<Item = S::Msg, Error=()> + 'static {
        let tasks = self.tasks.local_queue.clone();
        let future: Box<dyn Future<Item = (), Error = ()>> = Box::new(
            future
                .map({
                    let tasks = tasks.clone();
                    move |x: S::Msg| {
                        tasks.borrow_mut().push_back(x);
                        ()
                    }
                })
        );
        wasm_bindgen_futures::spawn_local(future);
    }
}

///////////////////////////////////////////////////////////////////////////////
// CACHE
///////////////////////////////////////////////////////////////////////////////

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);
    }
}

///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////

pub struct Tasks<S: Spec> {
    pub(crate) local_queue: Rc<RefCell<VecDeque<S::Msg>>>,
}

///////////////////////////////////////////////////////////////////////////////
// HTTP-CLIENT
///////////////////////////////////////////////////////////////////////////////

// pub struct SimpleHttpClient<S: Spec> {
//     pub(crate) mark: PhantomData<S>,
//     pub(crate) local_queue: Rc<RefCell<VecDeque<S::Msg>>>,
// }

// impl<S: Spec> SimpleHttpClient<S> {
//     pub fn send(
//         &self,
//         request: impl ToHttpRequest,
//         f: impl Fn(HttpResponse) -> S::Msg + 'static,
//     ) -> Result<(), ()> where S::Msg: 'static {
//         // HELPERS
//         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<_>>()
//         }
//         // SETUP
//         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));
//         // SEND
//         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");
//         }
//         // DONE
//         Ok(())
//     }
//     pub fn send_ext(
//         &self,
//         custom: impl HttpClientExt + 'static
//     ) -> Result<(), ()> where S::Msg: 'static {
//         // HELPERS
//         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<_>>()
//         }
//         // SETUP
//         let HttpRequest{url,method,headers,body} = custom.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()),
//                 };
//                 if let Some(value) = custom.on_reply(response) {
//                     register_message(SystemMessage::Public {
//                         from_name: String::from(""),
//                         from_tid: TypeId::of::<()>(),
//                         value,
//                     });
//                 }
//             }
//         });
//         let onload_callback: js_sys::Function = From::from(onload_callback);
//         request.set_onloadend(Some(&onload_callback));
//         // SEND
//         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");
//         }
//         // DONE
//         Ok(())
//     }
// }

// pub trait HttpClientExt : ToHttpRequest {
//     fn on_reply(&self, value: HttpResponse)-> Option<Rc<Any>>;
// }

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,
}

// impl HttpResponse {
//     pub fn output<T: DeserializeOwned>(&self) -> Result<T, ()> {
//         match serde_json::from_str::<T>(&self.body) {
//             Ok(value) => Ok(value),
//             _ => Err(())
//         }
//     }
// }



///////////////////////////////////////////////////////////////////////////////
// TIMEOUT
///////////////////////////////////////////////////////////////////////////////

// struct Timeouts<Msg>(Vec<Timeout<Msg>>);
// struct Timeout<Msg>{
//     triggered: RefCell<bool>,
//     name: Option<String>,
//     on_timeout: Box<Fn()->Msg>,
// }


///////////////////////////////////////////////////////////////////////////////
// GLOABL MESSAGES
///////////////////////////////////////////////////////////////////////////////
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<dyn Any>,
    },
    Private {
        from_name: String,
        from_tid: TypeId,
        to_tid: TypeId,
        value: Rc<dyn 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<dyn 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)
    }
}



///////////////////////////////////////////////////////////////////////////////
// MISCELLANEOUS HELPERS
///////////////////////////////////////////////////////////////////////////////

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 => {
                // save_model::<S>(name, model);
                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!()
    // browser::window()
    //     .local_storage
    //     .set::<S::Model>(&spec_key::<S>(name), model);
}

pub(crate) fn load_saved_model<S: Spec + 'static>(name: &str) -> Option<S::Model> {
    unimplemented!()
    // browser::window()
    //     .local_storage
    //     .get::<S::Model>(&spec_key::<S>(name))
}

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);
}

// pub(crate) fn http_request()