### Reactive Display Media Stream (Rust) Source: https://leptos-use.rs/print Hook for reactive access to `mediaDevices.getDisplayMedia()`. It provides a stream of the screen capture and functions to start and stop the capture. The `start` and `stop` functions are sendwrapped and must be called from the same thread. On the server, stream related calls are ignored. ```rust use leptos::prelude::*; use leptos::logging::{log, error}; use leptos_use::{use_display_media, UseDisplayMediaReturn}; #[component] fn Demo() -> impl IntoView { let video_ref = NodeRef::::new(); let UseDisplayMediaReturn { stream, start, .. } = use_display_media(); start(); Effect::new(move |_| video_ref.get().map(|v| { match stream.get() { Some(Ok(s)) => v.set_src_object(Some(&s)), Some(Err(e)) => error!("Failed to get media stream: {:?}", e), None => log!("No stream yet"), } }) ); view! { } } ``` -------------------------------- ### Install Leptos-Use with Cargo Source: https://leptos-use.rs/get_started This command adds the leptos-use crate to your project's dependencies using Cargo, Rust's package manager. Ensure you have Rust and Cargo installed. ```bash cargo add leptos-use ``` -------------------------------- ### Example Browser Permission States Source: https://leptos-use.rs/browser/use_permission Illustrates various permission states for different browser features. This provides a quick overview of how permissions might be reported, showing states like 'granted' or 'prompt'. ```text accelerometer: granted accessibility_events: prompt ambient_light_sensor: prompt background_sync: granted camera: prompt clipboard_read: prompt clipboard_write: granted gyroscope: granted magnetometer: granted microphone: prompt notifications: prompt payment_handler: granted persistent_storage: granted push: prompt speaker: prompt ``` -------------------------------- ### Reactive EventSource with use_event_source and JsonSerdeCodec Source: https://leptos-use.rs/print Example of setting up a reactive EventSource connection to receive JSON-encoded messages. It utilizes `JsonSerdeCodec` for deserialization and demonstrates how to access connection state, received data, and control the connection. ```rust use leptos::prelude::*; use leptos_use::{use_event_source, UseEventSourceReturn}; use codee::string::JsonSerdeCodec; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, PartialEq)] pub struct EventSourceData { pub message: String, pub priority: u8, } #[component] fn Demo() -> impl IntoView { let UseEventSourceReturn { ready_state, data, error, close, .. } = use_event_source::("https://event-source-url"); view! { } // The view content is omitted in the original example } ``` -------------------------------- ### Use Cookie with Options in Leptos Source: https://leptos-use.rs/print Illustrates the use of `use_cookie_with_options` in Leptos to manage cookies with advanced settings. This example demonstrates setting a cookie with a specific `max_age` and `SameSite` attribute, providing fine-grained control over cookie behavior. ```rust use cookie::SameSite; use leptos::prelude::*; use leptos_use::{use_cookie_with_options, UseCookieOptions}; use codee::string::FromToStringCodec; #[component] fn Demo() -> impl IntoView { let (cookie, set_cookie) = use_cookie_with_options::( "user_info", UseCookieOptions::default() .max_age(3600_000) // one hour .same_site(SameSite::Lax) ); view! {} // Placeholder for actual view content } ``` -------------------------------- ### Use Websocket with MsgpackSerdeCodec for Binary Data Source: https://leptos-use.rs/print Implements a WebSocket connection for sending and receiving binary data serialized with Msgpack, using the MsgpackSerdeCodec. This requires enabling the `msgpack_serde` feature flag. The example defines a struct for data exchange and uses it with the `send` function. ```rust use leptos::*; use codee::binary::MsgpackSerdeCodec; use leptos_use::{use_websocket, UseWebSocketReturn}; use serde::{Deserialize, Serialize}; #[component] fn Demo() -> impl IntoView { #[derive(Serialize, Deserialize)] struct SomeData { name: String, count: i32, } let UseWebSocketReturn { message, send, .. } = use_websocket::("wss://some.websocket.server/"); let send_data = move || { send(&SomeData { name: "John Doe".to_string(), count: 42, }); }; view! {} } ``` -------------------------------- ### Use Window Size Hook for Leptos Source: https://leptos-use.rs/print Provides reactive window width and height. Defaults to INFINITY on the server. Requires the 'use_window_size' feature. ```rust use leptos::*; use leptos_use::{use_window_size, UseWindowSizeReturn}; #[component] fn Demo() -> impl IntoView { let UseWindowSizeReturn { width, height } = use_window_size(); view! { } } ``` -------------------------------- ### Use Generic Storage with Base64 and ProstCodec Source: https://leptos-use.rs/storage/use_storage Binds a string to either local or session storage using `use_storage`. This example uses `SessionStorage` and `Base64` encoding with `ProstCodec` for binary data serialization. ```rust use leptos::prelude::*; use leptos_use::storage::{StorageType, use_storage}; use codee::string::Base64; use codee::binary::ProstCodec; #[component] pub fn Demo() -> impl IntoView { let (id, set_id, _) = use_storage::>( StorageType::Session, "my-id", ); view! {} } ``` -------------------------------- ### Manage Cookie with Default Options in Leptos Source: https://leptos-use.rs/print Provides an example of using the `use_cookie` hook in Leptos for basic cookie management. This function initializes a cookie with a random value if it doesn't exist and allows updating and resetting its value. It utilizes a codec for encoding/decoding values. ```rust use leptos::prelude::*; use leptos_use::use_cookie; use codee::string::FromToStringCodec; use rand::random; #[component] fn Demo() -> impl IntoView { let (counter, set_counter) = use_cookie::("counter"); let reset = move || set_counter.set(Some(random())); if counter.get().is_none() { reset(); } let increase = move || { set_counter.set(counter.get().map(|c| c + 1)); }; view! {

