### Run Dioxus SDK Example Source: https://github.com/dioxuslabs/sdk/blob/main/examples/timing/README.md Use this command to serve and run the Dioxus SDK time example. ```bash dx serve ``` -------------------------------- ### Geolocation Example with Dioxus SDK Source: https://github.com/dioxuslabs/sdk/blob/main/README.md Demonstrates how to initialize and use the geolocation service in a Dioxus application. Requires the `dioxus-sdk-geolocation` crate. Handles initialization, location retrieval, and error states. ```rust // dioxus-sdk-geolocation= { version = "*" } use dioxus::prelude::*; use dioxus_sdk_geolocation::{ init_geolocator, use_geolocation, PowerMode }; #[component] fn App() -> Element { let geolocator = init_geolocator(PowerMode::High).unwrap(); let coords = use_geolocation(); match coords { Ok(coords) => { rsx!( p { "Latitude: {coords.latitude} | Longitude: {coords.longitude}" } ) } Err(Error::NotInitialized) => { rsx!( p { "Initializing..." } ) } Err(e) => { rsx!( p { "An error occurred {e}" } ) } } } ``` -------------------------------- ### Initialize Geolocator and Use Geolocation Hook Source: https://github.com/dioxuslabs/sdk/blob/main/packages/geolocation/README.md This example demonstrates how to initialize the geolocator with a specific power mode and then use the use_geolocation hook to display the user's coordinates or any errors encountered. ```rust use dioxus::prelude::*; use dioxus_sdk_geolocation::{ init_geolocator, use_geolocation, PowerMode }; #[component] fn App() -> Element { let geolocator = init_geolocator(PowerMode::High).unwrap(); let coords = use_geolocation(); match coords { Ok(coords) => { rsx!( p { "Latitude: {coords.latitude} | Longitude: {coords.longitude}" } ) } Err(Error::NotInitialized) => { rsx!( p { "Initializing..." } ) } Err(e) => { rsx!( p { "An error occurred {e}" } ) } } } ``` -------------------------------- ### Dioxus App with Interval and Debounce Hooks Source: https://github.com/dioxuslabs/sdk/blob/main/packages/time/README.md This example demonstrates using `use_interval` to increment a counter every second and `use_debounce` to reset the counter after a 2-second delay following the last button click. Ensure `dioxus-sdk-time` is added as a dependency. ```rust use dioxus::{logger::tracing::info, prelude::*}; use dioxus_sdk_time::{use_debounce, use_interval}; use std::time::Duration; fn main() { dioxus::launch(App); } #[component] fn App() -> Element { let mut count = use_signal(|| 0); // Increment count every second. use_interval(Duration::from_secs(1), move || count += 1); // Reset count after 2 seconds of the latest action call. let mut debounce = use_debounce(Duration::from_millis(2000), move |text| { info!("{text}"); count.set(0); }); rsx! { p { "{count}" }, button { // Trigger the debounce. onclick: move |_| debounce.action("button was clicked"), "Reset the counter! (2 second debounce)" } } } ``` -------------------------------- ### Use One-Shot Timer Hook in Dioxus Source: https://context7.com/dioxuslabs/sdk/llms.txt Demonstrates how to use the `use_timeout` hook to execute a callback after a delay. Includes functionality to start and cancel the timeout. ```rust use dioxus::prelude::* use dioxus_sdk_time::{use_timeout, TimeoutHandle}; use std::time::Duration; #[component] fn App() -> Element { let mut message = use_signal(|| "Click the button!"); let mut pending_timeout: Signal> = use_signal(|| None); let timeout = use_timeout(Duration::from_secs(3), move |()| { message.set("Timeout fired!"); pending_timeout.set(None); }); rsx! { div { p { "{message}" } button { onclick: move |_| { message.set("Waiting for 3 seconds..."); let handle = timeout.action(()); pending_timeout.set(Some(handle)); }, "Start 3s Timeout" } if pending_timeout().is_some() { button { onclick: move |_| { if let Some(handle) = pending_timeout.take() { handle.cancel(); message.set("Timeout cancelled!"); } }, "Cancel" } } } } } ``` ```rust use dioxus::prelude::* use dioxus_sdk_time::sleep; use std::time::Duration; #[component] fn App() -> Element { let mut status = use_signal(|| "Ready"); rsx! { div { p { "Status: {status}" } button { onclick: move |_| { spawn(async move { status.set("Processing..."); // Wait 2 seconds sleep(Duration::from_secs(2)).await; status.set("Step 1 complete"); // Wait another second sleep(Duration::from_secs(1)).await; status.set("All done!"); }); }, "Start Process" } } } } ``` ```rust use dioxus::prelude::* use dioxus_sdk_time::use_timeout; use std::time::Duration; #[component] fn AsyncNotification() -> Element { let mut show_notification = use_signal(|| false); let hide_timeout = use_timeout(Duration::from_secs(5), move |()| async move { // Can do async work before hiding dioxus_sdk_time::sleep(Duration::from_millis(300)).await; show_notification.set(false); }); rsx! { div { button { onclick: move |_| { show_notification.set(true); hide_timeout.action(()); }, "Show Notification" } if show_notification() { div { class: "notification", "This will auto-hide in 5 seconds" } } } } } ``` -------------------------------- ### Track Window Dimensions with use_window_size Source: https://context7.com/dioxuslabs/sdk/llms.txt Use this hook to get reactive window dimensions. It works on both web and desktop platforms. Access individual dimensions using extension methods like `.width()` and `.height()`. ```rust use dioxus::prelude::* use dioxus_sdk_window::size::{use_window_size, get_window_size, ReadableWindowSizeExt}; #[component] fn App() -> Element { let size = use_window_size(); rsx! { div { h1 { "Window Size Tracker" } match size() { Ok(s) => rsx! { p { "Width: {s.width}px" } p { "Height: {s.height}px" } p { "Aspect Ratio: {s.width as f64 / s.height as f64:.2}" } }, Err(e) => rsx! { p { "Error getting size: {e}" } } } } } } ``` ```rust // Using the extension trait for individual dimensions #[component] fn ResponsiveLayout() -> Element { let size = use_window_size(); // Access individual dimensions with extension methods let is_mobile = use_memo(move || { size.width().map(|w| w < 768).unwrap_or(false) }); let half_width = use_memo(move || { size.width().unwrap_or(800) / 2 }); rsx! { div { style: "width: {half_width}px;", if is_mobile() { MobileNav {} } else { DesktopNav {} } p { "Content area: {half_width}px wide" } } } } #[component] fn MobileNav() -> Element { rsx! { nav { "Mobile Navigation" } } } #[component] fn DesktopNav() -> Element { rsx! { nav { "Desktop Navigation" } } } ``` -------------------------------- ### Serve Dioxus App for Desktop Source: https://github.com/dioxuslabs/sdk/blob/main/examples/window_size/README.md Run your Dioxus application on the desktop platform using the `dx serve` command. ```bash dx serve --platform desktop ``` -------------------------------- ### Serve Dioxus App for Web Source: https://github.com/dioxuslabs/sdk/blob/main/examples/window_size/README.md Run your Dioxus application on the web platform using the `dx serve` command. ```bash dx serve --platform web ``` -------------------------------- ### Show a basic notification in Dioxus Source: https://github.com/dioxuslabs/sdk/blob/main/packages/notification/README.md Use the Notification::new() builder pattern to construct and display a system notification. Ensure the app_name, summary, and body are set before calling show(). ```rust use dioxus_sdk_notification::Notification; Notification::new() .app_name("dioxus test".to_string()) .summary("hi, this is dioxus test".to_string()) .body("lorem ipsum".to_string()) .show() .unwrap(); ``` -------------------------------- ### Add Dioxus SDK Window Dependency Source: https://github.com/dioxuslabs/sdk/blob/main/packages/window/README.md Add the `dioxus-sdk-window` crate to your project's `Cargo.toml` file to include window management features. ```toml [dependencies] dioxus-sdk-window = "0.1" ``` -------------------------------- ### Add Dioxus SDK to Project Dependencies Source: https://github.com/dioxuslabs/sdk/blob/main/README.md Shows how to include the `dioxus-sdk` crate in your project's `Cargo.toml` file. Feature flags can be enabled here to include specific SDK functionalities. ```toml [dependencies] dioxus-sdk = { version = "0.6", features = [] } ``` -------------------------------- ### Add Dioxus SDK Time Dependency Source: https://github.com/dioxuslabs/sdk/blob/main/packages/time/README.md Add the `dioxus-sdk-time` crate to your project's `Cargo.toml` file to include timing utilities. ```toml [dependencies] dioxus-sdk-time = "0.1" ``` -------------------------------- ### Initialize and Use Geolocation Hook Source: https://context7.com/dioxuslabs/sdk/llms.txt Initializes the geolocator with high accuracy and displays real-time latitude and longitude. Handles initialization, access denied, and other errors. ```rust use dioxus::prelude::* use dioxus_sdk_geolocation::{init_geolocator, use_geolocation, Error, PowerMode}; #[component] fn App() -> Element { // Initialize geolocator first (call once at app root) let _geolocator = init_geolocator(PowerMode::High).unwrap(); // Get reactive location updates let coords = use_geolocation(); rsx! { div { h1 { "Location Tracker" } match coords() { Ok(coords) => rsx! { p { "Latitude: {coords.latitude:.6}" } p { "Longitude: {coords.longitude:.6}" } a { href: "https://www.google.com/maps?q={coords.latitude},{coords.longitude}", target: "_blank", "View on Google Maps" } }, Err(Error::NotInitialized) => rsx! { p { "Initializing location services..." } }, Err(Error::AccessDenied) => rsx! { p { "Location access denied. Please enable location permissions." } }, Err(e) => rsx! { p { "Error: {e}" } } } } } } ``` -------------------------------- ### Add Dioxus SDK Util Dependency Source: https://github.com/dioxuslabs/sdk/blob/main/packages/util/README.md Include `dioxus-sdk-util` in your project's `Cargo.toml` file to use its utilities. ```toml [dependencies] dioxus-sdk-util = "0.1" ``` -------------------------------- ### Send Basic Desktop Notification Source: https://context7.com/dioxuslabs/sdk/llms.txt Sends a basic native desktop notification with a summary and body. Ensure the app name is set for clarity. ```rust use dioxus::prelude::* use dioxus_sdk_notification::{Notification, NotificationTimeout}; use std::time::Duration; #[component] fn App() -> Element { rsx! { div { button { onclick: move |_| { // Basic notification Notification::new() .app_name("My Dioxus App") .summary("Task Complete") .body("Your download has finished!") .show() .unwrap(); }, "Send Notification" } } } } ``` -------------------------------- ### Use Generic Storage Hook (use_storage) Source: https://context7.com/dioxuslabs/sdk/llms.txt A lower-level storage hook generic over the storage backing (LocalStorage or SessionStorage). Allows creating custom storage hooks. ```rust use dioxus::prelude::*; use dioxus_sdk_storage::{use_storage, LocalStorage, SessionStorage}; use serde::{Deserialize, Serialize}; #[derive(Clone, Serialize, Deserialize, PartialEq, Default)] struct UserPreferences { theme: String, font_size: u32, } // Custom hook using LocalStorage (persists until cleared) fn use_local_prefs() -> Signal { use_storage::("user-prefs", UserPreferences::default) } // Custom hook using SessionStorage (cleared when browser closes) fn use_session_data() -> Signal { use_storage::("session-token", || String::new()) } #[component] fn App() -> Element { let mut prefs = use_local_prefs(); let session = use_session_data(); rsx! { div { p { "Theme: {prefs.read().theme}" } p { "Font Size: {prefs.read().font_size}" } button { onclick: move |_| { prefs.write().theme = "dark".to_string(); prefs.write().font_size = 16; }, "Apply Dark Theme" } } } } ``` -------------------------------- ### Initialize Geolocation with Low Power Mode Source: https://context7.com/dioxuslabs/sdk/llms.txt Initializes the geolocator using low power mode for background tracking and battery efficiency. Displays the last known coordinates. ```rust use dioxus::prelude::* use dioxus_sdk_geolocation::{init_geolocator, use_geolocation, Error, PowerMode}; // Low power mode for background tracking #[component] fn BackgroundTracker() -> Element { // Use low power mode for battery efficiency let _geolocator = init_geolocator(PowerMode::Low).unwrap(); let coords = use_geolocation(); rsx! { div { if let Ok(c) = coords() { p { "Last known: {c.latitude:.4}, {c.longitude:.4}" } } } } } ``` -------------------------------- ### Add Dioxus SDK Sync Dependency Source: https://github.com/dioxuslabs/sdk/blob/main/packages/sync/README.md Include `dioxus-sdk-sync` in your project's `Cargo.toml` file to add synchronization primitives. ```toml [dependencies] dioxus-sdk-sync = "0.1" ``` -------------------------------- ### Detect System Theme with use_system_theme Hook Source: https://context7.com/dioxuslabs/sdk/llms.txt Use `use_system_theme` to reactively track the operating system's theme preference. This hook updates automatically when system settings change. Use `get_theme` for a one-time check within effects or handlers. ```rust use dioxus::prelude::* use dioxus_sdk_window::theme::{use_system_theme, get_theme, Theme, ThemeError}; #[component] fn App() -> Element { // Reactive theme tracking let theme = use_system_theme(); // Determine CSS class based on theme let theme_class = match theme().unwrap_or(Theme::Light) { Theme::Light => "light-mode", Theme::Dark => "dark-mode", }; let bg_color = match theme().unwrap_or(Theme::Light) { Theme::Light => "#ffffff", Theme::Dark => "#1a1a2e", }; let text_color = match theme().unwrap_or(Theme::Light) { Theme::Light => "#333333", Theme::Dark => "#f0f0f0", }; rsx! { div { class: "{theme_class}", style: "background-color: {bg_color}; color: {text_color}; padding: 20px; min-height: 100vh;", h1 { "Theme-Aware App" } match theme() { Ok(Theme::Light) => rsx! { p { "You're using light mode" } }, Ok(Theme::Dark) => rsx! { p { "You're using dark mode" } }, Err(ThemeError::Unsupported) => rsx! { p { "Theme detection not supported" } }, Err(e) => rsx! { p { "Theme error: {e}" } } } } } } // One-time theme check (use inside effects/handlers only) #[component] fn ThemeChecker() -> Element { let mut current_theme = use_signal(|| None::); rsx! { button { onclick: move |_| { // get_theme() should only be called in effects/handlers to avoid hydration issues if let Ok(theme) = get_theme() { current_theme.set(Some(theme)); } }, "Check Theme" } if let Some(theme) = current_theme() { p { "Detected theme: {theme}" } } } } ``` -------------------------------- ### Add Individual Dioxus SDK Crates to Cargo.toml Source: https://context7.com/dioxuslabs/sdk/llms.txt Alternatively, add individual crates from the Dioxus SDK to your Cargo.toml. ```toml [dependencies] dioxus-sdk-storage = "0.7" dioxus-sdk-time = "0.7" dioxus-sdk-window = "0.7" dioxus-sdk-sync = "0.7" dioxus-sdk-geolocation = "0.7" dioxus-sdk-notification = "0.7" dioxus-sdk-util = "0.7" ``` -------------------------------- ### Add Dioxus Storage Dependency Source: https://github.com/dioxuslabs/sdk/blob/main/packages/storage/README.md Add the `dioxus-storage` crate to your project's `Cargo.toml` file to enable local and persistent storage functionalities. ```toml [dependencies] dioxus_sdk_storage = "0.1" ``` -------------------------------- ### Send Timed Desktop Notification with Icon Source: https://context7.com/dioxuslabs/sdk/llms.txt Sends a desktop notification with a specified icon path and a duration before it automatically dismisses. Note: `icon_path` is not supported on macOS. ```rust use dioxus::prelude::* use dioxus_sdk_notification::{Notification, NotificationTimeout}; use std::time::Duration; #[component] fn App() -> Element { rsx! { div { button { onclick: move |_| { // Notification with icon and timed duration Notification::new() .app_name("My Dioxus App") .summary("New Message") .body("You have 3 unread messages") .icon_path("/path/to/icon.png") // Not supported on macOS .timeout(NotificationTimeout::Duration(Duration::from_secs(10))) .show() .unwrap(); }, "Send Timed Notification" } } } } ``` -------------------------------- ### Track Document Scroll with use_root_scroll Source: https://context7.com/dioxuslabs/sdk/llms.txt This web-only hook tracks the scroll position and dimensions of the root document. It provides metrics for scroll position, viewport size, and content size. Use `use_memo` to calculate derived scroll metrics like scroll percentage or distance from the bottom. ```rust use dioxus::prelude::* use dioxus_sdk_util::scroll::use_root_scroll; #[component] fn App() -> Element { let scroll = use_root_scroll(); // Calculate useful scroll metrics let scroll_percentage = use_memo(move || { let metrics = scroll(); if metrics.scroll_height > metrics.client_height { (metrics.scroll_top / (metrics.scroll_height - metrics.client_height)) * 100.0 } else { 0.0 } }); let distance_from_bottom = use_memo(move || { let metrics = scroll(); metrics.scroll_height - (metrics.scroll_top + metrics.client_height) }); let is_near_bottom = use_memo(move || distance_from_bottom() < 100.0); // Generate long content for scrolling let content = "Lorem ipsum dolor sit amet. ".repeat(500); rsx! { // Fixed scroll indicator div { style: "position: fixed; top: 0; left: 0; right: 0; height: 4px; background: #eee; z-index: 100;", div { style: "height: 100%; background: #007bff; width: {scroll_percentage():.1}%;", } } // Fixed scroll info panel div { style: "position: fixed; top: 20px; right: 20px; padding: 10px; background: rgba(0,0,0,0.8); color: white; border-radius: 8px; z-index: 100;", p { "Scroll: {scroll().scroll_top:.0}px" } p { "Progress: {scroll_percentage():.1}%" } p { "To bottom: {distance_from_bottom():.0}px" } } // Main content div { style: "padding: 60px 20px 20px;", h1 { "Scroll Tracking Demo" } p { "{content}" } // Infinite scroll trigger if is_near_bottom() { div { style: "padding: 20px; text-align: center;", "Loading more content..." } } } } } ``` ```rust // Infinite scroll implementation #[component] fn InfiniteScrollList() -> Element { let scroll = use_root_scroll(); let mut items = use_signal(|| (1..=20).collect::>()); let mut loading = use_signal(|| false); // Load more when near bottom use_effect(move || { let metrics = scroll(); let distance = metrics.scroll_height - (metrics.scroll_top + metrics.client_height); if distance < 200.0 && !loading() { loading.set(true); spawn(async move { dioxus_sdk_time::sleep(std::time::Duration::from_secs(1)).await; let last = *items().last().unwrap_or(&0); items.write().extend((last + 1)..=(last + 10)); loading.set(false); }); } }); rsx! { ul { for item in items() { li { key: "{item}", "Item {item}" } } } if loading() { p { "Loading..." } } } } ``` -------------------------------- ### Use Persistent Storage with Auto-Generated Keys Source: https://context7.com/dioxuslabs/sdk/llms.txt Use `use_singleton_persistent` to store state that persists across renders. The hook automatically generates a unique key based on the call site location, ensuring each instance has its own isolated storage. ```rust use dioxus::prelude::* use dioxus_sdk_storage::use_singleton_persistent; #[component] fn Counter() -> Element { // Key is automatically generated from file:line location // Each call site gets its own unique storage key let mut count = use_singleton_persistent(|| 0); rsx! { button { onclick: move |_| *count.write() += 1, "Count: {count}" } } } #[component] fn App() -> Element { rsx! { div { // Each Counter instance has its own persistent storage Counter {} Counter {} // Different storage key due to different call location } } } ``` -------------------------------- ### Add dioxus-sdk-notification to Cargo.toml Source: https://github.com/dioxuslabs/sdk/blob/main/packages/notification/README.md Add this dependency to your project's Cargo.toml file to include the notification functionality. ```toml [dependencies] dioxus-sdk-notification = "0.1" ``` -------------------------------- ### Add Dioxus Geolocation to Cargo.toml Source: https://github.com/dioxuslabs/sdk/blob/main/packages/geolocation/README.md Add this dependency to your Cargo.toml file to include the geolocation utilities in your Dioxus project. ```toml [dependencies] dioxus-sdk-geolocation = "0.1" ``` -------------------------------- ### Use Cross-Tab Synchronized Storage (use_synced_storage) Source: https://context7.com/dioxuslabs/sdk/llms.txt A storage hook that synchronizes state across all browser tabs or application instances. Updates in one tab notify and update others. ```rust use dioxus::prelude::*; use dioxus_sdk_storage::{use_synced_storage, LocalStorage}; #[component] fn App() -> Element { // This value syncs across all open tabs of the application let mut shared_counter = use_synced_storage::("shared-count", || 0i32); rsx! { div { h1 { "Synced Counter: {shared_counter}" } p { "Open this page in multiple tabs to see synchronization!" } button { onclick: move |_| *shared_counter.write() += 1, "Increment (syncs to all tabs)" } button { onclick: move |_| shared_counter.set(0), "Reset" } } } } ``` -------------------------------- ### Use Persistent State with use_persistent Source: https://github.com/dioxuslabs/sdk/blob/main/packages/storage/README.md Demonstrates how to use the `use_persistent` hook to manage a persistent state variable, such as a counter, in a Dioxus component. This hook allows the state to persist across re-renders and can be initialized with a default value. ```rust use dioxus_sdk_storage::use_persistent; use dioxus::prelude::*; #[component] fn App() -> Element { let mut num = use_persistent("count", || 0); rsx! { div { button { onclick: move |_| { *num.write() += 1; }, "Increment" } div { "{ *num.read() }" } } } } ``` -------------------------------- ### Use Persistent Storage Hook (use_persistent) Source: https://context7.com/dioxuslabs/sdk/llms.txt A hook for storing data that persists across application reloads. Changes are automatically saved to storage. ```rust use dioxus::prelude::*; use dioxus_sdk_storage::use_persistent; #[component] fn App() -> Element { // Initialize with a key and default value factory let mut count = use_persistent("user-count", || 0); let mut username = use_persistent("username", || String::from("Guest")); rsx! { div { h1 { "Welcome, {username}!" } p { "Visit count: {count}" } button { onclick: move |_| { // Writing to the signal automatically persists the change *count.write() += 1; }, "Increment Count" } input { value: "{username}", oninput: move |e| { *username.write() = e.value(); } } } } } ``` -------------------------------- ### Use Async Sleep Function in Dioxus Source: https://context7.com/dioxuslabs/sdk/llms.txt Illustrates the use of the `dioxus_sdk_time::sleep` function for introducing asynchronous delays within Dioxus components, suitable for both web and desktop. ```rust use dioxus::prelude::* use dioxus_sdk_time::sleep; use std::time::Duration; #[component] fn App() -> Element { let mut status = use_signal(|| "Ready"); rsx! { div { p { "Status: {status}" } button { onclick: move |_| { spawn(async move { status.set("Processing..."); // Wait 2 seconds sleep(Duration::from_secs(2)).await; status.set("Step 1 complete"); // Wait another second sleep(Duration::from_secs(1)).await; status.set("All done!"); }); }, "Start Process" } } } } ``` -------------------------------- ### Use Broadcast Channel Hook in Dioxus Source: https://context7.com/dioxuslabs/sdk/llms.txt Use `use_channel` to create a broadcast channel for sending messages between components. Listeners can subscribe using `use_listen_channel`. Ensure to handle potential send/receive errors. ```rust use dioxus::prelude::* use dioxus_sdk_sync::channel::{use_channel, use_listen_channel, UseChannel}; #[derive(Clone, Debug)] enum AppEvent { UserLoggedIn(String), ThemeChanged(String), DataRefresh, } #[component] fn App() -> Element { // Create a channel with buffer size of 10 let channel: UseChannel = use_channel(10); rsx! { div { // Pass channel to children EventEmitter { channel } EventListener { channel } AnotherListener { channel } } } } #[component] fn EventEmitter(channel: UseChannel) -> Element { rsx! { div { button { onclick: move |_| { // Send event to all listeners channel.try_send(AppEvent::UserLoggedIn("Alice".to_string())).ok(); }, "Login as Alice" } button { onclick: move |_| { channel.try_send(AppEvent::ThemeChanged("dark".to_string())).ok(); }, "Switch to Dark Theme" } button { onclick: move |_| { // Async send spawn(async move { channel.send(AppEvent::DataRefresh).await.ok(); }); }, "Refresh Data" } } } } #[component] fn EventListener(channel: UseChannel) -> Element { let mut last_event = use_signal(|| "None".to_string()); // Listen for channel events use_listen_channel(&channel, move |result| async move { match result { Ok(event) => { last_event.set(format!("{:?}", event)); } Err(e) => { last_event.set(format!("Error: {:?}", e)); } } }); rsx! { p { "Last event: {last_event}" } } } #[component] fn AnotherListener(channel: UseChannel) -> Element { let mut theme = use_signal(|| "light".to_string()); use_listen_channel(&channel, move |result| async move { if let Ok(AppEvent::ThemeChanged(new_theme)) = result { theme.set(new_theme); } }); rsx! { p { "Current theme: {theme}" } } } ``` -------------------------------- ### Send Persistent Desktop Notification Source: https://context7.com/dioxuslabs/sdk/llms.txt Sends a desktop notification that remains visible until manually dismissed by setting the timeout to `NotificationTimeout::Never`. ```rust use dioxus::prelude::* use dioxus_sdk_notification::{Notification, NotificationTimeout}; use std::time::Duration; #[component] fn App() -> Element { rsx! { div { button { onclick: move |_| { // Notification with custom timeout Notification::new() .app_name("My Dioxus App") .summary("Important Alert") .body("This notification stays until dismissed") .timeout(NotificationTimeout::Never) .show() .unwrap(); }, "Send Persistent Notification" } } } } ``` -------------------------------- ### Use Interval for Repeated Timer Actions Source: https://context7.com/dioxuslabs/sdk/llms.txt The `use_interval` hook repeatedly executes a callback at a specified `Duration`. It supports both synchronous and asynchronous callbacks and can be cancelled. ```rust use dioxus::prelude::* use dioxus_sdk_time::use_interval; use std::time::Duration; #[component] fn App() -> Element { let mut seconds = use_signal(|| 0); let mut is_running = use_signal(|| true); // Increment counter every second let mut interval = use_interval(Duration::from_secs(1), move |()| { if is_running() { seconds += 1; } }); rsx! { div { h1 { "Timer: {seconds}s" } button { onclick: move |_| is_running.set(!is_running()), if is_running() { "Pause" } else { "Resume" } } button { onclick: move |_| { interval.cancel(); }, "Stop Timer" } } } } ``` ```rust // Async interval example #[component] fn AsyncPoller() -> Element { let mut data = use_signal(|| "Loading...".to_string()); use_interval(Duration::from_secs(5), move |()| async move { // Simulating async API call dioxus_sdk_time::sleep(Duration::from_millis(100)).await; data.set(format!("Updated at {:?}", std::time::Instant::now())); }); rsx! { p { "{data}" } } } ``` -------------------------------- ### Use Debounce for Delayed Actions Source: https://context7.com/dioxuslabs/sdk/llms.txt The `use_debounce` hook delays the execution of a callback until a specified `Duration` has passed without the action being triggered again. This is useful for debouncing user input to prevent excessive API calls. ```rust use dioxus::prelude::* use dioxus_sdk_time::use_debounce; use std::time::Duration; #[component] fn SearchInput() -> Element { let mut query = use_signal(|| String::new()); let mut results = use_signal(|| Vec::::new()); // Only search after user stops typing for 500ms let mut search_debounce = use_debounce(Duration::from_millis(500), move |search_term: String| { // This only runs after 500ms of no new input println!("Searching for: {search_term}"); results.set(vec![ format!("Result 1 for '{search_term}'"), format!("Result 2 for '{search_term}'"), ]); }); rsx! { div { input { r#type: "text", placeholder: "Search...", value: "{query}", oninput: move |e| { let value = e.value(); query.set(value.clone()); search_debounce.action(value); } } button { onclick: move |_| search_debounce.cancel(), "Cancel Search" } ul { for result in results() { li { "{result}" } } } } } } ``` ```rust // Async debounce example with auto-save #[component] fn AutoSaveEditor() -> Element { let mut content = use_signal(|| String::new()); let mut save_status = use_signal(|| "Saved"); let mut auto_save = use_debounce(Duration::from_secs(2), move |text: String| async move { save_status.set("Saving..."); // Simulate API call dioxus_sdk_time::sleep(Duration::from_millis(500)).await; println!("Auto-saved: {text}"); save_status.set("Saved"); }); rsx! { div { textarea { value: "{content}", oninput: move |e| { let value = e.value(); content.set(value.clone()); save_status.set("Unsaved changes..."); auto_save.action(value); } } p { "Status: {save_status}" } } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.