### Subscribe to and Send Messages in a Leptos Component Source: https://github.com/synphonyte/leptos-axum-socket/blob/main/README.md Use `expect_socket_context` to get the socket instance within a Leptos component. Subscribe to messages using a specific key and log received messages. Send messages using the `send` method. ```rust #[component] pub fn MyComponent() -> impl IntoView { let socket = expect_socket_context(); // Subscribe to receive messages that are sent with the given key socket.subscribe( MyKey { bla: "bla".to_string(), }, |msg: &MyMsg| { // Simply log the message leptos::logging::log!("message: {msg:#?}"); }, ); let on_click = move || { // Send a message with the given key socket.send( MyKey { bla: "bla".to_string(), }, MyMsg { awesome_msg: "awesome message".to_string(), }, ); }; view! { "..." } } ``` -------------------------------- ### Add Send Mapper to ServerSocket Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Adds a mapper to transform or filter outgoing messages. Return `Some(msg)` to allow the message (optionally modified), or `None` to block it. This example sanitizes messages and blocks those exceeding 1000 characters. ```rust use leptos_axum_socket::{ServerSocket, SocketMsg}; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct ChatKey { room_id: Uuid } #[derive(Clone, Serialize, Deserialize, Debug)] struct ChatMsg { message: String, author: String } impl SocketMsg for ChatMsg { type Key = ChatKey; #[cfg(feature = "ssr")] type AppState = crate::AppState; } #[derive(Clone)] struct SocketContext { user_id: Uuid } #[cfg(feature = "ssr")] async fn setup_mappers(server_socket: &ServerSocket) { let mut socket = server_socket.lock().await; // Add message mapper - sanitize content before broadcasting socket.add_send_mapper(|key: ChatKey, mut msg: ChatMsg, _ctx: &SocketContext| { // Sanitize message content msg.message = msg.message .replace("", ""); // Return Some to allow, None to block if msg.message.len() > 1000 { None // Block messages that are too long } else { Some(msg) } }); } ``` -------------------------------- ### Register WebSocket Endpoint with SocketRoute Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt The `SocketRoute` trait provides the `socket_route` method to easily register a WebSocket endpoint. This example shows adding it to an Axum router. ```rust use axum::Router; use leptos_axum_socket::SocketRoute; #[cfg(feature = "ssr")] fn build_router(state: AppState) -> Router { Router::new() // ... other routes ... .socket_route(connect_to_websocket) // Adds GET /socket-msg .with_state(state) } ``` -------------------------------- ### ServerSocket Initialization and Axum Integration Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Demonstrates how to initialize the ServerSocket and integrate it into an Axum application, including registering the WebSocket route. ```APIDOC ## ServerSocket The `ServerSocket` struct is the server-side component that manages WebSocket connections and message routing. It must be included in your Axum application state and is used to configure subscription filters and message mappers. ### Usage Example ```rust use leptos::prelude::* use leptos_axum_socket::ServerSocket use axum::extract::FromRef #[cfg(feature = "ssr")] #[derive(Clone, FromRef)] pub struct AppState { pub leptos_options: LeptosOptions, pub server_socket: ServerSocket, } #[cfg(feature = "ssr")] #[tokio::main] async fn main() { use axum::Router use leptos_axum::{generate_route_list, LeptosRoutes} use leptos_axum_socket::SocketRoute let conf = get_configuration(None).unwrap(); let routes = generate_route_list(App); // Create the server socket let state = AppState { leptos_options: conf.leptos_options.clone(), server_socket: ServerSocket::new(), }; let app = Router::new() .leptos_routes(&state, routes, { let opts = state.leptos_options.clone(); move || shell(opts.clone()) }) .socket_route(connect_to_websocket) // Register WebSocket route .with_state(state); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app.into_make_service()).await.unwrap(); } ``` ``` -------------------------------- ### Initialize Axum App with ServerSocket and Routes Source: https://github.com/synphonyte/leptos-axum-socket/blob/main/README.md Initialize your Axum app in `main.rs`, construct the `AppState`, and register the `ServerSocket` and Leptos routes. The `socket_route` method is used to register the WebSocket connection handler. ```rust #[tokio::main] async fn main() { let conf = get_configuration(None).unwrap(); let addr = conf.leptos_options.site_addr; let routes = generate_route_list(App); // Construct the Axum app state let state = AppState { leptos_options: conf.leptos_options, server_socket: ServerSocket::new(), }; // Optional: add subscription filters and message mappers { let mut server_socket = state.server_socket.lock().await; server_socket.add_subscribe_filter(async |key: MyKey, _ctx: &()| { key.bla == "bla" }); server_socket.add_send_mapper(|key: MyKey, msg: MyMsg, _ctx: &()| { if key.bla == "bla" { Some(MyMsg { awesome_msg: msg.awesome_msg.replace("old", "new"), }) } else { None } }); } // Init the Axum app let app: Router = Router::new() .leptos_routes(&state, routes, { let leptos_options = state.leptos_options.clone(); move || shell(leptos_options.clone()) }) .socket_route(connect_to_websocket) // Register the socket route (implementation below) .fallback(leptos_axum::file_and_error_handler::(shell)) .with_state(state); // Register the state let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); // axum::serve(listener, app.into_make_service()) // .await // .unwrap(); } ``` -------------------------------- ### Implement full-stack chat application Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Demonstrates shared state, server-side socket routing, and client-side subscription management for a chat room. ```rust // lib.rs - Shared types and state use leptos::prelude::*; use leptos_axum_socket::{ServerSocket, SocketMsg}; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[cfg(feature = "ssr")] #[derive(Clone, axum::extract::FromRef)] pub struct AppState { pub leptos_options: LeptosOptions, pub server_socket: ServerSocket, } #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] pub struct ChatKey { pub room_id: Uuid } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct ChatMsg { pub id: Uuid, pub message: String, pub author: String, } impl SocketMsg for ChatMsg { type Key = ChatKey; #[cfg(feature = "ssr")] type AppState = AppState; } // main.rs - Server setup #[cfg(feature = "ssr")] #[tokio::main] async fn main() { use axum::{Router, extract::{State, WebSocketUpgrade, Query}, response::Response}; use leptos_axum::{generate_route_list, LeptosRoutes}; use leptos_axum_socket::{SocketRoute, handlers::upgrade_websocket}; let conf = get_configuration(None).unwrap(); let state = AppState { leptos_options: conf.leptos_options.clone(), server_socket: ServerSocket::new(), }; // Configure filters { let mut socket = state.server_socket.lock().await; socket.add_subscribe_filter(async |_key: ChatKey, _ctx: &()| true); } let app = Router::new() .leptos_routes(&state, generate_route_list(App), move || shell(conf.leptos_options.clone())) .socket_route(|ws: WebSocketUpgrade, State(socket): State| async { upgrade_websocket(ws, socket, ()) }) .with_state(state); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app.into_make_service()).await.unwrap(); } // app.rs - Client components use leptos::prelude::*; use leptos_axum_socket::{provide_socket_context, expect_socket_context}; #[component] pub fn App() -> impl IntoView { provide_socket_context(); view! { } } #[component] pub fn ChatRoom(room_id: Uuid) -> impl IntoView { let socket = expect_socket_context(); let (messages, set_messages) = signal(Vec::::new()); let (input, set_input) = signal(String::new()); socket.subscribe(ChatKey { room_id }, move |msg: &ChatMsg| { set_messages.write().push(msg.clone()); }); let send = move |_| { let msg = input.get_untracked(); if !msg.trim().is_empty() { socket.send(ChatKey { room_id }, ChatMsg { id: Uuid::new_v4(), message: msg, author: "User".to_string(), }); set_input.set(String::new()); } }; view! {
    {m.author}": "{m.message} } />
} } ``` -------------------------------- ### Initialize Socket Context with Query Parameters Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Use `provide_socket_context_with_query` to initialize the socket context with custom query parameters. This is useful for passing authentication tokens or user identifiers to the server upon connection. ```rust use leptos::prelude::*; use leptos_axum_socket::provide_socket_context_with_query; #[component] pub fn App() -> impl IntoView { let user_id = "user-12345"; // Pass query parameters to the WebSocket connection // Server will receive: /socket-msg?user_id=user-12345 provide_socket_context_with_query(&[("user_id", user_id)]); view! {
} } ``` -------------------------------- ### Initialize ServerSocket and Axum App Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Include ServerSocket in your Axum application state and register the WebSocket route. Ensure the `ssr` feature is enabled for server-side rendering. ```rust use leptos::prelude::*; use leptos_axum_socket::ServerSocket; use axum::extract::FromRef; #[cfg(feature = "ssr")] #[derive(Clone, FromRef)] pub struct AppState { pub leptos_options: LeptosOptions, pub server_socket: ServerSocket, } #[cfg(feature = "ssr")] #[tokio::main] async fn main() { use axum::Router; use leptos_axum::{generate_route_list, LeptosRoutes}; use leptos_axum_socket::SocketRoute; let conf = get_configuration(None).unwrap(); let routes = generate_route_list(App); // Create the server socket let state = AppState { leptos_options: conf.leptos_options.clone(), server_socket: ServerSocket::new(), }; let app = Router::new() .leptos_routes(&state, routes, { let opts = state.leptos_options.clone(); move || shell(opts.clone()) }) .socket_route(connect_to_websocket) // Register WebSocket route .with_state(state); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app.into_make_service()).await.unwrap(); } ``` -------------------------------- ### Initialize Socket Context in Root Component Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Call `provide_socket_context` in your root Leptos component to initialize the WebSocket connection context. This must be done before any component attempts to send or subscribe to messages. ```rust use leptos::prelude::*; use leptos_axum_socket::provide_socket_context; #[component] pub fn App() -> impl IntoView { // Initialize the socket context for all child components provide_socket_context(); view! {
} } ``` -------------------------------- ### provide_socket_context Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Initializes the WebSocket connection context in the root Leptos component. This must be called before any component attempts to subscribe or send messages. ```APIDOC ## provide_socket_context ### Description Initializes the WebSocket connection context in your root Leptos component. This must be called before any component attempts to subscribe or send messages. ### Usage ```rust use leptos::prelude::*; use leptos_axum_socket::provide_socket_context; #[component] pub fn App() -> impl IntoView { provide_socket_context(); view! {
...
} } ``` -------------------------------- ### provide_socket_context_with_query Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Initializes the socket context with custom query parameters passed to the WebSocket connection, useful for authentication or user identification. ```APIDOC ## provide_socket_context_with_query ### Description Initializes the socket context with custom query parameters passed to the WebSocket connection. This is useful for authentication or identifying users on the server side. ### Parameters - **query_params** (&[(&str, &str)]) - Required - A slice of key-value pairs to be appended to the WebSocket connection URL. ### Usage ```rust provide_socket_context_with_query(&[("user_id", "user-12345")]); ``` -------------------------------- ### Implement WebSocket Connection Handler Source: https://github.com/synphonyte/leptos-axum-socket/blob/main/README.md Implement the `connect_to_websocket` handler for Axum. This function upgrades the incoming WebSocket request and passes the `ServerSocket` and optional context to `upgrade_websocket`. ```rust #[cfg(feature = "ssr")] pub async fn connect_to_websocket( ws: WebSocketUpgrade, State(socket): State, ) -> Response { // You could do authentication here // Provide extra context like the user's ID for example that is passed to the permission filters let ctx = (); upgrade_websocket(ws, socket, ctx) } ``` -------------------------------- ### Provide Socket Context in Root Leptos Component Source: https://github.com/synphonyte/leptos-axum-socket/blob/main/README.md In your root Leptos component (e.g., `App`), call `provide_socket_context()` to make the socket available throughout your Leptos application. This must be called before `expect_socket_context` is used. ```rust #[component] pub fn App() -> impl IntoView { provide_socket_context(); view! { "..." } } ``` -------------------------------- ### Define Axum App State with ServerSocket Source: https://github.com/synphonyte/leptos-axum-socket/blob/main/README.md Define your Axum application state in `lib.rs`, including the `ServerSocket` which is required for Leptos Axum Socket to function. The `AppState` struct must derive `axum::extract::FromRef`. ```rust use leptos::prelude::*; #[cfg(feature = "ssr")] #[derive(Clone, axum::extract::FromRef)] pub struct AppState { // This is required for Leptos Axum Socket to work pub socket: leptos_axum_socket::ServerSocket, // this is required for Leptos to work with axum pub leptos_options: LeptosOptions, } ``` -------------------------------- ### WebSocket Upgrade Handler Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Details on how to handle incoming WebSocket upgrade requests using `upgrade_websocket`, including custom context for authentication. ```APIDOC ## upgrade_websocket The `upgrade_websocket` function handles the WebSocket upgrade request in your Axum handler. It accepts a context parameter that can be used for authentication and authorization in filters and mappers. ### Handler Function Example ```rust use axum::{ extract::{Query, State, WebSocketUpgrade}, response::Response, }; use leptos_axum_socket::{ServerSocket, handlers::upgrade_websocket}; use serde::Deserialize; use uuid::Uuid; #[derive(Deserialize)] pub struct WebSocketQuery { user_id: Uuid, } // Custom context passed to filters and mappers #[derive(Clone)] pub struct SocketContext { user_id: Uuid, is_admin: bool, } pub async fn connect_to_websocket( ws: WebSocketUpgrade, State(socket): State, Query(query): Query, ) -> Response { // Perform authentication here if needed let ctx = SocketContext { user_id: query.user_id, is_admin: false, // Check database, etc. }; // Upgrade the connection with context upgrade_websocket(ws, socket, ctx) } ``` ``` -------------------------------- ### Handle WebSocket Upgrade Request Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt This handler upgrades an incoming WebSocket connection. It extracts query parameters for context and uses `upgrade_websocket` to establish the connection. Ensure `SocketContext` is defined and populated. ```rust use axum::{ extract::{Query, State, WebSocketUpgrade}, response::Response, }; use leptos_axum_socket::{ServerSocket, handlers::upgrade_websocket}; use serde::Deserialize; use uuid::Uuid; #[derive(Deserialize)] pub struct WebSocketQuery { user_id: Uuid, } // Custom context passed to filters and mappers #[derive(Clone)] pub struct SocketContext { user_id: Uuid, is_admin: bool, } pub async fn connect_to_websocket( ws: WebSocketUpgrade, State(socket): State, Query(query): Query, ) -> Response { // Perform authentication here if needed let ctx = SocketContext { user_id: query.user_id, is_admin: false, // Check database, etc. }; // Upgrade the connection with context upgrade_websocket(ws, socket, ctx) } ``` -------------------------------- ### ServerSocket::add_subscribe_filter Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Details on how to add asynchronous filters to control client subscription access to specific keys. ```APIDOC ## ServerSocketInner::add_subscribe_filter The `add_subscribe_filter` method adds an async filter that controls whether a client can subscribe to a specific key. Multiple filters can be added, and all must return `true` for the subscription to be allowed. ### Filter Configuration Example ```rust use leptos_axum_socket::ServerSocket use serde::{Deserialize, Serialize} use uuid::Uuid; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct PrivateRoomKey { room_id: Uuid } #[derive(Clone)] struct SocketContext { user_id: Uuid, allowed_rooms: Vec, } #[cfg(feature = "ssr")] async fn setup_filters(server_socket: &ServerSocket) { let mut socket = server_socket.lock().await; // Add subscription filter - only allow if user has access to the room socket.add_subscribe_filter( async |key: PrivateRoomKey, ctx: SocketContext| { // Return true to allow subscription, false to deny ctx.allowed_rooms.contains(&key.room_id) } ); } ``` ``` -------------------------------- ### expect_socket_context Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Retrieves the socket context for use in components. Panics if the context was not provided. ```APIDOC ## expect_socket_context ### Description The expect_socket_context function retrieves the socket context for use in components. It panics if the context was not provided, making it suitable when you're certain the context exists. ### Usage ```rust let socket = expect_socket_context(); ``` -------------------------------- ### Define Key and Message Types for Socket Communication Source: https://github.com/synphonyte/leptos-axum-socket/blob/main/README.md Define serializable key and message types for your socket communication. Ensure your message type implements the `SocketMsg` trait. ```rust #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] pub struct MyKey { pub bla: String, } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct MyMsg { pub awesome_msg: String, } // Implement the SocketMsg trait for MyMsg to link the key and message types impl SocketMsg for MyMsg { type Key = MyKey; #[cfg(feature = "ssr")] type AppState = AppState; } ``` -------------------------------- ### Add Subscription Filter to ServerSocket Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Use `add_subscribe_filter` to define asynchronous filters that control client subscription access. All filters must return `true` for a subscription to be permitted. The filter receives the key and the `SocketContext`. ```rust use leptos_axum_socket::ServerSocket; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct PrivateRoomKey { room_id: Uuid } #[derive(Clone)] struct SocketContext { user_id: Uuid, allowed_rooms: Vec, } #[cfg(feature = "ssr")] async fn setup_filters(server_socket: &ServerSocket) { let mut socket = server_socket.lock().await; // Add subscription filter - only allow if user has access to the room socket.add_subscribe_filter( async |key: PrivateRoomKey, ctx: SocketContext| { // Return true to allow subscription, false to deny ctx.allowed_rooms.contains(&key.room_id) } ); } ``` -------------------------------- ### Broadcast Message from Server Function Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Broadcasts a message from a server function to all subscribers of the specified key. This is the preferred way to send messages from `#[server]` functions. ```rust use leptos::prelude::*; use leptos_axum_socket::SocketMsg; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct NotificationKey { user_id: Uuid } #[derive(Clone, Serialize, Deserialize, Debug)] struct NotificationMsg { title: String, body: String } impl SocketMsg for NotificationMsg { type Key = NotificationKey; #[cfg(feature = "ssr")] type AppState = crate::AppState; } #[server] pub async fn create_order(user_id: Uuid, items: Vec) -> Result<(), ServerFnError> { // Process the order... // Notify the user via WebSocket leptos_axum_socket::send( &NotificationKey { user_id }, &NotificationMsg { title: "Order Confirmed".to_string(), body: format!("Your order with {} items has been placed!", items.len()), }, ).await; Ok(()) } ``` -------------------------------- ### Retrieve Socket Context in a Component Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Use `expect_socket_context` to retrieve the socket context within a Leptos component. This function will panic if the context has not been provided, so ensure it's called only after `provide_socket_context` or `provide_socket_context_with_query`. ```rust use leptos::prelude::*; use leptos_axum_socket::expect_socket_context; #[component] pub fn MessageSender() -> impl IntoView { let socket = expect_socket_context(); view! { } } ``` -------------------------------- ### SocketRoute Trait Extension Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Explains how the `SocketRoute` trait simplifies registering WebSocket endpoints within an Axum router. ```APIDOC ## SocketRoute Trait The `SocketRoute` trait extends Axum's `Router` with a `socket_route` method to register the WebSocket endpoint. ### Router Configuration ```rust use axum::Router use leptos_axum_socket::SocketRoute #[cfg(feature = "ssr")] fn build_router(state: AppState) -> Router { Router::new() // ... other routes ... .socket_route(connect_to_websocket) // Adds GET /socket-msg .with_state(state) } ``` ``` -------------------------------- ### Send Message from Axum Server Function Source: https://github.com/synphonyte/leptos-axum-socket/blob/main/README.md Send messages from the server using the `leptos_axum_socket::send` function within an Axum server function. This requires the `ssr` feature to be enabled. ```rust #[server] pub async fn my_server_function() -> Result<(), ServerFnError> { // Send from the server leptos_axum_socket::send( &MyKey { bla: "bla".to_string(), }, &MyMsg { awesome_msg: "Hello, world!".to_string(), }, ).await; Ok(()) } ``` -------------------------------- ### SocketContext::send Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Broadcasts a message to all subscribers of the specified key. Messages are sent through the WebSocket to the server, which then distributes them to all connected clients subscribed to that key. ```APIDOC ## SocketContext::send ### Description Broadcasts a message to all subscribers of the specified key. Messages are sent through the WebSocket to the server, which then distributes them to all connected clients subscribed to that key. ### Parameters - **key** (ChatKey) - Required - The key to broadcast the message to. - **message** (ChatMsg) - Required - The message payload to send. ``` -------------------------------- ### Subscribe to Socket Messages Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Registers a handler for incoming messages matching a specific key. Subscriptions are automatically cleaned up when the component unmounts. ```rust use leptos::prelude::*; use leptos_axum_socket::{expect_socket_context, SocketMsg}; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct ChatKey { room_id: Uuid } #[derive(Clone, Serialize, Deserialize, Debug)] struct ChatMsg { id: Uuid, message: String, author: String } impl SocketMsg for ChatMsg { type Key = ChatKey; #[cfg(feature = "ssr")] type AppState = crate::AppState; } #[component] pub fn ChatRoom(room_id: Uuid) -> impl IntoView { let socket = expect_socket_context(); let (messages, set_messages) = signal(Vec::::new()); // Subscribe to messages for this specific room socket.subscribe( ChatKey { room_id }, move |msg: &ChatMsg| { // Handler is called for each incoming message set_messages.write().push(msg.clone()); }, ); view! {
    {msg.author}": "{msg.message} } />
} } ``` -------------------------------- ### Send Socket Messages Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Broadcasts a message to all subscribers of a specific key via the WebSocket. ```rust use leptos::prelude::*; use leptos::ev::SubmitEvent; use leptos_axum_socket::{expect_socket_context, SocketMsg}; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct ChatKey { room_id: Uuid } #[derive(Clone, Serialize, Deserialize, Debug)] struct ChatMsg { id: Uuid, message: String, author: String } impl SocketMsg for ChatMsg { type Key = ChatKey; #[cfg(feature = "ssr")] type AppState = crate::AppState; } #[component] pub fn ChatInput(room_id: Uuid, username: String) -> impl IntoView { let socket = expect_socket_context(); let (input, set_input) = signal(String::new()); let on_submit = move |ev: SubmitEvent| { ev.prevent_default(); let message = input.get_untracked(); if !message.trim().is_empty() { // Broadcast message to all subscribers of this room socket.send( ChatKey { room_id }, ChatMsg { id: Uuid::new_v4(), message, author: username.clone(), }, ); set_input.set(String::new()); } }; view! {
} } ``` -------------------------------- ### Broadcast Message from Axum Handler Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Broadcasts messages from within Axum handlers (as opposed to Leptos server functions). Access it by locking the `ServerSocket`. ```rust use axum::extract::State; use leptos_axum_socket::{ServerSocket, SocketMsg}; use serde::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct SystemKey { channel: String } #[derive(Clone, Serialize, Deserialize, Debug)] struct SystemMsg { event: String, data: String } impl SocketMsg for SystemMsg { type Key = SystemKey; #[cfg(feature = "ssr")] type AppState = crate::AppState; } pub async fn broadcast_system_message( State(socket): State, ) { // Lock the socket to access ServerSocketInner socket.lock().await.send( &SystemKey { channel: "system".to_string() }, &SystemMsg { event: "maintenance".to_string(), data: "Server will restart in 5 minutes".to_string(), }, ); } ``` -------------------------------- ### leptos_axum_socket::send Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Broadcasts a message from a server function to all subscribers of the specified key. ```APIDOC ## leptos_axum_socket::send ### Description Broadcasts a message from a server function to all subscribers of the specified key. This is the preferred way to send messages from `#[server]` functions. ### Parameters - **key** (SocketMsg::Key) - Required - The key identifying the subscribers. - **msg** (SocketMsg) - Required - The message to broadcast. ``` -------------------------------- ### Reconnect WebSocket Connection Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Disconnects and re-establishes the WebSocket connection, useful for resetting server-side context after authentication changes. ```rust use leptos::prelude::*; use leptos_axum_socket::expect_socket_context; #[component] pub fn LogoutButton() -> impl IntoView { let socket = expect_socket_context(); let on_logout = move |_| { // Perform logout logic... // Reconnect WebSocket to update server-side context // This re-establishes the connection and re-subscribes to all channels socket.reconnect(); }; view! { } } ``` -------------------------------- ### SocketContext::unsubscribe Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Stops listening for messages with the specified key. While subscriptions are automatically cleaned up on component unmount, this can be used for manual control over subscriptions. ```APIDOC ## SocketContext::unsubscribe ### Description Stops listening for messages with the specified key. While subscriptions are automatically cleaned up on component unmount, this can be used for manual control over subscriptions. ### Parameters - **key** (NotificationKey) - Required - The key to unsubscribe from. ``` -------------------------------- ### ServerSocketInner::send (Axum Handler) Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Broadcasts messages from within Axum handlers by locking the ServerSocket. ```APIDOC ## ServerSocketInner::send ### Description Broadcasts messages from within Axum handlers. Access it by locking the `ServerSocket`. ### Parameters - **key** (SocketMsg::Key) - Required - The key identifying the subscribers. - **msg** (SocketMsg) - Required - The message to broadcast. ``` -------------------------------- ### SocketContext::reconnect Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Disconnects and re-establishes the WebSocket connection. This is useful when user authentication state changes and you need to reset the server-side context. ```APIDOC ## SocketContext::reconnect ### Description Disconnects and re-establishes the WebSocket connection. This is useful when user authentication state changes and you need to reset the server-side context. ``` -------------------------------- ### Send targeted messages from Axum handler Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Uses the send_to_self method to deliver messages to a specific client identified by request headers. ```rust use axum::{ extract::State, http::HeaderMap, }; use leptos_axum_socket::{ServerSocket, SocketMsg}; use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct PrivateKey { user_id: String } #[derive(Clone, Serialize, Deserialize, Debug)] struct PrivateMsg { content: String } impl SocketMsg for PrivateMsg { type Key = PrivateKey; #[cfg(feature = "ssr")] type AppState = crate::AppState; } pub async fn send_private_response( State(socket): State, headers: HeaderMap, ) { // Send only to the requesting client using their cookie socket.lock().await.send_to_self( &PrivateKey { user_id: "current".to_string() }, &PrivateMsg { content: "Private response".to_string() }, &headers, ).await; } ``` -------------------------------- ### Define SocketMsg Trait and Message Types Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Implement the `SocketMsg` trait to link message types to their keys and application state. This is crucial for type-safe pub/sub routing. Ensure message types are serializable and deserializable. ```rust use leptos_axum_socket::{ServerSocket, SocketMsg}; use serde::{Deserialize, Serialize}; use axum::extract::FromRef; // Define application state (SSR only) #[cfg(feature = "ssr")] #[derive(Clone, FromRef)] pub struct AppState { pub socket: ServerSocket, pub leptos_options: leptos::prelude::LeptosOptions, } // Define the key type - used for routing messages to subscribers #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] pub struct ChatKey { pub room_id: String, } // Define the message type - the actual payload #[derive(Clone, Serialize, Deserialize, Debug)] pub struct ChatMsg { pub id: uuid::Uuid, pub message: String, pub author: String, } // Link the message to its key type impl SocketMsg for ChatMsg { type Key = ChatKey; #[cfg(feature = "ssr")] type AppState = AppState; } ``` -------------------------------- ### SocketContext::subscribe Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Registers a handler function that is called whenever a message matching the specified key is received. The subscription is automatically cleaned up when the component is unmounted. ```APIDOC ## SocketContext::subscribe ### Description Registers a handler function that is called whenever a message matching the specified key is received. The subscription is automatically cleaned up when the component is unmounted. ### Parameters - **key** (ChatKey) - Required - The key to subscribe to. - **handler** (Fn) - Required - The callback function executed when a message is received. ``` -------------------------------- ### Send Message to Self from Server Function Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Sends a message from a server function only to the specific WebSocket connection that initiated the server function call. This is useful for sending private responses or acknowledgments. ```rust use leptos::prelude::*; use leptos_axum_socket::SocketMsg; use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct ToastKey { session_id: String } #[derive(Clone, Serialize, Deserialize, Debug)] struct ToastMsg { message: String, severity: String } impl SocketMsg for ToastMsg { type Key = ToastKey; #[cfg(feature = "ssr")] type AppState = crate::AppState; } #[server] pub async fn save_settings(theme: String) -> Result<(), ServerFnError> { // Save settings to database... // Send confirmation toast only to the caller leptos_axum_socket::send_to_self( &ToastKey { session_id: "current".to_string() }, &ToastMsg { message: "Settings saved successfully!".to_string(), severity: "success".to_string(), }, ).await; Ok(()) } ``` -------------------------------- ### Unsubscribe from Socket Messages Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Manually stops listening for messages associated with a specific key. ```rust use leptos::prelude::*; use leptos_axum_socket::expect_socket_context; use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Debug)] struct NotificationKey { user_id: String } #[component] pub fn NotificationToggle(user_id: String) -> impl IntoView { let socket = expect_socket_context(); let (enabled, set_enabled) = signal(true); let toggle = move |_| { if enabled.get() { // Manually unsubscribe from notifications socket.unsubscribe(NotificationKey { user_id: user_id.clone() }); } set_enabled.set(!enabled.get()); }; view! { } } ``` -------------------------------- ### ServerSocketInner::add_send_mapper Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Adds a mapper function to transform or filter outgoing messages before they are broadcasted. ```APIDOC ## ServerSocketInner::add_send_mapper ### Description Adds a mapper that can transform or filter outgoing messages. Return `Some(msg)` to allow the message (optionally modified), or `None` to block it. ### Parameters - **mapper** (closure) - Required - A function taking (key, msg, context) and returning Option. ``` -------------------------------- ### leptos_axum_socket::send_to_self Source: https://context7.com/synphonyte/leptos-axum-socket/llms.txt Sends a message from a server function only to the specific WebSocket connection that initiated the call. ```APIDOC ## leptos_axum_socket::send_to_self ### Description Sends a message from a server function only to the specific WebSocket connection that initiated the server function call. Useful for private responses or acknowledgments. ### Parameters - **key** (SocketMsg::Key) - Required - The key identifying the connection. - **msg** (SocketMsg) - Required - The message to send. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.