Counter: {move || counter.get().map(|c| c.to_string()).unwrap_or("—".to_string())}

} } ``` -------------------------------- ### Use Websocket with Msgpack Codec in Leptos Source: https://leptos-use.rs/network/use_websocket Illustrates using `use_websocket` with `MsgpackSerdeCodec` for binary message encoding and decoding. This example requires the `msgpack_serde` feature flag to be enabled. It defines a `SomeData` struct for serialization and deserialization. Dependencies include `leptos`, `codee::binary::MsgpackSerdeCodec`, `leptos_use`, and `serde`. ```rust use leptos::*; use codee::binary::MsgpackSerdeCodec; use leptos_use::{use_websocket, UseWebSocketReturn}; use serde::{Deserialize, Serialize}; #[component] fn Demo() -> impl IntoView { #[derive(Serialize, Deserialize)] struct SomeData { name: String, count: i32, } let UseWebSocketReturn { message, send, .. } = use_websocket::("wss://some.websocket.server/"); let send_data = move || { send(&SomeData { name: "John Doe".to_string(), count: 42, }); }; view! {} // Placeholder for actual view implementation } ``` -------------------------------- ### Get Reactive Window Size with Leptos use_window_size Source: https://leptos-use.rs/elements/use_window_size This Rust code snippet demonstrates how to use the `use_window_size` hook from the `leptos_use` crate to get reactive window width and height. It requires the `use_window_size` feature to be enabled. On the server, dimensions default to infinity. ```rust use leptos::* use leptos_use::{use_window_size, UseWindowSizeReturn}; #[component] fn Demo() -> impl IntoView { let UseWindowSizeReturn { width, height } = use_window_size(); view! {

