-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathlib.rs
207 lines (192 loc) · 6.37 KB
/
lib.rs
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
#![deny(warnings)]
use sauron::dom::spawn_local;
use sauron::dom::Http;
use sauron::html::attributes::*;
use sauron::html::events::*;
use sauron::html::*;
use sauron::js_sys::TypeError;
use sauron::{jss, text, wasm_bindgen, Application, Cmd, Node, Program};
use serde::Deserialize;
#[macro_use]
extern crate log;
const DATA_URL: &str = "https://reqres.in/api/users";
const PER_PAGE: i32 = 4;
#[derive(Debug)]
pub enum Msg {
NextPage,
PrevPage,
ReceivedData(Data),
JsonError(serde_json::Error),
RequestError(TypeError),
}
pub struct App {
page: i32,
data: Data,
error: Option<String>,
}
#[derive(Deserialize, Debug, PartialEq, Clone, Default)]
pub struct Data {
page: i32,
per_page: i32,
total: i32,
total_pages: i32,
data: Vec<User>,
}
#[derive(Deserialize, PartialEq, Debug, Clone)]
pub struct User {
id: i32,
email: String,
first_name: String,
last_name: String,
avatar: String,
}
impl App {
pub fn new() -> Self {
App {
page: 1,
data: Data::default(),
error: None,
}
}
fn fetch_page(&self) -> Cmd<Self, Msg> {
let url = format!("{}?page={}&per_page={}", DATA_URL, self.page, PER_PAGE);
Cmd::new(|mut program| {
spawn_local(async move {
let msg = match Http::fetch_text(&url).await {
Ok(v) => match serde_json::from_str(&v) {
Ok(data1) => Msg::ReceivedData(data1),
Err(err) => Msg::JsonError(err),
},
Err(e) => Msg::RequestError(e),
};
program.dispatch(msg);
})
})
}
}
impl Application<Msg> for App {
fn init(&mut self) -> Cmd<Self, Msg> {
console_log::init_with_level(log::Level::Trace).unwrap();
self.fetch_page()
}
fn view(&self) -> Node<Msg> {
div(
[],
[
div(
[class("some-class"), id("some-id"), attr("data-id", 1)],
[
input(
[
class("prev_page"),
r#type("button"),
disabled(self.page <= 1),
value("<< Prev Page"),
on_click(|_| {
trace!("Button is clicked");
Msg::PrevPage
}),
],
[],
),
text(format!("Page: {}", self.page)),
input(
[
class("next_page"),
r#type("button"),
disabled(self.page >= self.data.total_pages),
value("Next Page >>"),
on_click(|_| {
trace!("Button is clicked");
Msg::NextPage
}),
],
[],
),
],
),
div([], []).with_children(self.data.data.iter().map(|user| {
ul(
[],
[
li([], [text(&user.id)]),
li([], [text(&user.email)]),
li([], [text(&user.first_name)]),
li([], [img([src(&user.avatar)], [])]),
],
)
})),
footer(
[class("error")],
[if let Some(error) = &self.error {
text(error)
} else {
text!("")
}],
),
],
)
}
fn update(&mut self, msg: Msg) -> Cmd<Self, Msg> {
trace!("App is updating from msg: {:?}", msg);
match msg {
Msg::NextPage => {
if self.page < self.data.total_pages {
self.page += 1;
self.fetch_page()
} else {
Cmd::none()
}
}
Msg::PrevPage => {
if self.page > 1 {
self.page -= 1;
}
self.fetch_page()
}
Msg::ReceivedData(data1) => {
self.data = data1;
Cmd::none()
}
Msg::JsonError(err) => {
trace!("Error fetching users! {:#?}", err);
self.error = Some(format!("There was an error fetching the page: {:?}", err));
Cmd::none()
}
Msg::RequestError(type_error) => {
trace!("Error requesting the page: {:?}", type_error);
self.error = Some(format!(
"There was an error fetching the page: {:?}",
type_error
));
Cmd::none()
}
}
}
fn stylesheet() -> Vec<String> {
vec![jss! {
"body": {
font_family: "Fira Sans, Courier New, Courier, Lucida Sans Typewriter, Lucida Typewriter, monospace",
}
}]
}
}
#[wasm_bindgen(start)]
pub fn main() {
console_error_panic_hook::set_once();
Program::mount_to_body(App::new());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_json() {
let json = r#"
{"page":1,"per_page":3,"total":12,"total_pages":4,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"},{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"},{"id":3,"email":"emma.wong@reqres.in","first_name":"Emma","last_name":"Wong","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"}]}
"#;
println!("json: {}", json);
let res: Result<Data, _> = serde_json::from_str(json);
println!("res: {:#?}", res);
assert!(res.is_ok());
}
}