add shitty game browser

This commit is contained in:
Adam 2024-07-28 02:36:04 -04:00
parent 52b147e93d
commit 89b7af27d6
9 changed files with 118 additions and 47 deletions

View file

@ -35,22 +35,19 @@ pub fn Auth() -> impl IntoView {
<div class="p-1"> <div class="p-1">
<h2 class="text-2xl">Sign in:</h2> <h2 class="text-2xl">Sign in:</h2>
<p>Username:</p> <p>Username:</p>
<form <form onsubmit="return false" on:submit=send_login>
onsubmit="return false" <input
on:submit=send_login class="w-96 font-mono rounded-sm bg-slate-900 text-slate-200"
> placeholder=move || username.get()
<input node_ref=username_input_ref
class="w-96 font-mono rounded-sm bg-slate-900 text-slate-200" />
placeholder=move || username.get() <br/>
node_ref=username_input_ref <input
/> class="py-2 px-4 pl-4 font-bold text-white rounded border-b-4 bg-slate-600 border-slate-800 hover:bg-slate-700 hover:border-slate-500"
<br /> type="submit"
<input value="Send"
class="py-2 px-4 pl-4 font-bold text-white rounded border-b-4 bg-slate-600 border-slate-800 hover:bg-slate-700 hover:border-slate-500" />
type="submit" </form>
value="Send"
/>
</form>
</div> </div>
} }
} }

View file

@ -0,0 +1,39 @@
use crate::components::websocket::WebSocketContext;
use leptos::*;
use leptos_use::core::ConnectionReadyState;
use lib::models::GamesUpdate;
#[component]
pub fn Browser() -> impl IntoView {
let websocket = expect_context::<WebSocketContext>();
let game_update_context = expect_context::<ReadSignal<Option<GamesUpdate>>>();
let (active_games, set_active_games) = create_signal::<Vec<String>>(vec![]);
create_effect(move |_| {
game_update_context.with(move |games| {
if let Some(games) = games {
set_active_games(games.games.clone());
logging::log!("{:#?}",active_games());
}
})
});
// Clear games list on disconnect
create_effect(move |_| {
websocket.ready_state.with(move |status| {
if *status == ConnectionReadyState::Closed {
set_active_games(vec![]);
}
})
});
view! {
<div class="p-1">
<ul>
<h2 class="text-2xl">Game Browser</h2>
{move || active_games().into_iter().map(|n| view! { <li>{n}</li> }).collect_view()}
</ul>
</div>
}
}

View file

