use leptos::*; use leptos_use::{core::ConnectionReadyState, use_websocket, UseWebsocketReturn}; use lib::*; use serde_json::from_str; use std::rc::Rc; #[derive(Clone)] pub struct WebSocketContext { pub ready_state: Signal, // pub message: Signal>, pub send: Rc, pub open: Rc, pub close: Rc, } impl WebSocketContext { pub fn new( ready_state: Signal, // message: Signal>, send: Rc, open: Rc, close: Rc, ) -> Self { Self { ready_state, // message, send, open, close, } } #[inline(always)] pub fn send(&self, message: &str) { (self.send)(message) } // #[inline(always)] // pub fn open(&self) { // (self.open)() // } // // #[inline(always)] // pub fn close(&self) { // (self.close)() // } } #[component] pub fn Websocket() -> impl IntoView { let UseWebsocketReturn { ready_state, message, send, open, close, .. } = use_websocket("ws://0.0.0.0:3030/websocket"); provide_context(WebSocketContext::new( ready_state, // message, Rc::new(send.clone()), Rc::new(open.clone()), Rc::new(close.clone()), )); // Contexts for message handler let (state_summary, set_state_summary) = create_signal::>(Option::None); // let (game_object, set_game_object) = create_signal::>(Option::None); let (user_update, set_user_update) = create_signal::>(Option::None); let (chat_update, set_chat_update) = create_signal::>(Option::None); let (chat_message, set_chat_message) = create_signal::>(Option::None); let (active_games, set_active_games) = create_signal::>(Option::None); let (card_packs_meta, set_card_packs_meta) = create_signal::(CardPacksMeta { official_meta: vec![], unofficial_meta: vec![], }); // provide_context::>>(game_object); provide_context::>>(user_update); provide_context::>>(chat_update); provide_context::>>(chat_message); provide_context::>>(active_games); provide_context::>(card_packs_meta); provide_context::>>(state_summary); // Message handler 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) = from_str::(message) { // set_game_object(Some(game)); // } if let Ok(state_summary) = from_str::(message) { set_state_summary(Some(state_summary)); } else if let Ok(chat_message) = from_str::(message) { set_chat_message(Some(chat_message)); } else if let Ok(user_update) = from_str::(message) { set_user_update(Some(user_update)); } else if let Ok(chat_update) = from_str::(message) { set_chat_update(Some(chat_update)); } else if let Ok(games_update) = from_str::(message) { set_active_games(Some(games_update)); } else if let Ok(packs_meta_update) = from_str::(message) { set_card_packs_meta(packs_meta_update); } else { logging::log!("Unhandled message: {}", message); } } }) }); }