cards/client/src/components/auth.rs
2024-09-07 01:17:51 -04:00

72 lines
2.7 KiB
Rust

use crate::components::websocket::WebSocketContext;
use leptos::{html::Input, prelude::*};
use leptos_use::core::ConnectionReadyState;
use lib::*;
use serde_json::to_string;
#[component]
pub fn Auth() -> impl IntoView {
let websocket = expect_context::<WebSocketContext>();
let (username, set_username) = signal("".to_string());
let user_context = expect_context::<ReadSignal<Option<UserUpdate>>>();
let connected = move || websocket.ready_state.get() == ConnectionReadyState::Open;
Effect::new(move |_| {
user_context.with(|new_user| {
if let Some(user) = new_user {
set_username(user.username.to_string());
}
})
});
let username_input_ref = NodeRef::<Input>::new();
let send_login = move |_| {
if let Some(input) = username_input_ref.get() {
if input.value() != String::from("") {
websocket.send(
&to_string(&UserLogInRequest {
username: input.value(),
})
.unwrap(),
);
set_username.set("".to_string());
input.set_value("");
}
}
};
// Clear user name on disconnect
Effect::new(move |_| {
if !connected() {
set_username(String::from(""));
}
});
view! {
<div class="my-2">
<h2 class="text-2xl">Sign in:</h2>
<Show when=move || { connected() } fallback=|| view! { <p>"Disconnected."</p> }>
<p>
"You were already given a random name but if you'd like to change it this is the place. Identities are saved once created so if you leave or get disconnected just enter your old name here to \"log back in\". Please don't steal each other's identities (yes, you can)."
</p>
<br />
<p>Username:</p>
<form onsubmit="return false" on:submit=send_login.clone()>
<input
class="w-96 font-mono rounded-sm bg-neutral-900 text-neutral-200"
placeholder=move || username.get()
node_ref=username_input_ref
disabled=move || !connected()
/>
<br />
<input
class="py-2 px-4 pl-4 font-bold text-white rounded border-b-4 bg-neutral-600 border-neutral-800 hover:bg-neutral-700 hover:border-neutral-500"
type="submit"
value="Send"
disabled=move || !connected()
/>
</form>
</Show>
</div>
}
}