{width}x{height}

} } ``` -------------------------------- ### Synchronize Signals with Custom Assigns Source: https://leptos-use.rs/print This example demonstrates synchronizing signals with custom assignment logic using `SyncSignalOptions::with_assigns`. This is useful when direct transformation is not possible or desired, allowing explicit control over how values are copied or assigned between signals. This requires the `sync_signal` feature. ```rust use leptos::prelude::*; use leptos_use::{sync_signal_with_options, SyncSignalOptions}; #[derive(Clone)] pub struct Foo { bar: i32, } #[component] fn Demo() -> impl IntoView { let (a, set_a) = signal(Foo { bar: 10 }); let (b, set_b) = signal(2); let stop = sync_signal_with_options( (a, set_a), (b, set_b), SyncSignalOptions::with_assigns( |b: &mut i32, a: &Foo| *b = a.bar, |a: &mut Foo, b: &i32| a.bar = *b, ), ); view! { } } ``` -------------------------------- ### Watch Signal with Options (Immediate Execution) (Rust) Source: https://leptos-use.rs/watch/whenever Provides advanced control over the 'whenever' watcher using 'WatchOptions'. This example demonstrates enabling immediate execution of the callback. Note SSR limitations regarding throttling/debouncing. Requires the 'whenever' feature. ```rust use leptos::prelude::*; use leptos::logging::log; use leptos_use::{WatchOptions, whenever_with_options}; pub fn Demo() -> impl IntoView { let (counter, set_counter) = signal(0); whenever_with_options( move || counter.get() == 7, |_, _, _| log!("counter is 7 now!"), WatchOptions::default().immediate(true), ); view! { } } ``` -------------------------------- ### Get Element Size with Various Input Types Source: https://leptos-use.rs/print Demonstrates the flexibility of `use_element_size` by accepting various input types for the target element, including `Option`, `web_sys::Element`, CSS selectors as `&str`, Leptos `HtmlElement`, and signals. ```rust use_element_size(window().body()); // Option use_element_size(window().body().unwrap()); // web_sys::Element use_element_size("div > p.some-class"); // &str or String intepreted as CSS selector pub fn some_directive(el: HtmlElement) { use_element_size(el); // leptos::html::HtmlElement } // Signal let (str_signal, set_str_signal) = signal("div > p.some-class"); use_element_size(str_signal); // Signal let (el_signal, set_el_signal) = signal(document().query_selector("div > p.some-class").unwrap()); use_element_size(el_signal); ``` -------------------------------- ### use_event_source_with_options with Named Events Source: https://leptos-use.rs/print Shows how to configure `use_event_source_with_options` to listen for specific named events ('notice', 'update') from the server-sent events stream. It uses `FromToStringCodec` for simple string data. ```rust use leptos::prelude::*; use leptos_use::{use_event_source_with_options, UseEventSourceReturn, UseEventSourceOptions}; use codee::string::FromToStringCodec; #[component] fn Demo() -> impl IntoView { let UseEventSourceReturn { ready_state, data, error, close, .. } = use_event_source_with_options::( "https://event-source-url", UseEventSourceOptions::default() .named_events(["notice".to_string(), "update".to_string()]) ); view! { } // The view content is omitted in the original example } ``` -------------------------------- ### SSR Feature Configuration for Leptos Use (TOML) Source: https://leptos-use.rs/print Shows how to correctly configure the `ssr` feature for leptos-use in Cargo.toml to work with server-side rendering. ```toml [dependencies] leptos-use = "0.10" # do NOT enable the "ssr" feature here ... [features] hydrate = [ "leptos/hydrate", ... ] ssr = [ ... "leptos/ssr", ... "leptos-use/ssr" # <== add this ] ... ``` -------------------------------- ### Configuring Reconnection with use_event_source_with_options Source: https://leptos-use.rs/print Demonstrates advanced configuration for `use_event_source_with_options`, specifically setting reconnection limits and intervals. This allows for robust handling of network interruptions by automatically attempting to re-establish the connection. ```rust use leptos::prelude::*; use leptos_use::{use_event_source_with_options, UseEventSourceReturn, UseEventSourceOptions, ReconnectLimit}; use codee::string::FromToStringCodec; #[component] fn Demo() -> impl IntoView { let UseEventSourceReturn { ready_state, data, error, close, .. } = use_event_source_with_options::( "https://event-source-url", UseEventSourceOptions::default() .reconnect_limit(ReconnectLimit::Limited(5)) // at most 5 attempts .reconnect_interval(2000) // wait for 2 seconds between attempts ); view! { } // The view content is omitted in the original example } ``` -------------------------------- ### Use Websocket with Heartbeat Option in Leptos Source: https://leptos-use.rs/network/use_websocket Shows how to configure heartbeats for a WebSocket connection using `use_websocket_with_options`. This example defines a custom `Heartbeat` struct and uses `FromToStringCodec` for heartbeats, sending them every 10 seconds. Dependencies include `leptos`, `codee::string::FromToStringCodec`, `leptos_use`, and `serde`. ```rust use leptos::*; use codee::string::FromToStringCodec; use leptos_use::{use_websocket_with_options, UseWebSocketOptions, UseWebSocketReturn}; use serde::{Deserialize, Serialize}; #[component] fn Demo() -> impl IntoView { #[derive(Default)] struct Heartbeat; // Simple example for usage with `FromToStringCodec` impl std::fmt::Display for Heartbeat { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "") } } let UseWebSocketReturn { send, message, .. } = use_websocket_with_options::( "wss://echo.websocket.events/", UseWebSocketOptions::default() // Enable heartbeats every 10 seconds. In this case we use the same codec as for the // other messages. But this is not necessary. .heartbeat::(10_000), ); view! {} // Placeholder for actual view implementation } ``` -------------------------------- ### Conditional Rendering with Session Storage Flag Source: https://leptos-use.rs/storage/use_storage Demonstrates using a boolean flag from session storage to control conditional rendering. This example might cause hydration warnings if used without special handling due to server-side rendering differences. ```rust use leptos::prelude::*; use leptos_use::storage::use_session_storage; use codee::string::FromToStringCodec; #[component] pub fn Example() -> impl IntoView { let (flag, set_flag, _) = use_session_storage::("my-flag"); view! {
Some conditional content
} } ``` -------------------------------- ### Use Display Media Hook in Leptos Source: https://leptos-use.rs/browser/use_display_media This Rust code snippet demonstrates how to use the `use_display_media` hook from the `leptos_use` crate to capture and display the user's screen stream. It initializes the stream, starts capturing, and updates a video element with the stream. Dependencies include `leptos` and `leptos_use`. The output is a video element displaying the screen stream. ```rust use leptos::prelude::*; use leptos::logging::{log, error}; use leptos_use::{use_display_media, UseDisplayMediaReturn}; #[component] fn Demo() -> impl IntoView { let video_ref = NodeRef::::new(); let UseDisplayMediaReturn { stream, start, .. } = use_display_media(); start(); Effect::new(move |_| video_ref.get().map(|v| { match stream.get() { Some(Ok(s)) => v.set_src_object(Some(&s)), Some(Err(e)) => error!("Failed to get media stream: {:?}", e), None => log!("No stream yet"), } }) ); view! { } } ``` -------------------------------- ### Use Cookie with Options (max_age, sameSite) - Leptos Source: https://leptos-use.rs/browser/use_cookie Shows how to use `use_cookie_with_options` to configure cookie attributes like `max_age` for expiration and `same_site` for security. This example sets the cookie to expire in one hour and use the 'Lax' SameSite policy. ```rust use cookie::SameSite; use leptos::prelude::*; use leptos_use::{use_cookie_with_options, UseCookieOptions}; use codee::string::FromToStringCodec; #[component] fn Demo() -> impl IntoView { let (cookie, set_cookie) = use_cookie_with_options::( "user_info", UseCookieOptions::default() .max_age(3600_000) // one hour .same_site(SameSite::Lax) ); view! {} // Placeholder for actual view content } ``` -------------------------------- ### Manage Browser Favicon Source: https://leptos-use.rs/print Provides a reactive way to manage the browser's favicon. It allows changing the favicon to a specified URL. This requires the `use_favicon` feature. ```rust use leptos::prelude::*; use leptos_use::use_favicon; #[component] fn Demo() -> impl IntoView { let (icon, set_icon) = use_favicon(); set_icon.set(Some("dark.png".to_string())); // change current icon view! { } } ``` -------------------------------- ### Use Event Listener on Element with NodeRef - Leptos Source: https://leptos-use.rs/browser/use_event_listener Shows how to use `use_event_listener` with a `NodeRef` to attach a click listener to a specific HTML element. The listener logs information about the click event and the target element. This example highlights dynamic element rendering based on a condition. ```rust use leptos::prelude::*; use leptos::ev::click; use leptos::logging::log; use leptos_use::use_event_listener; #[component] fn Demo() -> impl IntoView { let element = NodeRef::new(); use_event_listener(element, click, |evt| { log!("click from element {:?}", event_target::(&evt)); }); let (cond, set_cond) = signal(true); view! { "Condition false" } >
"Condition true"
} } ``` -------------------------------- ### Throttle Signal with Options in Leptos Source: https://leptos-use.rs/print This shows how to use `signal_throttled_with_options` and `signal_throttled_local_with_options` for throttled signals with customizable options. `ThrottleOptions` allow control over `leading` and `trailing` edge behavior. ```rust use leptos::prelude::*; use leptos_use::{signal_throttled_with_options, signal_throttled_local_with_options, ThrottleOptions}; use std::cell::RefCell; #[component] fn Demo() -> impl IntoView { let (input, set_input) = signal(""); let throttled: Signal<&'static str> = signal_throttled_with_options( input, 1000.0, ThrottleOptions::default().leading(false).trailing(true) ); let (input_local, set_input_local) = signal_local(RefCell::new(0)); let throttled_local: Signal, _> = signal_throttled_local_with_options( input_local, 1000.0, ThrottleOptions::default().leading(false).trailing(true) ); view! { } } ``` -------------------------------- ### Internal structure of use_element_size Source: https://leptos-use.rs/print Provides a glimpse into the internal signature of `use_element_size`, highlighting its acceptance of `Into>`. This explains why various input types are supported due to `From` trait implementations. ```rust pub fn use_element_size(el: Into>) -> UseElementSizeReturn {} ``` -------------------------------- ### Binary and String Codec Usage in Rust Source: https://leptos-use.rs/print Demonstrates how to use binary and string codecs, including wrapping binary codecs with Base64 for string representation and using OptionCodec for optional values. These codecs are part of the 'codee' crate. ```rust use leptos_use::codee::{Base64, OptionCodec, FromToStringCodec, WebpackSerdeCodec, ProstCodec}; // Using a binary codec wrapped in Base64 for string encoding let base64_prost_codec = Base64::::new(); // Using OptionCodec with a string codec for f64 let optional_f64_codec = OptionCodec::>::new(); // Example of encoding/decoding (implementation details omitted for brevity) // let encoded_data = base64_prost_codec.encode(&some_data)?; // let decoded_data: SomeType = base64_prost_codec.decode(&encoded_data)?; // let encoded_option = optional_f64_codec.encode(Some(3.14)); // let decoded_option: Option = optional_f64_codec.decode(&encoded_option); ``` -------------------------------- ### Get Element Size with use_element_size (NodeRef) Source: https://leptos-use.rs/print Shows how to use `use_element_size` to get the dimensions (width and height) of an HTML element in Leptos. It utilizes a `NodeRef` to associate the element with the hook. ```rust use leptos::{*, html::Div}; use leptos_use::{use_element_size, UseElementSizeReturn}; #[component] pub fn Component() -> impl IntoView { let el = NodeRef::
::new(); let UseElementSizeReturn { width, height } = use_element_size(el); view! {
} } ``` -------------------------------- ### Get Element Size with Leptos NodeRef Source: https://leptos-use.rs/element_parameters Demonstrates how to use the use_element_size function from leptos_use with a Leptos NodeRef to get the width and height of an element. Requires leptos and leptos_use crates. ```rust #![allow(unused)] fn main() { use leptos::{*, html::Div}; use leptos_use::{use_element_size, UseElementSizeReturn}; #[component] pub fn Component() -> impl IntoView { let el = NodeRef::
::new(); let UseElementSizeReturn { width, height } = use_element_size(el); view! {
} } } ``` -------------------------------- ### Use Mouse Tracking Utility in Leptos Component Source: https://leptos-use.rs/get_started Demonstrates how to import and use the `use_mouse` function from the `leptos-use` library within a Leptos component. This utility tracks the mouse coordinates (x, y) on the screen. It requires Leptos to be set up. ```rust use leptos::prelude::*; use leptos_use::{use_mouse, UseMouseReturn}; #[component] fn Demo() -> impl IntoView { let UseMouseReturn { x, y, .. } = use_mouse(); view! { cx, {x} " x " {y} } } ``` -------------------------------- ### Get Reactive Timestamp with use_timestamp Source: https://leptos-use.rs/animation/use_timestamp Demonstrates how to use the `use_timestamp` function to get a reactive current timestamp. This function is available when the `use_timestamp` feature is enabled. It returns a signal that updates automatically. ```rust use leptos::prelude::*; use leptos_use::use_timestamp; #[component] fn Demo() -> impl IntoView { let timestamp = use_timestamp(); view! { } } ``` -------------------------------- ### Get Reactive Mouse Position with Leptos `use_mouse` Hook Source: https://leptos-use.rs/print These snippets demonstrate how to use the `use_mouse` hook to obtain reactive mouse coordinates (`x`, `y`) and the `source_type`. The first example shows basic usage, while the second illustrates how to configure `use_mouse` using `use_mouse_with_options` to disable touch event tracking, ensuring that only mouse-related changes are detected. The `dragover` event is utilized for tracking mouse position during drag operations. ```rust use leptos::prelude::*; use leptos_use::{use_mouse, UseMouseReturn}; #[component] fn Demo() -> impl IntoView { let UseMouseReturn { x, y, source_type, .. } = use_mouse(); view! { } } ``` ```rust use leptos::prelude::*; use leptos_use::{use_mouse_with_options, UseMouseOptions, UseMouseReturn}; #[component] fn Demo() -> impl IntoView { let UseMouseReturn { x, y, .. } = use_mouse_with_options( UseMouseOptions::default().touch(false) ); view! { } } ``` -------------------------------- ### Provide WebsocketContext using use_websocket Hook Source: https://leptos-use.rs/print This Rust code demonstrates providing a `WebsocketContext` using the `use_websocket` hook from `leptos_use`. It initializes a WebSocket connection and then wraps the `send` function and `message` signal into the `WebsocketContext`, which is then provided to the Leptos application context. This approach uses dynamic dispatch for ergonomics. ```rust use leptos::prelude::*; use codee::string::FromToStringCodec; use leptos_use::{use_websocket, UseWebSocketReturn}; use std::sync::Arc; #[derive(Clone)] pub struct WebsocketContext { pub message: Signal>, send: Arc, } impl WebsocketContext { pub fn new(message: Signal>, send: Arc) -> Self { Self { message, send, } } } #[component] fn Demo() -> impl IntoView { let UseWebSocketReturn { message, send, .. // ignore other fields like open, close, etc. } = use_websocket::("ws:://some.websocket.io"); provide_context(WebsocketContext::new(message, Arc::new(send.clone()))); view! { } } ``` -------------------------------- ### Use Websocket with String Codec in Leptos Source: https://leptos-use.rs/network/use_websocket Demonstrates how to establish a WebSocket connection using the `use_websocket` function with `String` codec for both sending and receiving messages. It includes functionality to send messages, open/close the connection, and display the connection status and received messages. Dependencies include `leptos::prelude`, `codee::string::FromToStringCodec`, and `leptos_use`. ```rust use leptos::prelude::*; use codee::string::FromToStringCodec; use leptos_use::{use_websocket, UseWebSocketReturn}; use leptos_use::core::ConnectionReadyState; #[component] fn Demo() -> impl IntoView { let UseWebSocketReturn { ready_state, message, send, open, close, .. } = use_websocket::("wss://echo.websocket.events/"); let send_message = move |_| { send(&"Hello, world!".to_string()); }; let status = move || ready_state.get().to_string(); let connected = move || ready_state.get() == ConnectionReadyState::Open; let open_connection = move |_| { open(); }; let close_connection = move |_| { close(); }; view! {

