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
#![cfg(target_arch = "wasm32")]
use std::{
    cell::{Cell, UnsafeCell},
    default::Default,
    rc::Rc,
};

pub use serde_json::from_str;
pub use wasm_bindgen::JsCast;
pub use web_sys as web;

pub use yarte_derive::App;
pub use yarte_helpers::{helpers::big_num_32::*, recompile};

mod queue;

use self::queue::Queue;

/// App are object which encapsulate state and behavior
///
///
/// App communicate exclusively by directional exchanging messages
/// The sender can't wait the response since it never answer
// TODO: derive
pub trait App: Default + Sized + Unpin + 'static {
    type BlackBox;
    type Message: 'static;
    /// Private: empty for overridden in derive
    #[doc(hidden)]
    fn __render(&mut self, _addr: &Addr<Self>) {}

    /// Private: empty for overridden in derive
    #[doc(hidden)]
    fn __hydrate(&mut self, _addr: &Addr<Self>) {}

    /// Private: empty for overridden in derive
    #[doc(hidden)]
    fn __dispatch(&mut self, _msg: Self::Message, _addr: &Addr<Self>) {}

    /// Private: Start a new asynchronous app, returning its address.
    #[doc(hidden)]
    fn __start(self) -> Addr<Self>
    where
        Self: App,
    {
        Addr(Rc::new(Context::new(self)))
    }

    /// Construct and start a new asynchronous app, returning its
    /// address.
    ///
    /// This is constructs a new app using the `Default` trait, and
    /// invokes its `start` method.
    fn start_default() -> Addr<Self>
    where
        Self: App,
    {
        Self::default().__start()
    }
}

/// The address of App
pub struct Addr<A: App>(Rc<Context<A>>);

impl<A: App> Addr<A> {
    /// Enqueue message
    #[inline]
    fn push(&self, msg: A::Message) {
        self.0.q.push(msg);
        self.update();
    }

    /// Sends a message
    ///
    /// The message is always queued
    pub fn send(&self, msg: A::Message) {
        self.push(msg);
    }

    #[inline]
    fn update(&self) {
        if self.0.ready.get() {
            self.0.ready.replace(false);
            while let Some(msg) = self.0.q.pop() {
                // UB is checked by ready Cell
                unsafe {
                    self.0.app.get().as_mut().unwrap().__dispatch(msg, &self);
                }
                while let Some(msg) = self.0.q.pop() {
                    unsafe {
                        self.0.app.get().as_mut().unwrap().__dispatch(msg, &self);
                    }
                }
                unsafe {
                    self.0.app.get().as_mut().unwrap().__render(&self);
                }
            }
            self.0.ready.replace(true);
        }
    }

    /// Hydrate app
    /// Link events and save closures
    ///
    /// # Safety
    /// Produce **unexpected behaviour** if launched more than one time
    #[inline]
    pub unsafe fn hydrate(&self) {
        debug_assert!(!self.0.ready.get());
        // Only run one time
        self.0.app.get().as_mut().unwrap().__hydrate(&self);
        self.0.ready.replace(true);
        self.update();
    }
}

impl<A: App> Clone for Addr<A> {
    fn clone(&self) -> Self {
        Addr(Rc::clone(&self.0))
    }
}

/// Encapsulate inner context of the App
pub struct Context<A: App> {
    app: UnsafeCell<A>,
    q: Queue<A::Message>,
    ready: Cell<bool>,
}

