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
use std::cell::Ref;
use std::fmt;
use std::future::Future;

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
#[cfg(all(target_arch = "wasm32", feature = "web-csr"))]
use wasm_bindgen::UnwrapThrowExt;

use crate::reflow::{self, Cage, Revisable, RevisableId};
use crate::{Scope, Widget};

#[derive(Serialize, Deserialize, Default, Debug)]
#[serde(rename_all = "snake_case")]
pub enum LoadState<T>
where
    T: Serialize + fmt::Debug + 'static,
{
    #[default]
    Idle,
    Loading,
    Loaded(T),
}

impl<T> LoadState<T>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
{
    pub fn is_idle(&self) -> bool {
        matches!(self, Self::Idle)
    }
    pub fn is_loading(&self) -> bool {
        matches!(self, Self::Loading)
    }
    pub fn is_loaded(&self) -> bool {
        matches!(self, Self::Loaded(_))
    }
}

#[allow(clippy::type_complexity)]
pub struct Loader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    fut_maker: Option<Box<dyn Fn() -> Fut>>,
    callback: Box<dyn Fn(&T, &mut Scope)>,
    fallback: Option<Box<dyn Fn(&mut Scope)>>,
    state: Cage<LoadState<T>>,
    gathers: IndexMap<RevisableId, Box<dyn Revisable>>,
    observing: IndexMap<RevisableId, Box<dyn Revisable>>,
}
impl<T, Fut> fmt::Debug for Loader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Loader").finish()
    }
}

impl<T, Fut> Loader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    pub fn new(fut_maker: impl Fn() -> Fut + Clone + 'static, callback: impl Fn(&T, &mut Scope) + 'static) -> Self {
        Self {
            fut_maker: Some(Box::new(fut_maker)),
            callback: Box::new(callback),
            fallback: None,
            state: Cage::new(LoadState::Idle),
            gathers: IndexMap::new(),
            observing: IndexMap::new(),
        }
    }
    pub fn fallback(mut self, fallback: impl Fn(&mut Scope) + 'static) -> Self {
        self.fallback = Some(Box::new(fallback));
        self
    }
    pub fn state(&self) -> Ref<'_, LoadState<T>> {
        self.state.get()
    }
    pub fn observe(mut self, item: impl Revisable + 'static) -> Self {
        self.observing.insert(item.id(), Box::new(item));
        self
    }
}

impl<T, Fut> Widget for Loader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    fn attach(&mut self, _ctx: &mut Scope) {}

    fn build(&mut self, ctx: &mut Scope) {
        #[cfg(all(target_arch = "wasm32", feature = "web-csr"))]
        if crate::web::is_hydrating() {
            if let Some(new_state) = load_state(ctx) {
                if new_state.is_loaded() {
                    // Create fallback and remove it for server and client can create same view id.
                    if let Some(fallback) = &self.fallback {
                        (fallback)(ctx);
                        for view_id in ctx.show_list.clone() {
                            ctx.detach_child(&view_id);
                        }
                    }
                }
                self.state.revise(|mut state| {
                    *state = new_state;
                });
            }
        }
        self.state.bind_view(ctx.view_id());
        for item in self.observing.values() {
            item.bind_view(ctx.view_id());
        }

        let gathers = if !self.state().is_loaded() {
            if let Some(fallback) = &self.fallback {
                (fallback)(ctx);
            }

            let state = self.state.clone();
            let (gathers, fut) = reflow::gather(|| (self.fut_maker.as_ref().unwrap())());
            state.revise_silent(|mut state| {
                *state = LoadState::<T>::Loading;
            });
            crate::spawn::spawn_local(async move {
                let result = fut.await;
                state.revise(|mut state| {
                    *state = LoadState::Loaded(result);
                });
            });
            gathers
        } else {
            crate::reflow::gather(|| _ = (self.fut_maker.as_ref().unwrap())()).0
        };
        self.gathers = gathers;
        for gather in self.gathers.values() {
            gather.bind_view(ctx.view_id());
        }
    }

    fn patch(&mut self, ctx: &mut Scope) {
        let mut is_revising = false;
        for item in self.observing.values() {
            if item.is_revising() {
                is_revising = true;
                break;
            }
        }
        if !is_revising {
            for item in self.gathers.values() {
                if item.is_revising() {
                    is_revising = true;
                    break;
                }
            }
        }
        if is_revising {
            self.state.revise_silent(|mut state| {
                *state = LoadState::Loading;
            });

            if let Some(fallback) = &self.fallback {
                (fallback)(ctx);
            }

            for gather in std::mem::take(&mut self.gathers).values() {
                gather.unbind_view(ctx.view_id());
            }

            let state = self.state.clone();
            let (gathers, fut) = reflow::gather(|| (self.fut_maker.as_ref().unwrap())());
            crate::spawn::spawn_local(async move {
                let result = fut.await;
                state.revise(|mut state| {
                    *state = LoadState::Loaded(result);
                });
            });
            self.gathers = gathers;
            for gather in self.gathers.values() {
                gather.bind_view(ctx.view_id());
            }
        } else if let LoadState::Loaded(result) = &*self.state.get() {
            for view_id in ctx.show_list.clone() {
                ctx.detach_child(&view_id);
            }

            (self.callback)(result, ctx);

            for view_id in ctx.show_list.clone() {
                ctx.attach_child(&view_id);
            }
        }

        #[cfg(feature = "web-ssr")]
        save_state(ctx, &*self.state.get());
    }
}

