summaryrefslogtreecommitdiff
path: root/webapp/src/main.rs
blob: de4dd7a7a026effa6b721f947f87590e72c1c6c7 (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
#[allow(unused_imports)]
use log::{debug, error, info, warn};
use yew::prelude::*;
use yew_router::prelude::*;
pub mod components;
pub mod utils;
use components::{AppContextProvider, ErrorInfo, OnlineTable};
extern crate wee_alloc;
pub mod routing;
use crate::{components::use_app_context, routing::Route};
pub mod services;

// Use `wee_alloc` as the global allocator.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

fn main() {
    std::panic::set_hook(Box::new(console_error_panic_hook::hook));
    wasm_logger::init(wasm_logger::Config::new(log::Level::Debug));
    yew::start_app::<App>();
}

#[function_component(App)]
pub fn app() -> Html {
    html! {
        <>
            <AppContextProvider>
                <BrowserRouter>
                    <Switch<Route> render={Switch::render(switch)} />
                </BrowserRouter>
            </AppContextProvider>
        </>
    }
}

#[function_component(Home)]
fn home() -> Html {
    let ctx = use_app_context();

    let user = match &ctx.user() {
        Some(userinfo) => html! {
            <p>{ format!("Logged in as {}", userinfo.username) }</p>
        },
        None => html! { <p><a href="/api/login">{ "Log in" }</a></p> },
    };

    if let Some(table) = ctx.user().as_ref().and_then(|u| u.table.as_ref()) {
        let history = use_history().unwrap();
        history.push(Route::Table { id: table.id });
    }

    let create_table = {
        let ctx = ctx.clone();
        Callback::from(move |_| {
            ctx.create_table();
        })
    };

    html! {
        <ul>
        <li>{ user }</li>
        <li><button onclick={create_table}>{ "Create table" }</button></li>
        </ul>
    }
}

#[function_component(Header)]
fn header() -> Html {
    let ctx = use_app_context();
    html! {
        if let Some(error) = &ctx.error() {
            <ErrorInfo ..(*error).clone()/>
        }
    }
}

fn switch(routes: &Route) -> Html {
    let main = match routes {
        Route::Home => html! { <Home/> },
        Route::Table { id } => html! {
            <OnlineTable table={ protocol::Table { id: *id } } />
        },
    };

    html! {
        <>
          <Header/>
          { main }
        </>
    }
}