impl<A: App> Context<A> {
    fn new(app: A) -> Self {
        Self {
            app: UnsafeCell::new(app),
            q: Queue::new(),
            ready: Cell::new(false),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::default::Default;

    use wasm_bindgen_futures::spawn_local;
    use wasm_bindgen_test::*;

    #[derive(Default)]
    struct Test {
        c: Rc<Cell<usize>>,
        any: usize,
        it: Vec<usize>,
        black_box: <Self as App>::BlackBox,
    }

    impl App for Test {
        type BlackBox = BlackBox;
        type Message = Msg;
        fn __dispatch(&mut self, m: Self::Message, addr: &Addr<Self>) {
            match m {
                Msg::Msg(i) => msg(self, i, addr),
                Msg::Reset => reset(self, addr),
                Msg::Tree(i) => msg_tree(self, i, addr),
                Msg::Fut(i) => msg_fut(self, i, addr),
            }
        }
    }

    /// PoC tree builder and diff
    /// Tree is a tree of flow with static bool slices for expressions and IfElse flow
    ///  `app.black_box.t_root & [bool; N] != 0`
    /// For iterables vector of bool slices allocated in black box
    ///  `app.black_box.t_children_I[J] & [bool; M] != 0`
    /// management of children will control by `__render`
    /// and macros push or pop or replace
    /// or manual control of black box
    ///
    /// BlackBox trait Tree control
    ///     - render_all:
    ///     - ignore_next_render ?:
    /// public fields in BlackBox for Dom references
    ///
    /// Construct in base of used variables in templates
    ///
    /// this macro is construct in derive
    #[derive(Debug, PartialEq)]
    struct BlackBox {
        t_root: u8,
        t_children_0: Vec<bool>,
    }

    impl Default for BlackBox {
        fn default() -> BlackBox {
            BlackBox {
                t_root: 0xFF,
                t_children_0: vec![],
            }
        }
    }

    impl BlackBox {
        fn set_zero(&mut self) {
            self.t_root = 0;
            for child in self.t_children_0.iter_mut() {
                *child = false;
            }
        }
    }

    #[macro_export]
    macro_rules! set_any {
        ($app:ident, $value:expr) => {
            // fields, index will set in derive
            $app.black_box.t_root |= 1 << 1;
            $app.any = $value;
        };
    }

    #[macro_export]
    macro_rules! set_it {
        ($app:ident, $value:expr) => {
            // fields, index will set in derive
            let value = $value;
            $app.black_box.t_root |= 1 << 2;
            $app.black_box.t_children_0 = vec![true; value.len()];
            $app.it = value;
        };
    }

    // For template
    // ```
    // <h1>{{ c }} {{ any }}</h1>
    // <div>
    //     {{# each it }}
    //         {{ this + 2 }}
    //         <br>
    //     {{/ each }}
    // </div>
    // ```
    //
    // get a black box tree
    // ```
    // struct BlackBox {
    //     t_root: bool,
    //     t_children_0: Vec<bool>,
    //     ...
    // }
    // ```
    //
    #[macro_export]
    macro_rules! push_it {
        ($app:ident, $value:expr) => {
            // fields, index will set in derive
            $app.black_box.t_root |= 1 << 2;
            $app.black_box.t_children_0.push(true);
            $app.it.push($value);
        };
    }

    #[macro_export]
    macro_rules! pop_it {
        ($app:ident) => {{
            // fields, index will set in derive
            $app.black_box.t_root |= 1 << 2;
            $app.black_box.t_children_0.pop();
            $app.it.pop()
        }};
    }

    #[macro_export]
    macro_rules! set_it_index {
        ($app:ident [$i:expr] $value:expr) => {
            // fields, index will set in derive
            $app.black_box.t_root |= 1 << 2;
            $app.black_box
                .t_children_0
                .get_mut($i)
                .map(|x| *x = true)
                .and_then(|_| $app.it.get_mut($i).map(|x| *x = $value))
        };
    }

    // #[templates(.., mode = "wasm")]
    // #[msg enum Msg {
    //      #[fn(msg)]
    //      Msg,
    //      #[fn(reset)]
    //      Reset,
    //      #[fn(msg_tree)]
    //      MsgTree(usize),
    //      #[fn(msg_fut)]
    //      MsgFut(usize),
    // }]
    enum Msg {
        Msg(usize),
        Reset,
        Tree(usize),
        Fut(usize),
    }

    #[inline]
    fn msg_tree(app: &mut Test, msg: usize, _addr: &Addr<Test>) {
        app.black_box.set_zero();
        // after first render
        let expected = BlackBox {
            t_root: 0,
            t_children_0: vec![],
        };
        assert_eq!(app.black_box, expected);
        set_any!(app, msg);
        set_it!(app, vec![1, 2, 3, 4]);
        let expected = BlackBox {
            t_root: 6,
            t_children_0: vec![true, true, true, true],
        };
        assert_eq!(app.black_box, expected);
        app.black_box.set_zero();
        push_it!(app, 5);
        let expected = BlackBox {
            t_root: 4,
            t_children_0: vec![false, false, false, false, true],
        };
        assert_eq!(app.black_box, expected);
        app.black_box.set_zero();
        let _ = pop_it!(app);
        let expected = BlackBox {
            t_root: 4,
            t_children_0: vec![false, false, false, false],
        };
        assert_eq!(app.black_box, expected);
        app.black_box.set_zero();
        let expected = BlackBox {
            t_root: 0,
            t_children_0: vec![false, false, false, false],
        };
        assert_eq!(app.black_box, expected);
        set_it_index!(app [1] 6);
        let expected = BlackBox {
            t_root: 4,
            t_children_0: vec![false, true, false, false],
        };
        assert_eq!(app.black_box, expected)
    }

    #[inline]
    fn msg(app: &mut Test, msg: usize, _addr: &Addr<Test>) {
        app.c.replace(msg);
    }

    #[inline]
    fn reset(_app: &mut Test, addr: &Addr<Test>) {
        addr.send(Msg::Msg(0));
    }

    #[inline]
    fn msg_fut(_app: &mut Test, msg: usize, addr: &Addr<Test>) {
        addr.send(Msg::Reset);
        let mb = addr.clone();
        let work = unsafe {
            async_timer::Timed::platform_new_unchecked(
                async move { mb.send(Msg::Msg(msg)) },
                core::time::Duration::from_secs(1),
            )
        };
        spawn_local(async move {
            work.await.unwrap();
        });
    }

    #[wasm_bindgen_test]
    fn test() {
        let c = Rc::new(Cell::new(0));
        let c2 = Rc::clone(&c);
        let app = Test {
            c,
            ..Default::default()
        };
        let addr = app.__start();
        unsafe {
            addr.hydrate();
        }
        let addr2 = addr.clone();
        addr.send(Msg::Msg(2));
        assert_eq!(c2.get(), 2);
        addr2.send(Msg::Msg(3));
        addr.send(Msg::Msg(1));
        assert_eq!(c2.get(), 1);
        addr.send(Msg::Msg(1));
        addr2.send(Msg::Msg(3));
        assert_eq!(c2.get(), 3);
        addr2.send(Msg::Reset);
        assert_eq!(c2.get(), 0);
        addr2.send(Msg::Msg(3));
        assert_eq!(c2.get(), 3);
        addr2.send(Msg::Fut(7));
        assert_eq!(c2.get(), 0);
        let c3 = Rc::clone(&c2);
        let work = unsafe {
            async_timer::Timed::platform_new_unchecked(async {}, core::time::Duration::from_secs(1))
        };
        spawn_local(async move {
            work.await.unwrap();
            assert_eq!(c3.get(), 7);
            addr2.send(Msg::Reset);
            assert_eq!(c3.get(), 0);
        });
        addr.send(Msg::Reset);
        assert_eq!(c2.get(), 0);
        addr.send(Msg::Tree(0))
    }
}