@ -95,37 +95,34 @@ pub fn Chat() -> impl IntoView {
<div class="p-1"> <div class="p-1">
<h2 class="text-2xl">Chat:</h2> <h2 class="text-2xl">Chat:</h2>
<span class="flex"> <span class="flex">
<textarea <textarea
node_ref=chat_history_ref node_ref=chat_history_ref
class="w-96 h-60 font-mono rounded-sm resize-none bg-slate-900 text-slate-200" class="w-96 h-60 font-mono rounded-sm resize-none bg-slate-900 text-slate-200"
readonly=true readonly=true
wrap="soft" wrap="soft"
> >
{move || chat_history.get()} {move || chat_history.get()}
</textarea> </textarea>
<ul> <ul>
<h2 class="text-2xl">Users:</h2> <h2 class="text-2xl">Users:</h2>
{move || users().into_iter().map(|n| view! {<li>{n}</li>}).collect_view()} {move || users().into_iter().map(|n| view! { <li>{n}</li> }).collect_view()}
</ul> </ul>
</span> </span>
<br/> <br/>
<span> <span>
<form <form onsubmit="return false" on:submit=send_message>
onsubmit="return false" <input
on:submit=send_message class="w-80 h-11 font-mono rounded-sm bg-slate-900 text-slate-200"
> placeholder="talk shit..."
<input node_ref=chat_input_ref
class="w-80 h-11 font-mono rounded-sm bg-slate-900 text-slate-200" />
placeholder="talk shit..." <input
node_ref=chat_input_ref class="py-2 px-4 pl-4 font-bold text-white rounded border-b-4 bg-slate-600 border-slate-800 hover:bg-slate-700 hover:border-slate-500"
/> type="submit"
<input value="Send"
class="py-2 px-4 pl-4 font-bold text-white rounded border-b-4 bg-slate-600 border-slate-800 hover:bg-slate-700 hover:border-slate-500" />
type="submit" </form>
value="Send"
/>
</form>
</span> </span>
<br/> <br/>
</div> </div>

View file

@ -1,4 +1,5 @@
pub mod auth; pub mod auth;
pub mod browser;
pub mod chat; pub mod chat;
pub mod debug; pub mod debug;
pub mod websocket; pub mod websocket;

View file

@ -73,11 +73,13 @@ pub fn Websocket() -> impl IntoView {
let (user_update, set_user_update) = create_signal::<Option<UserUpdate>>(Option::None); let (user_update, set_user_update) = create_signal::<Option<UserUpdate>>(Option::None);
let (chat_update, set_chat_update) = create_signal::<Option<ChatUpdate>>(Option::None); let (chat_update, set_chat_update) = create_signal::<Option<ChatUpdate>>(Option::None);
let (chat_message, set_chat_message) = create_signal::<Option<ChatMessage>>(Option::None); let (chat_message, set_chat_message) = create_signal::<Option<ChatMessage>>(Option::None);
let (active_games, set_active_games) = create_signal::<Option<GamesUpdate>>(Option::None);
provide_context::<ReadSignal<Option<Game>>>(game_object); provide_context::<ReadSignal<Option<Game>>>(game_object);
provide_context::<ReadSignal<Option<UserUpdate>>>(user_update); provide_context::<ReadSignal<Option<UserUpdate>>>(user_update);
provide_context::<ReadSignal<Option<ChatUpdate>>>(chat_update); provide_context::<ReadSignal<Option<ChatUpdate>>>(chat_update);
provide_context::<ReadSignal<Option<ChatMessage>>>(chat_message); provide_context::<ReadSignal<Option<ChatMessage>>>(chat_message);
provide_context::<ReadSignal<Option<GamesUpdate>>>(active_games);
provide_context::<ReadSignal<Option<ServerStateSummary>>>(state_summary); provide_context::<ReadSignal<Option<ServerStateSummary>>>(state_summary);
// Message handler // Message handler
@ -96,6 +98,8 @@ pub fn Websocket() -> impl IntoView {
set_user_update(Some(user_update)); set_user_update(Some(user_update));
} else if let Ok(chat_update) = from_str::<ChatUpdate>(message) { } else if let Ok(chat_update) = from_str::<ChatUpdate>(message) {
set_chat_update(Some(chat_update)); set_chat_update(Some(chat_update));
} else if let Ok(games_update) = from_str::<GamesUpdate>(message) {
set_active_games(Some(games_update));
} else { } else {
logging::log!("Unhandled message: {}", message); logging::log!("Unhandled message: {}", message);
} }

View file

@ -1,4 +1,5 @@
use crate::components::auth::*; use crate::components::auth::*;
use crate::components::browser::*;
use crate::components::chat::*; use crate::components::chat::*;
use crate::components::debug::*; use crate::components::debug::*;
use crate::components::websocket::*; use crate::components::websocket::*;
@ -34,6 +35,8 @@ pub fn Home() -> impl IntoView {
<hr/> <hr/>
<Auth/> <Auth/>
<hr/> <hr/>
<Browser/>
<hr/>
<Chat/> <Chat/>
<hr/> <hr/>
<Debug/> <Debug/>

View file

@ -1,5 +1,11 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Games update
#[derive(Serialize, Deserialize, Debug)]
pub struct GamesUpdate {
pub games: Vec<String>,
}
/// Chat update /// Chat update
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct ChatUpdate { pub struct ChatUpdate {
@ -7,7 +13,6 @@ pub struct ChatUpdate {
pub users: Vec<String>, pub users: Vec<String>,
} }
/// User update /// User update
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct UserUpdate { pub struct UserUpdate {
@ -21,7 +26,7 @@ pub struct UserLogIn {
} }
/// Chat message /// Chat message
#[derive(Clone, Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct ChatMessage { pub struct ChatMessage {
pub text: String, pub text: String,
} }

View file

@ -41,6 +41,16 @@ fn generate_chat_update(state: &Arc<AppState>) -> ChatUpdate {
} }
} }
fn generate_games_update(state: &Arc<AppState>) -> GamesUpdate {
let mut names = vec![];
for game in state.games.lock().unwrap().iter() {
names.push(game.name.clone());
}
GamesUpdate { games: names }
}
pub async fn on_websocket_connection(stream: WebSocket, state: Arc<AppState>, addr: SocketAddr) { pub async fn on_websocket_connection(stream: WebSocket, state: Arc<AppState>, addr: SocketAddr) {
// Add User to users // Add User to users
let new_user = User { let new_user = User {
@ -80,6 +90,11 @@ pub async fn on_websocket_connection(stream: WebSocket, state: Arc<AppState>, ad
to_string(&server_sum_update(&state)).unwrap(), to_string(&server_sum_update(&state)).unwrap(),
)) ))
.await; .await;
let _ = &sender
.send(Message::Text(
to_string(&generate_games_update(&state)).unwrap(),
))
.await;
// ANNOUNCE THY PRESENCE // ANNOUNCE THY PRESENCE
let msg = ChatMessage { let msg = ChatMessage {

View file

@ -21,6 +21,7 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, addr: Sock
tracing::error!("Failed to convert Game object to JSON.") tracing::error!("Failed to convert Game object to JSON.")
} }
state.games.lock().unwrap().push(new_game_object); state.games.lock().unwrap().push(new_game_object);
let _ = tx.send(to_string(&generate_games_update(state)).unwrap());
let _ = tx.send(to_string(&server_sum_update(state)).unwrap()); let _ = tx.send(to_string(&server_sum_update(state)).unwrap());
// let _update = tx.send(motd()); // let _update = tx.send(motd());
} else { } else {
@ -33,7 +34,13 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, addr: Sock
} else if let Ok(user_log_in) = serde_json::from_str::<UserLogIn>(&text) { } else if let Ok(user_log_in) = serde_json::from_str::<UserLogIn>(&text) {
let old_name = state.users.lock().unwrap().get(&addr).unwrap().name.clone(); let old_name = state.users.lock().unwrap().get(&addr).unwrap().name.clone();
let new_name = user_log_in.username.clone(); let new_name = user_log_in.username.clone();
state.users.lock().unwrap().get_mut(&addr).unwrap().change_name(user_log_in.username); state
.users
.lock()
.unwrap()
.get_mut(&addr)
.unwrap()
.change_name(user_log_in.username);
let msg = format! { let msg = format! {
"{0} changed name to {1}.", "{0} changed name to {1}.",
old_name, old_name,
@ -62,7 +69,10 @@ pub async fn message_handler(message: Message, state: &Arc<AppState>, addr: Sock
tracing::debug!("close received without close frame") tracing::debug!("close received without close frame")
} }
let msg = ChatMessage { let msg = ChatMessage {
text: format!("{0} left.", state.users.lock().unwrap().get(&addr).unwrap().name), text: format!(
"{0} left.",
state.users.lock().unwrap().get(&addr).unwrap().name
),
}; };
tracing::debug!("{}", msg.text); tracing::debug!("{}", msg.text);
let _ = tx.send(to_string::<ChatMessage>(&msg).unwrap()); let _ = tx.send(to_string::<ChatMessage>(&msg).unwrap());