#[cfg(feature = "web-ssr")]
fn save_state<T>(ctx: &Scope, state: &LoadState<T>)
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
{
    pub use base64::prelude::*;
    if let Some(parent_node) = &ctx.parent_node {
        let key = format!("gly-{}", ctx.view_id());
        let data = serde_json::to_string(&state).unwrap();
        parent_node.set_attribute(key, BASE64_STANDARD_NO_PAD.encode(&data));
    }
}

#[cfg(all(target_arch = "wasm32", feature = "web-csr"))]
fn load_state<T>(ctx: &Scope) -> Option<LoadState<T>>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
{
    let key = format!("gly-{}", ctx.view_id());
    if let Some(parent_node) = &ctx.parent_node {
        if let Some(data) = parent_node.get_attribute(&key) {
            parent_node.remove_attribute(&key).ok();
            let data = crate::web::window().atob(&data).unwrap_throw();
            return serde_json::from_str(&data).ok();
        }
    }
    None
}

#[allow(clippy::type_complexity)]
pub struct OnceLoader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    fut_maker: Option<Box<dyn FnOnce() -> Fut>>,
    callback: Box<dyn Fn(&T, &mut Scope)>,
    fallback: Option<Box<dyn Fn(&mut Scope)>>,
    state: Cage<LoadState<T>>,
}
impl<T, Fut> fmt::Debug for OnceLoader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OnceLoader").finish()
    }
}

impl<T, Fut> OnceLoader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    pub fn new(fut_maker: impl FnOnce() -> Fut + 'static, callback: impl Fn(&T, &mut Scope) + 'static) -> Self {
        Self {
            fut_maker: Some(Box::new(fut_maker)),
            callback: Box::new(callback),
            fallback: None,
            state: Cage::new(LoadState::Idle),
        }
    }
    pub fn fallback(mut self, fallback: impl Fn(&mut Scope) + 'static) -> Self {
        self.fallback = Some(Box::new(fallback));
        self
    }
    pub fn state(&self) -> Ref<'_, LoadState<T>> {
        self.state.get()
    }
}

impl<T, Fut> Widget for OnceLoader<T, Fut>
where
    T: Serialize + for<'a> Deserialize<'a> + fmt::Debug + 'static,
    Fut: Future<Output = T> + 'static,
{
    fn attach(&mut self, _ctx: &mut Scope) {}

    fn build(&mut self, ctx: &mut Scope) {
        #[cfg(all(target_arch = "wasm32", feature = "web-csr"))]
        if crate::web::is_hydrating() {
            if let Some(new_state) = load_state(ctx) {
                if new_state.is_loaded() {
                    // Create fallback and remove it for server and client can create same view id.
                    if let Some(fallback) = &self.fallback {
                        (fallback)(ctx);
                        for view_id in ctx.show_list.clone() {
                            ctx.detach_child(&view_id);
                        }
                    }
                }
                self.state.revise(|mut state| {
                    *state = new_state;
                });
            }
        }
        self.state.bind_view(ctx.view_id());

        if !self.state().is_loaded() {
            if let Some(fallback) = &self.fallback {
                (fallback)(ctx);
            }

            let state = self.state.clone();
            let fut = (self.fut_maker.take().unwrap())();
            state.revise_silent(|mut state| {
                *state = LoadState::<T>::Loading;
            });
            crate::spawn::spawn_local(async move {
                let result = fut.await;
                state.revise(|mut state| {
                    *state = LoadState::Loaded(result);
                });
            });
        } else {
            self.fut_maker.take();
        }
    }

    fn patch(&mut self, ctx: &mut Scope) {
        if let LoadState::Loaded(result) = &*self.state.get() {
            for view_id in ctx.show_list.clone() {
                ctx.detach_child(&view_id);
            }

            (self.callback)(result, ctx);

            for view_id in ctx.show_list.clone() {
                ctx.attach_child(&view_id);
            }
        }

        #[cfg(feature = "web-ssr")]
        save_state(ctx, &*self.state());
    }
}