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
|
use async_channel::{Receiver, Sender};
use chrono::NaiveDate;
use crate::{
app::{calendar, form, utils, App},
model::{event, event::Event},
};
pub fn send(tx: Sender<Msg>, msg: Msg) {
utils::spawn(async move {
let _ = tx.send(msg).await;
})
}
pub enum Msg {
ShowAddForm { date: NaiveDate },
ShowUpdateForm { event: Event },
AddEvent { new: Event },
UpdateEvent { old: Event, new: Event },
DeleteEvent { event: Event },
}
pub async fn event_handler(rx: Receiver<Msg>, mut app: App) {
while let Ok(msg) = rx.recv().await {
match msg {
Msg::ShowAddForm { date } => {
form::show(&app, event::init(date), true).await;
}
Msg::ShowUpdateForm { event } => {
form::show(&app, event, false).await;
}
Msg::AddEvent { new } => {
let date = new.date.clone();
app.events.push(new);
calendar::refresh_date(&app, date);
}
Msg::UpdateEvent { old, new } => {
let new_date = new.date.clone();
match app.events.iter().position(|e| e.id == new.id) {
Some(index) => {
app.events.remove(index);
app.events.push(new);
calendar::refresh_date(&app, new_date);
if old.date != new_date {
calendar::refresh_date(&app, old.date.clone())
}
}
None => println!("Event not found when updating from {:?} to {:?}", old, new),
}
}
Msg::DeleteEvent { event } => match app.events.iter().position(|e| e.id == event.id) {
Some(index) => {
app.events.remove(index);
calendar::refresh_date(&app, event.date);
}
None => println!("Event not found when trying to delete {:?}", event),
},
}
}
}
|