summaryrefslogtreecommitdiff
path: root/webapp/src/components/app_context_provider.rs
blob: 35b35d7b47a90fc0f90e23b54b301387cee1d52f (plain)
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
use crate::{routing::Route, utils::ok_json};
use anyhow::Context;
use gloo_net::http::Request;
use log::error;
use log::info;
use protocol::UserInfo;
use std::future::Future;
use uuid::Uuid;
use wasm_bindgen_futures::spawn_local;
use yew::prelude::*;
use yew_router::prelude::*;

#[derive(Properties, Clone, PartialEq, Debug)]
pub struct ErrorInfoProperties {
    pub message: String,
}

#[derive(Clone, PartialEq)]
pub struct AppState {
    user: UseStateHandle<Option<UserInfo>>,
    error: UseStateHandle<Option<ErrorInfoProperties>>,
}

#[derive(Clone, PartialEq)]
pub struct AppContext {
    state: AppState,
    history: AnyHistory,
}

impl AppContext {
    pub fn spawn_async<F>(&self, f: F)
    where
        F: Future<Output = Result<(), anyhow::Error>> + 'static,
    {
        let error = self.state.error.clone();
        spawn_local(async move {
            if let Err(err) = f.await {
                error!("Error occurred: {err:?}");
                error.set(Some(ErrorInfoProperties {
                    message: format!("{err:?}"),
                }));
            }
        });
    }

    pub fn user(&self) -> Option<&UserInfo> {
        self.state.user.as_ref()
    }

    pub fn error(&self) -> Option<&ErrorInfoProperties> {
        self.state.error.as_ref()
    }

    pub fn set_error(&self, error: anyhow::Error) {
        self.state.error.set(Some(ErrorInfoProperties {
            message: format!("{error:?}"),
        }));
    }

    pub fn create_table(&self) {
        let user = self.state.user.clone();
        let history = self.history.clone();
        self.spawn_async(async move {
            let response = Request::post("/api/table").send().await?;
            let table_id: Uuid =
                ok_json(response).await.context("creating table")?;
            info!("Created table {table_id}");
            if let Some(user_info) = user.as_ref() {
                user.set(Some(UserInfo {
                    table: Some(protocol::Table { id: table_id }),
                    ..(user_info.clone())
                }));
            }
            history.push(Route::Home);
            Ok(())
        });
    }

    pub fn leave_table(&self) {
        let user = self.state.user.clone();
        let history = self.history.clone();
        self.spawn_async(async move {
            let response = Request::delete("/api/table").send().await?;
            if !response.ok() {
                anyhow::bail!("error while leaving table");
            }
            if let Some(user_info) = user.as_ref() {
                user.set(Some(UserInfo {
                    table: None,
                    ..(user_info.clone())
                }));
            }
            history.push(Route::Home);
            Ok(())
        });
    }
}

#[derive(Properties, Clone, PartialEq)]
pub struct Props {
    pub children: Children,
}

async fn initialize_user_info() -> Result<Option<UserInfo>, anyhow::Error> {
    let response = Request::get("/api/user/info")
        .send()
        .await
        .context("fetching user_info")?;
    if response.status() == 401 {
        web_sys::window()
            .unwrap()
            .location()
            .assign("/api/login")
            .unwrap();
    };
    ok_json(response).await.context("requesting user_info")
}

pub fn use_app_context() -> AppContext {
    let state: AppState = use_context::<AppState>().unwrap();
    let history = use_history().unwrap();

    AppContext { state, history }
}

#[function_component(AppContextProvider)]
pub fn app_context_provider(props: &Props) -> Html {
    let initialized = use_state(|| false);
    let user: UseStateHandle<Option<UserInfo>> = use_state(|| None);
    let error: UseStateHandle<Option<ErrorInfoProperties>> = use_state(|| None);

    {
        let initialized = initialized.clone();
        let user = user.clone();
        let error = error.clone();
        use_effect_with_deps(
            move |_| {
                spawn_local(async move {
                    initialized.set(true);
                    match initialize_user_info().await {
                        Ok(user_info) => user.set(user_info),
                        Err(e) => error.set(Some(ErrorInfoProperties {
                            message: format!(
                                "Could not contact server: {:?}",
                                e
                            ),
                        })),
                    };
                });
                || ()
            },
            (),
        );
    }

    if !*initialized {
        return html! {
                <p>{ "Loading app..." }</p>
        };
    }

    info!("Recomputing state");
    info!("User is {:?}", *user);

    let state = AppState { user, error };

    html! {
            <ContextProvider<AppState> context={state}>
                { for props.children.iter() }
            </ContextProvider<AppState>>
    }
}