use html::Textarea; use leptos::*; use leptos_use::{core::ConnectionReadyState, use_websocket, UseWebsocketReturn}; use lib::models::*; use serde_json::to_string; #[component] pub fn Websocket() -> impl IntoView { let UseWebsocketReturn { ready_state, message, send, open, close, .. } = use_websocket("ws://0.0.0.0:3030/websocket"); // Signals let (online_users, set_online_users) = create_signal(0); let (active_games, set_active_games) = create_signal(0); let (chat_history, set_chat_history) = create_signal::>(vec![]); // Websocket stuff let status = move || ready_state.get().to_string(); let connected = move || ready_state.get() == ConnectionReadyState::Open; let open_connection = move |_| { open(); }; let fake_new_game_request = NewGameRequest { name: String::from("Ligma"), host: Player { name: String::from("Adam"), role: PlayerRole::Host, white: vec![], black: vec![], }, packs: vec![0], }; // Game stuff let new_game_test = move |_| { send(&to_string(&fake_new_game_request).unwrap()); }; let close_connection = move |_| { close(); set_online_users(0); set_active_games(0); update_chat_history(&set_chat_history, format!("Disconnected.\n")); }; // Chat stuff let chat_history_ref = create_node_ref::(); fn update_chat_history(&history: &WriteSignal>, message: String) { let _ = &history.update(|history: &mut Vec<_>| history.push(message)); } // handle incoming messages create_effect(move |_| { message.with(move |message_raw| { // Send all messages as strings into chat box if let Some(message) = message_raw { if let Ok(_game) = serde_json::from_str::(message) { logging::log!("Game object received."); } else if let Ok(state_summary) = serde_json::from_str::(message) { logging::log!( "Users: {}\nGames: {}", state_summary.online_users, state_summary.active_games ); set_online_users(state_summary.online_users); set_active_games(state_summary.active_games); } else { update_chat_history(&set_chat_history, format!("{}\n", message)); } } }) }); create_effect(move |_| { chat_history.with(move |_| { // Scroll chat textarea to bottom if let Some(hist) = chat_history_ref.get() { hist.set_scroll_top(hist.scroll_height()); } }) }); // Login stuff let (username, _set_username) = create_signal("ligma"); view! { Connection "Users Online: " {online_users} "Active Games: " {active_games} "Connection Status: " {status} "Connect" "Disconnect" Sign in Username: Chat {move || chat_history.get()} // // "Send" // "Test New Game" } }
"Users Online: " {online_users}
"Active Games: " {active_games}
"Connection Status: " {status}
Username: