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
pub mod use_fetch_collection_hook;
pub mod use_fetch_hook;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
pub use use_fetch_collection_hook::{
use_fetch_collection, IntoList, UseFetchCollection, UseFetchCollectionStatusTrait,
};
pub use use_fetch_hook::{use_fetch, UseFetch, UseFetchStatusTrait};
use comp_state::{topo, update_state_with_topo_id};
use seed::*;
use serde::de::{DeserializeOwned, Deserializer};
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::str::FromStr;
#[derive(Clone, Debug)]
pub enum UseFetchStatus {
Initialized,
Loading,
Failed,
Complete,
}
impl Default for UseFetchStatus {
fn default() -> Self {
UseFetchStatus::Initialized
}
}
pub trait UseFetchMsgTrait {
fn fetch_message(id: topo::Id, url: String, method: Method) -> Self;
fn fetched_message(id: topo::Id, response: String) -> Self;
}
pub(crate) fn fetch_json<
T: DeserializeOwned + 'static + Clone,
J: Serialize + Clone + 'static,
Ms: Default + Clone + 'static,
Mdl: 'static,
>(
id: topo::Id,
url: String,
json: J,
method: Method,
) -> impl Future<Output = Result<Ms, Ms>> {
seed::fetch::Request::new(url)
.method(method)
.send_json(&json)
.fetch_string(move |f| {
let data = f.response().unwrap().data;
update_state_with_topo_id::<UseFetchCollection<T, J>, _>(id, |u| {
u.status = UseFetchStatus::Complete;
u.string_response = Some(data.clone());
crate::schedule_update::<Ms, Mdl>(Ms::default());
});
Ms::default()
})
}
pub struct NextTick {
inner: JsFuture,
}
impl NextTick {
pub fn new() -> NextTick {
let promise = js_sys::Promise::resolve(&JsValue::NULL);
let inner = JsFuture::from(promise);
NextTick { inner }
}
}
impl Default for NextTick {
fn default() -> Self {
Self::new()
}
}
impl Future for NextTick {
type Output = ();
fn poll(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<()> {
match Pin::new(&mut self.get_mut().inner).poll(ctx) {
Poll::Ready(_) => Poll::Ready(()),
Poll::Pending => Poll::Pending,
}
}
}
pub fn from_str<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: FromStr,
T::Err: Display,
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
T::from_str(&s).map_err(serde::de::Error::custom)
}