"status: " {status}

"Receive message: " {move || format!("{:?}", message.get())}

} } ``` -------------------------------- ### Get Element Bounding Box Reactively - Leptos Source: https://leptos-use.rs/elements/use_element_bounding This snippet demonstrates how to use the use_element_bounding function in Leptos to get reactive x, y, top, right, bottom, left, width, and height values for an HTML element. It requires the 'use_element_bounding' feature to be enabled. ```rust use leptos::prelude::*; use leptos::html::Div; use leptos_use::{use_element_bounding, UseElementBoundingReturn}; #[component] fn Demo() -> impl IntoView { let el = NodeRef::
::new(); let UseElementBoundingReturn { x, y, top,right,bottom,left, width, height, .. } = use_element_bounding(el); view! {
} } ``` -------------------------------- ### SSR-Safe Window and Document Access with Leptos-Use Source: https://leptos-use.rs/server_side_rendering Illustrates how to use Leptos-Use helper functions like 'use_window()' and 'use_event_listener()' in an SSR-compatible manner. These functions safely return Option types, preventing errors when 'window' or 'document' are not available on the server. ```rust #![allow(unused)] fn main() { use leptos::prelude::*; use leptos::ev::keyup; use leptos_use::{use_event_listener, use_window}; use_event_listener(use_window(), keyup, | evt| { ... }); } ``` -------------------------------- ### Configure & Display Web Notifications (Leptos) Source: https://leptos-use.rs/print Demonstrates how to use `use_web_notification_with_options` from `leptos_use` to configure and display desktop notifications. It sets notification options like direction, language, renotify, and tag, then shows a notification with a title. This function is ignored on the server-side and requires the `use_web_notification` feature. ```Rust use leptos::prelude::*; use leptos_use::{use_web_notification_with_options, UseWebNotificationOptions, ShowOptions, UseWebNotificationReturn, NotificationDirection}; #[component] fn Demo() -> impl IntoView { let UseWebNotificationReturn { show, close, .. } = use_web_notification_with_options( UseWebNotificationOptions::default() .direction(NotificationDirection::Auto) .language("en") .renotify(true) .tag("test"), ); show(ShowOptions::default().title("Hello World from leptos-use")); view! { } } ``` -------------------------------- ### Get Microphone Permission State with Leptos-Use Source: https://leptos-use.rs/browser/use_permission Demonstrates how to use the use_permission function from the leptos_use crate to get the current state of microphone access. This function returns a reactive signal representing the permission state. Server-side, it defaults to Unknown. Requires the 'use_permission' feature. ```rust use leptos::prelude::*; use leptos_use::use_permission; #[component] fn Demo() -> impl IntoView { let microphone_access = use_permission("microphone"); view! { } } ``` -------------------------------- ### use_toggle: Reactive Boolean Switcher Source: https://leptos-use.rs/print Implements a reactive boolean switcher with utility functions to toggle, set, and get the boolean value. It requires the 'use_toggle' feature to be enabled. ```rust use leptos::* use leptos_use::{use_toggle, UseToggleReturn}; #[component] fn Demo() -> impl IntoView { let UseToggleReturn { toggle, value, set_value } = use_toggle(true); view! { } } ``` -------------------------------- ### Use Local and Session Storage with Custom Codecs in Leptos Source: https://leptos-use.rs/print Demonstrates the usage of `use_local_storage`, `use_session_storage`, and `use_storage` hooks in Leptos. It shows how to bind signals to browser storage, handling different data types (structs, bools, numbers) and serialization formats (JSON, string, Protobuf via Base64). ```rust __ use leptos::prelude::* use leptos_use::storage::{StorageType, use_local_storage, use_session_storage, use_storage}; use serde::{Deserialize, Serialize}; use codee::string::{FromToStringCodec, JsonSerdeCodec, Base64}; use codee::binary::ProstCodec; #[component] pub fn Demo() -> impl IntoView { // Binds a struct: let (state, set_state, _) = use_local_storage::("my-state"); // Binds a bool, stored as a string: let (flag, set_flag, remove_flag) = use_session_storage::("my-flag"); // Binds a number, stored as a string: let (count, set_count, _) = use_session_storage::("my-count"); // Binds a number, stored in JSON: let (count, set_count, _) = use_session_storage::("my-count-kept-in-js"); // Bind string with SessionStorage stored in ProtoBuf format: let (id, set_id, _) = use_storage::>( StorageType::Session, "my-id", ); view! { } } // Data stored in JSON must implement Serialize, Deserialize. // And you have to add the feature "serde" to your project's Cargo.toml #[derive(Serialize, Deserialize, Clone, PartialEq)] pub struct MyState { pub hello: String, pub greeting: String, } // Default can be used to implement initial or deleted values. // You can also use a signal via UseStorageOptions::default_value` impl Default for MyState { fn default() -> Self { Self { hello: "hi".to_string(), greeting: "Hello".to_string() } } } ``` -------------------------------- ### Use Timeout Fn Hook for Leptos Source: https://leptos-use.rs/print The `use_timeout_fn` hook in leptos_use acts as a wrapper for `setTimeout`, providing controls to manage the timer. It allows starting and stopping the timeout, and checking if it's pending. The returned `start` and `stop` closures are Send-wrapped and must be called from the same thread. On the server, the callback is never executed, and the returned functions are no-ops. ```rust use leptos::prelude::*; use leptos_use::{use_timeout_fn, UseTimeoutFnReturn}; #[component] fn Demo() -> impl IntoView { let UseTimeoutFnReturn { start, stop, is_pending, .. } = use_timeout_fn( |i: i32| { // do sth }, 3000.0 ); start(3); view! { } } ``` -------------------------------- ### Use Clipboard API (Rust/Leptos) Source: https://leptos-use.rs/print Provides reactive access to the system clipboard for cut, copy, and paste operations. It requires user permission and is gated by the Permissions API. On the server, 'text' is always None and 'copy' is a no-op. Requires the 'use_clipboard' feature. ```rust use leptos::prelude::*; use leptos_use::{use_clipboard, UseClipboardReturn}; #[component] fn Demo() -> impl IntoView { let UseClipboardReturn { is_supported, text, copied, copy } = use_clipboard(); view! { Your browser does not support Clipboard API

} >
} } ``` -------------------------------- ### Control Timestamp Updates with use_timestamp_with_controls Source: https://leptos-use.rs/animation/use_timestamp Shows how to use `use_timestamp_with_controls` to get a reactive timestamp along with controls to pause and resume updates. The `pause` and `resume` functions are sendwrapped and can only be called from the same thread. ```rust use leptos::prelude::*; use leptos_use::{use_timestamp_with_controls, UseTimestampReturn}; #[component] fn Demo() -> impl IntoView { let UseTimestampReturn { timestamp, is_active, pause, resume, } = use_timestamp_with_controls(); view! { } } ``` -------------------------------- ### Provide WebsocketContext using leptos-use and dynamic dispatch Source: https://leptos-use.rs/network/use_websocket This snippet shows how to initialize `use_websocket` and provide the resulting context. It uses dynamic dispatch for the send function, wrapped in an `Arc`, to avoid explicit type parameters when providing the `WebsocketContext`. ```rust use leptos::prelude::*; use codee::string::FromToStringCodec; use leptos_use::{use_websocket, UseWebSocketReturn}; use std::sync::Arc; #[derive(Clone)] pub struct WebsocketContext { pub message: Signal>, send: Arc, } impl WebsocketContext { pub fn new(message: Signal>, send: Arc) -> Self { Self { message, send, } } } #[component] fn Demo() -> impl IntoView { let UseWebSocketReturn { message, send, .. // Ignore other fields like reconnect, close, etc. } = use_websocket::("ws:://some.websocket.io"); provide_context(WebsocketContext::new(message, Arc::new(send.clone()))); view! {} } ``` -------------------------------- ### Read and Set CSS Variable with use_css_var Source: https://leptos-use.rs/browser/use_css_var Demonstrates the basic usage of use_css_var to get and set a CSS variable's value. It initializes a CSS variable and then updates its value. This function requires the 'use_css_var' feature to be enabled. ```rust use leptos::prelude::*; use leptos_use::use_css_var; #[component] fn Demo() -> impl IntoView { let (color, set_color) = use_css_var("--color"); set_color.set("red".to_string()); view! {} // Placeholder for actual view content } ``` -------------------------------- ### Color Mode with Explicit Values and Persistence in Leptos Source: https://leptos-use.rs/browser/use_color_mode Shows how to explicitly get and set color modes (Dark, Light, Auto) using the `set_mode` function. This example highlights the persistence of the selected mode to local storage. ```rust use leptos::prelude::*; use leptos_use::{ColorMode, use_color_mode, UseColorModeReturn}; #[component] fn Demo() -> impl IntoView { let UseColorModeReturn { mode, set_mode, .. } = use_color_mode(); mode.get(); // Returns ColorMode::Dark or ColorMode::Light set_mode.set(ColorMode::Dark); // Changes to dark mode and persists it set_mode.set(ColorMode::Auto); // Changes back to auto mode view! { } } ``` -------------------------------- ### Reactive Clipboard API with Leptos Source: https://leptos-use.rs/browser/use_clipboard Demonstrates the usage of the `use_clipboard` hook to interact with the system clipboard in a Leptos application. It shows how to check for browser support, display the copied status, and trigger a copy action. The `copy` function can only be called from the same thread as `use_clipboard`. On the server, `text` is None and `copy` is a no-op. ```rust use leptos::prelude::*; use leptos_use::{use_clipboard, UseClipboardReturn}; #[component] fn Demo() -> impl IntoView { let UseClipboardReturn { is_supported, text, copied, copy } = use_clipboard(); view! { Your browser does not support Clipboard API

} >
} } ``` -------------------------------- ### Header Utility: Get HTTP header value on the server Source: https://leptos-use.rs/print The `header` utility function retrieves the value of an HTTP header by its name. This function is intended for server-side usage and requires the 'ssr' feature along with 'axum' or 'actix' features to be enabled. ```rust use leptos_use::utils::header; let content_len = header(http::header::CONTENT_LENGTH); ``` -------------------------------- ### Show Desktop Notification with Leptos-Use (Rust) Source: https://leptos-use.rs/browser/use_web_notification Demonstrates how to use the `use_web_notification_with_options` function to display a desktop notification. It configures notification options like direction, language, and tag. The `show` function is used to present the notification with a specified title. This feature is client-side only and requires the `use_web_notification` crate feature to be enabled. ```rust use leptos::prelude::*; use leptos_use::{use_web_notification_with_options, UseWebNotificationOptions, ShowOptions, UseWebNotificationReturn, NotificationDirection}; #[component] fn Demo() -> impl IntoView { let UseWebNotificationReturn { show, close, .. } = use_web_notification_with_options( UseWebNotificationOptions::default() .direction(NotificationDirection::Auto) .language("en") .renotify(true) .tag("test"), ); show(ShowOptions::default().title("Hello World from leptos-use")); view! { } } ``` -------------------------------- ### Manipulate CSS Variables (Rust) Source: https://leptos-use.rs/print Hook to reactively get and set CSS variables. It can work with a static variable name or a signal for dynamic updates. Options allow specifying a target element, an initial value, and observing changes to the CSS variable. ```rust use leptos::prelude::*; use leptos_use::use_css_var; #[component] fn Demo() -> impl IntoView { let (color, set_color) = use_css_var("--color"); set_color.set("red".to_string()); view! { } } ``` ```rust use leptos::prelude::*; use leptos_use::use_css_var; #[component] fn Demo() -> impl IntoView { let (key, set_key) = signal("--color".to_string()); let (color, set_color) = use_css_var(key); view! { } } ``` ```rust use leptos::prelude::*; use leptos::html::Div; use leptos_use::{use_css_var_with_options, UseCssVarOptions}; #[component] fn Demo() -> impl IntoView { let el = NodeRef::
::new(); let (color, set_color) = use_css_var_with_options( "--color", UseCssVarOptions::default() .target(el) .initial_value("#eee") .observe(true), ); view! {
"..."
} } ``` -------------------------------- ### Using Resize Observer with Multiple Elements Source: https://leptos-use.rs/print Demonstrates the `use_resize_observer` function, which can observe multiple elements. It accepts various input formats for elements, including arrays of `Option`, vectors of CSS selectors, and slices of `NodeRef`. ```rust // Array of Option use_resize_observer([window().body(), document().query_selector("div > p.some-class").unsrap()]); // Vec of &str. All of them will be interpreted as CSS selectors with query_selector_all() and the // results will be merged into one Vec. use_resize_observer(vec!["div > p.some-class", "p.some-class"]); // Slice of NodeRef let node_ref1 = NodeRef::
::new(); let node_ref2 = NodeRef::
::new(); use_resize_observer(vec![node_ref1, node_ref2].as_slice()); ``` -------------------------------- ### Detect User's Preferred Contrast Setting Source: https://leptos-use.rs/print Reactively detects the user's preferred contrast setting based on media queries. It returns a signal that indicates whether the user prefers more or less contrast. This hook is related to `use_media_query` and `use_preferred_dark`. ```rust use leptos::prelude::*; use leptos_use::use_preferred_contrast; #[component] fn Demo() -> impl IntoView { let preferred_contrast = use_preferred_contrast(); view! { } } ``` -------------------------------- ### Reactive Window Scroll with Leptos Source: https://leptos-use.rs/elements/use_window_scroll This snippet demonstrates how to use the `use_window_scroll` function from the `leptos_use` crate to get reactive scroll position signals (x and y). Note that on the server, these signals will always be 0.0. This feature requires the `use_window_scroll` crate feature to be enabled. ```rust use leptos::prelude::*; use leptos_use::use_window_scroll; #[component] fn Demo() -> impl IntoView { let (x, y) = use_window_scroll(); view! { } } ``` -------------------------------- ### Track Window Focus Reactively with leptos_use Source: https://leptos-use.rs/print The `use_window_focus` function from leptos_use reactively tracks the browser window's focus state using `window.onfocus` and `window.onblur` events. It returns a Signal that is `true` when the window is focused and `false` otherwise. On the server, this Signal is always `true`. Requires the `use_window_focus` crate feature. ```rust use leptos::prelude::*; use leptos_use::use_window_focus; #[component] fn Demo() -> impl IntoView { let focused = use_window_focus(); view! { } } ```