### Install Dioxus CLI (Prebuilt) Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/getting_started/index.md Downloads and installs the Dioxus CLI using a provided installation script. This is the recommended method for quick setup. ```sh curl -sSL https://dioxus.dev/install.sh | bash ``` -------------------------------- ### Configure WebView2 Installation Mode for Windows Bundles Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/configure.md Specify how WebView2 should be installed with Windows bundles. Options include embedding the bootstrapper, downloading it at runtime, using an offline installer, a fixed runtime path, or skipping installation. ```toml [webview_install_mode.EmbedBootstrapper] silent = true ``` ```toml [webview_install_mode.DownloadBootstrapper] silent = true ``` ```toml [webview_install_mode.OfflineInstaller] silent = true ``` ```toml [webview_install_mode.FixedRuntime] path = "path/to/runtime" ``` ```toml webview_install_mode = "Skip" ``` -------------------------------- ### View Dioxus CLI Help Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/index.md Run this command to verify your Dioxus CLI installation and to get an overview of all available commands and their options. ```bash dx --help ``` -------------------------------- ### SCSS Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/ui/styling.md Example of an SCSS file demonstrating variable usage and nested rules for styling. ```css $primary-color: #3b82f6; $secondary-color: #64748b; $border-radius: 8px; .card { background: white; border-radius: $border-radius; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); &:hover { box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } .header { background: $primary-color; color: white; padding: 16px; border-radius: $border-radius $border-radius 0 0; } .content { padding: 16px; color: $secondary-color; } } ``` -------------------------------- ### Server-Side Router Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/routing.md This example demonstrates setting up a server-side router for a fullstack Dioxus application. Ensure you have the Dioxus Router crate included in your project. ```rust use dioxus::prelude::*; use dioxus_router::prelude::*; #[derive(Routable, Clone, Debug)] eenum Route { #[route("/")] Home, #[route("/about")] About, } fn main() { LaunchBuilder::new() .launch(App) } fn App(cx: Scope) -> Element { rsx! { Router { } } } } #[inline_props] fn HomePage(cx: Scope) -> Element { rsx! { div { h1 {"Home Page"} Link { to: Route::About, "Go to About Page" } } } } #[inline_props] fn AboutPage(cx: Scope) -> Element { rsx! { div { h1 {"About Page"} Link { to: Route::Home, "Go to Home Page" } } } } ``` -------------------------------- ### Using `dioxus::serve` for Custom Server Setup Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/backend.md When `dioxus::launch` is insufficient, use `dioxus::serve` to get an Axum router. This maintains hot-reloading, logging, and devtools. ```rust use dioxus::prelude::*; fn main() { // ... dioxus_hot_reload::hot_reload_init!(); let mut app = DioxusApp {}; let router = app.router(); dioxus::serve(router, move || view(&mut app)).await; } // This is the server entrypoint impl DioxusApp { pub fn router(&self) -> axum::Router { // ... router.route("/api/save_dog", axum::routing::post(save_dog_server)) } } ``` -------------------------------- ### Full Dioxus Project Configuration Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/configure.md An example demonstrating all possible configuration fields for a Dioxus project, including application details, web settings, watchers, resources, proxies, and bundle information. ```toml [application] # App name name = "project_name" # `build` & `serve` output path out_dir = "dist" # The static resource path asset_dir = "public" [web.app] # HTML title tag content title = "project_name" [web.watcher] # When watcher is triggered, regenerate the `index.html` reload_html = true # Which files or dirs will be monitored watch_path = ["src", "public"] # Include style or script assets [web.resource] # CSS style file style = [] # Javascript code file script = [] [web.resource.dev] # Same as [web.resource], but for development servers # CSS style file style = [] # JavaScript files script = [] [[web.proxy]] backend = "http://localhost:8000/api/" [bundle] identifier = "com.dioxuslabs" publisher = "DioxusLabs" icon = "assets/icon.png" ``` -------------------------------- ### WebView2 Installer Mode Configuration Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/deploy/config.md Defines how the WebView2 runtime is installed. Options include skipping installation, downloading or embedding a bootstrapper, using an offline installer, or specifying a fixed runtime path. ```rust pub webview_install_mode: WebviewInstallMode, ``` -------------------------------- ### Install Rust Toolchains Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/getting_started/index.md Installs the stable Rust toolchain and the target for WebAssembly compilation. Ensure you have `rustup` installed. ```sh rustup toolchain install stable rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Example CSS Stylesheet Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/ui/styling.md An example of how an external CSS file (`main.css`) can be structured to style Dioxus components. ```css .my-component { background-color: #f0f9ff; border: 2px solid #0ea5e9; border-radius: 8px; padding: 16px; font-family: system-ui, sans-serif; } .my-component:hover { background-color: #e0f2fe; transform: translateY(-2px); transition: all 0.2s ease; } ``` -------------------------------- ### Install Dioxus CLI with cargo-binstall Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/getting_started/index.md Installs the Dioxus CLI using `cargo-binstall`. The `--force` flag can be used to overwrite an existing installation. ```sh cargo binstall dioxus-cli --force ``` -------------------------------- ### Native App Server Function Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/native.md Demonstrates calling a server function from a native Dioxus app. This example works identically on web, desktop, and mobile. ```rust use dioxus::prelude::*; fn main() { dioxus::launch(|| { let mut message = use_action(get_message); rsx! { h1 { "Server says: "} pre { "{message:?}"} button { onclick: move |_| message.call("world".into(), 30), "Click me!" } } }); } #[get("/api/{name}/?age")] async fn get_message(name: String, age: i32) -> Result { Ok(format!("Hello {}, you are {} years old!", name, age)) } ``` -------------------------------- ### Example Bundle Output Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/bundle.md This output indicates that the bundling process was successful and lists the generated application outputs, including the `.app` and `.dmg` files. ```sh 18.252s INFO Bundled app successfully! 18.252s INFO App produced 2 outputs: 18.252s INFO app - [./target/dx/hot_dog/bundle/macos/bundle/macos/HotDog.app] 18.252s INFO dmg - [./target/dx/hot_dog/bundle/macos/bundle/dmg/HotDog_0.1.0_aarch64.dmg] ``` -------------------------------- ### Hydration Example Introduction Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/ssr.md This Rust code snippet demonstrates the introductory part of a hydration example in Dioxus. It sets up the necessary components and logic for server-side rendering and client-side hydration. ```rust use dioxus::prelude::*; #[component] fn hydration_intro(cx: Scope) -> Element { // This component will be rendered on the server and then hydrated on the client. // Any futures or async operations here will be resolved on the server before rendering. let weather = use_future(cx, (), |_| async { // Simulate fetching weather data sleep(std::time::Duration::from_secs(1)).await; "Sunny" }); match weather.value() { Some(data) => rsx! { h1 { "Weather: {data}" } }, None => rsx! { h1 { "Loading weather..." } }, } } ``` -------------------------------- ### Install Dioxus CLI Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-070.md Use this command to install the Dioxus CLI with version management capabilities. ```bash curl https://dioxus.dev/install.sh | sh ``` -------------------------------- ### Install Dioxus CLI Source: https://github.com/dioxuslabs/docsite/blob/main/README.md Installs the Dioxus CLI using a script. Ensure you have a working Rust toolchain. ```sh curl -fsSL https://dioxus.dev/install.sh | bash ``` -------------------------------- ### Install Dioxus CLI with cargo-binstall Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/index.md Use cargo-binstall to install the Dioxus CLI, which bundles various development tools. This is the recommended method if prebuilt binaries are available for your platform. ```bash cargo binstall dioxus-cli ``` -------------------------------- ### Dioxus CLI Help Output Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/index.md This is an example of the output you can expect when running `dx --help`, detailing available commands and options for Dioxus development. ```text Dioxus: build web, desktop, and mobile apps with a single codebase Usage: dx [OPTIONS] Commands: new Create a new Dioxus project serve Build, watch, and serve the project bundle Bundle the Dioxus app into a shippable object build Build the Dioxus project and all of its assets run Run the project without any hotreloading init Init a new project for Dioxus in the current directory (by default). Will attempt to keep your project in a good state doctor Diagnose installed tools and system configuration print Print project information in a structured format, like cargo args, linker args, and other flags DX sets that might be useful in third-party tools translate Translate a source file into Dioxus code fmt Automatically format RSX check Check the project for any issues config Dioxus config file controls self-update Update the Dioxus CLI to the latest version tools Run a dioxus build tool. IE `build-assets`, `hotpatch`, etc components Manage components from the `dioxus-component` registry help Print this message or the help of the given subcommand(s) Options: --verbose Use verbose output [default: false] --trace Use trace output [default: false] --json-output Output logs in JSON format -h, --help Print help -V, --version Print version Logging Options: --log-to-file Write *all* logs to a file Manifest Options: --locked Assert that `Cargo.lock` will remain unchanged --offline Run without accessing the network --frozen Equivalent to specifying both --locked and --offline ``` -------------------------------- ### Dioxus Desktop App Setup Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/introducing-dioxus.md Initializes a new Dioxus binary crate for a desktop application and adds the Dioxus dependency with the 'desktop' feature. ```shell $ cargo init dioxus_example $ cd dioxus_example ``` ```toml [dependencies] dioxus = { version = "*", features = ["desktop"] } ``` -------------------------------- ### Prop Drilling Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/basics/context.md This example demonstrates prop drilling, where state is passed through multiple component layers. Use context to avoid this. ```rust fn app() -> Element { let name = use_signal(|| "bob".to_string()); rsx! { Container { name } } } #[name] fn Container(name: Signal) -> Element { rsx! { Content { name } } } #[name] fn Content(name: Signal) -> Element { rsx! { Title { name } } } #[name] fn Title(name: Signal) -> Element { rsx! { h1 { "{name}" } } } ``` -------------------------------- ### Install Dioxus CLI Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/deploy/index.md Install the Dioxus CLI using Cargo to facilitate application bundling. ```sh cargo install dioxus-cli ``` -------------------------------- ### Wix (Windows Installer) Settings Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/deploy/config.md Configures options for generating Windows Installer (MSI) packages, including language support, templates, and installer properties. ```rust #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub(crate) struct WixSettings { pub(crate) language: Vec<(String, Option) >, pub(crate) template: Option, pub(crate) fragment_paths: Vec, pub(crate) component_group_refs: Vec, pub(crate) component_refs: Vec, pub(crate) feature_group_refs: Vec, pub(crate) feature_refs: Vec, pub(crate) merge_refs: Vec, pub(crate) skip_webview_install: bool, pub(crate) license: Option, pub(crate) enable_elevated_update_task: bool, pub(crate) banner_path: Option, pub(crate) dialog_image_path: Option, pub(crate) fips_compliant: bool, /// MSI installer version in the format `major.minor.patch.build` (build is optional). /// /// Because a valid version is required for MSI installer, it will be derived from [`PackageSettings::version`] if this field is not set. /// /// The first field is the major version and has a maximum value of 255. The second field is the minor version and has a maximum value of 255. /// The third and fourth fields have a maximum value of 65,535. /// /// See for more info. pub version: Option, } ``` -------------------------------- ### Public Folder Structure Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/ui/assets.md Illustrates the typical file structure when using the public folder for assets. ```tree ├── assets ├── src └── public └── robots.txt ``` -------------------------------- ### Axum Router Setup with Dioxus Extensions Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/axum.md Demonstrates how Dioxus router extensions simplify the setup of static asset serving, SSR, and server function registration on an Axum router. ```rust axum::Router::new() .register_server_functions() .serve_static_assets() .fallback( get(render_handler).with_state(RenderHandleState::new(cfg, app)), ) ``` -------------------------------- ### Included example from src/included_example.rs Source: https://github.com/dioxuslabs/docsite/blob/main/packages/include_mdbook/packages/mdbook-gen-example/example-book/en/chapter_1.md This snippet is included directly from the specified Rust file. ```rust use dioxus_liveview::prelude::*; fn app(cx: Scope) -> Element { cx.render(rsx! { h1 {"Hello World"} }) } #[tokio::main] async fn main() { let mut app = LiveView::new(app); let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap(); println!("Listening on http://127.0.0.1:3000"); axum::serve(listener, app.into_axum()).await.unwrap(); } ``` -------------------------------- ### Serve Dioxus App in Development Mode Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/platforms/mobile.md Start the Dioxus development server to run your application, typically after navigating to the project directory. ```sh cd my-app dx serve ``` -------------------------------- ### Build output logs Source: https://github.com/dioxuslabs/docsite/blob/main/packages/include_mdbook/packages/mdbook-gen-example/example-book/en/chapter_1.md Example log output from a Dioxus build process, indicating successful bundling and output locations. ```json {"timestamp":" 9.927s","level":"INFO","message":"Bundled app successfully!","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"INFO","message":"App produced 2 outputs:","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"INFO","message":"app - [target/dx/hot_dog/bundle/macos/bundle/macos/HotDog.app]","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"INFO","message":"dmg - [target/dx/hot_dog/bundle/macos/bundle/dmg/HotDog_0.1.0_aarch64.dmg]","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"DEBUG","json":"{\"BundleOutput\":{\"bundles\":[\"target/dx/hot_dog/bundle/macos/bundle/macos/HotDog.app\"]}}"} ``` -------------------------------- ### dx bundle JSON output example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/bundle.md This is an example of the JSON output generated by `dx bundle` in JSON mode. It contains detailed information about the bundling process, including bundle types and paths. ```sh {"timestamp":" 9.927s","level":"INFO","message":"Bundled app successfully!","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"INFO","message":"App produced 2 outputs:","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"DEBUG","message":"Bundling produced bundles: [ Bundle { package_type: MacOsBundle, bundle_paths: [ "/Users/jonkelley/Development/Tinkering/06-demos/hot_dog/target/dx/hot_dog/bundle/macos/bundle/macos/HotDog.app", ], }, Bundle { package_type: Dmg, bundle_paths: [ "/Users/jonkelley/Development/Tinkering/06-demos/hot_dog/target/dx/hot_dog/bundle/macos/bundle/dmg/HotDog_0.1.0_aarch64.dmg", ], }, ]","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"INFO","message":"app - [/Users/jonkelley/Development/Tinkering/06-demos/hot_dog/target/dx/hot_dog/bundle/macos/bundle/macos/HotDog.app]","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"INFO","message":"dmg - [/Users/jonkelley/Development/Tinkering/06-demos/hot_dog/target/dx/hot_dog/bundle/macos/bundle/dmg/HotDog_0.1.0_aarch64.dmg]","target":"dx::cli::bundle"} {"timestamp":" 9.927s","level":"DEBUG","json":"{\"BundleOutput\":{\"bundles\":[\"/Users/jonkelley/Development/Tinkering/06-demos/hot_dog/target/dx/hot_dog/bundle/macos/bundle/macos/HotDog.app\",\"/Users/jonkelley/Development/Tinkering/06-demos/hot_dog/target/dx/hot_dog/bundle/macos/bundle/dmg/HotDog_0.1.0_aarch64.dmg\"]}}","target":"dx"} ``` -------------------------------- ### Verify Dioxus CLI Version Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/tooling.md Run this command to check if the dioxus-cli is installed and to verify its version against the guide. ```sh dx --version ``` -------------------------------- ### Example of implicit function overriding (discouraged) Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-070.md This example demonstrates an older approach using implicit function overriding, which led to issues where the program could get stuck waiting for I/O, preventing edits from taking effect. Explicit integration points are preferred. ```rust fn main() { loop { let next_event = wait_for_io(); do_thing(); } } ``` -------------------------------- ### Dioxus Component Example (Rust) Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/introducing-dioxus.md Defines a similar Card component in Dioxus using Rust, demonstrating state management and rendering with rsx! macro. ```rust #[derive(Props, PartialEq)] struct CardProps { title: String, paragraph: String } static Card: Component = |cx| { let mut count = use_state(&cx, || 0); cx.render(rsx!( aside { h2 { "{cx.props.title}" } p { "{cx.props.paragraph}" } button { onclick: move |_| count+=1, "Count: {count}" } }) ); }; ``` -------------------------------- ### Windows MSI Upgrade Code Configuration Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/deploy/config.md Defines the upgrade code for MSI installers. This GUID must remain constant across application updates to prevent duplicate installations. Tauri generates a default UUID v5, but it's recommended to set it explicitly in the Tauri config. ```rust pub upgrade_code: Option, ``` -------------------------------- ### Dioxus Hello World Source Code Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/beyond/walkthrough_readme.md The basic Dioxus program that renders 'Hello World' in a webview. This is the starting point for understanding the example's internals. ```rust use dioxus::prelude::*; fn main() { launch(app); } fn app(cx: Scope) -> Element { render! { h1 {"Hello World"} } } ``` -------------------------------- ### Run the Dioxus project Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/new_app.md Navigate to your project directory and use the `dx serve` command to build and run your Dioxus application. This command starts a local development server. ```sh cd hot_dog dx serve ``` -------------------------------- ### Get Element Handles with `onmounted` Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/advanced/breaking_out.md The `onmounted` event provides a live reference to a DOM element after it has been initially mounted. This allows you to interact with the element, for example, to focus or scroll it. ```rust use dioxus::prelude::*; use dioxus::web::Window; #[component] pub fn OnMounted() -> Element { rsx! { h1 {"Onmounted Example"} input { id: "my-input", placeholder: "Focus me", // The onmounted event fires after the element is mounted to the DOM. // It provides a reference to the element, allowing direct interaction. onmounted: move |event: Event| { // event.target() gives us the element that triggered the event. // We need to downcast it to the correct type (HtmlInputElement). if let Some(input) = event.target().unwrap().clone().dyn_into::().ok() { // Focus the input element input.focus().unwrap(); } } } } } ``` -------------------------------- ### Adding Custom Routes to Axum Router Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/axum.md Example of adding custom routes like POST for '/submit' and GET for '/about' and '/contact' to an Axum router, which will take priority over the Dioxus app's fallback handler. ```rust dioxus::serve(|| async move { use dioxus::server::axum::routing::{get, post}; let router = dioxus::server::router(app) .route("/submit", post(|| async { "Form submitted!" })) .route("/about", get(|| async { "About us" })) .route("/contact", get(|| async { "Contact us" })); Ok(router) }); ``` -------------------------------- ### Launching Client and Server Binaries with dx serve Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/project_setup.md Use the `dx serve` command with `@client` and `@server` modifiers to specify different binaries for the client and server components. This is useful when you have a dedicated server binary separate from your client application. ```sh dx serve @client --bin dog-app @server --bin pet-api ``` -------------------------------- ### Setting up Dioxus LiveView with Axum Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-030.md Example of setting up a LiveView application using Axum for routing and rendering. This demonstrates the basic structure for handling WebSocket connections and initial page rendering. ```rust async fn main() { let router = Router::new() .route("/", get(move || dioxus_liveview::body(addr))) .route("/app", get(move |ws| dioxus_liveview::render(ws))); axum::Server::bind("127.0.0.1".parse().unwrap()) .serve(router.into_make_service()) .await; } fn app(cx: Scope) -> Element { let posts = use_db_query(cx, RECENT_POSTS); render! { for post in posts { Post { key: "{post.id}", data: post } } } } ``` -------------------------------- ### Avoiding Waterfall Data Fetching Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/basics/resources.md This example shows how to avoid waterfall effects by initiating all data requests concurrently. By moving early return logic after all data fetching has started, requests can execute in parallel, improving performance. ```rust {{#include ../docs-router/src/doc_examples/data_fetching.rs:no_waterfall_effect}} ``` -------------------------------- ### Launch iOS Simulator Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/platforms/mobile.md Open the iOS simulator application and boot a specific device. ```sh open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app xcrun simctl boot "iPhone 15 Pro Max" ``` -------------------------------- ### Basic Dioxus Project Setup Source: https://github.com/dioxuslabs/docsite/blob/main/packages/include_mdbook/packages/mdbook-gen-example/example-book/en/chapter_2.md A minimal Rust main function demonstrating the inclusion of the dioxus_rocks crate. This serves as a basic entry point for a Dioxus application. ```rust fn main() { dioxus_rocks; } ``` -------------------------------- ### API Versioning: Using URL Prefixes Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/native.md Illustrates API versioning by using URL prefixes like `/api/v1/` and `/api/v2/` to manage different API versions and avoid breaking older clients. ```rust // This is at /api/v1/ #[post("/api/v1/do_it")] async fn do_it() -> Result<()> { /* */ } // This is at api/v2 #[post("/api/v2/do_it")] async fn do_it(name: String) -> Result<()> { /* */ } ``` -------------------------------- ### Dioxus CLI Help and Commands Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/tooling.md This output lists all available commands and options for the dioxus-cli, useful for managing your Dioxus projects. ```txt Build, Bundle & Ship Dioxus Apps Usage: dx [OPTIONS] Commands: build Build the Dioxus project and all of its assets translate Translate a source file into Dioxus code serve Build, watch & serve the Dioxus project and all of its assets new Create a new project for Dioxus init Init a new project for Dioxus in the current directory (by default). Will attempt to keep your project in a good state clean Clean output artifacts bundle Bundle the Dioxus app into a shippable object fmt Automatically format RSX check Check the project for any issues run Run the project without any hotreloading config Dioxus config file controls help Print this message or the help of the given subcommand(s) Options: --verbose Use verbose output [default: false] --trace Use trace output [default: false] --json-output Output logs in JSON format -h, --help Print help -V, --version Print version ``` -------------------------------- ### Install Dioxus CLI Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-040.md Command to install or update the Dioxus CLI, now renamed to 'dx'. Use '--force' to ensure the latest version is installed. ```bash cargo install dioxus-cli --force ``` -------------------------------- ### Basic Signal Initialization Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/basics/collections.md Demonstrates how to initialize a reactive Signal with an initial value. ```rust let mut count: Signal = use_signal(|| 0); ``` -------------------------------- ### Initialize SQLite Database Connection Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/databases.md Sets up a thread-local SQLite connection and creates the 'dogs' table if it doesn't exist. Ensure the 'server' feature is enabled. ```rust use dioxus::prelude::*; use dioxus_router::prelude::*; use std::sync::{Arc,Mutex}; #[derive(Clone, Debug)] struct DogImage(String); #[derive(Clone, Debug)] struct AppState { dogs: Vec, } impl AppState { fn new() -> Self { // Initialize the database connection let mut db = thread_local! { static DB: rusqlite::Connection = { let conn = rusqlite::Connection::open("hotdog.db").unwrap(); conn.execute_batch( "CREATE TABLE IF NOT EXISTS dogs ( id INTEGER PRIMARY KEY, image TEXT NOT NULL );", ).unwrap(); conn }; }; // Use the connection to fetch existing dogs let dogs = db.with(|db| { let mut stmt = db.prepare("SELECT image FROM dogs").unwrap(); let dogs_iter = stmt.query_map([], |row| Ok(DogImage(row.get(0)?))) .unwrap(); let mut dogs = Vec::new(); for dog in dogs_iter { dogs.push(dog.unwrap()); } dogs }); Self { dogs } } } #[component] fn App(cx: Scope) -> Element { use_shared_state_provider(cx, || AppState::new()); view! { cx, Router:: { outlet { cx } } } } #[derive(Routable, Clone, Debug)] enum Route { #[layout] Page, #[redirect] ToHome } #[component] fn Page(cx: Scope) -> Element { view! { cx, { let dogs = use_shared_state::(cx).unwrap(); view! { cx, h1 {"Favorite Dog Images"} ul { dogs.read().dogs.iter().map(|dog| { view! { cx, li { img { src: "{dog.0}", width: "100", } } } }) } AddDogForm {} } } } } #[component] fn AddDogForm(cx: Scope) -> Element { let dog_input = use_state(cx, || "".to_string()); let dogs = use_shared_state::(cx).unwrap(); view! { cx, form { onsubmit: move |event| { event.prevent_default(); // Use the database connection to save the dog let mut db = thread_local! { static DB: rusqlite::Connection = rusqlite::Connection::open("hotdog.db").unwrap(); }; db.with(|db| { let mut stmt = db.prepare_mut("INSERT INTO dogs (image) VALUES (?1)").unwrap(); stmt.execute([dog_input.current().clone()]).unwrap(); }); // Update the app state dogs.write().dogs.push(DogImage(dog_input.current().clone())); dog_input.set("".to_string()); }, label { "Dog Image URL: " input { value: "{dog_input}", oninput: move |event| { dog_input.set(event.value.clone()); } } } button {"Add Dog"} } } } fn main() { dioxus_web::launch(App); } ``` -------------------------------- ### Install WASM Target for Rust Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/creating.md Ensure the WASM target is installed for Rust before running your Dioxus project. This is necessary for web compilation. ```bash rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Application Configuration Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/configure.md Configure application-wide settings that apply to both web and desktop builds. Use 'asset_dir' for static assets and 'sub_package' to specify the default crate in a workspace. ```toml [application] asset_dir = "public" sub_package = "my-crate" ``` -------------------------------- ### Simplified `use_context` and `use_context_provider` Hooks Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/advanced/custom_hooks.md Illustrates custom implementations for `use_context` and `use_context_provider` hooks, showing how to consume and provide context within components. ```rust use dioxus::prelude::*; use std::cell::RefCell; use std::rc::Rc; // A simplified context type struct MyContext(String); fn use_context_provider(cx: Scope, value: MyContext) { // In a real scenario, this would use `provide_context` // For demonstration, we'll just store it locally cx.use_hook(|| value); } fn use_context(cx: Scope) -> MyContext { // In a real scenario, this would use `consume_context` // For demonstration, we'll return a default or a locally stored value cx.use_hook(|| MyContext("Default Context".to_string())) } ``` -------------------------------- ### Install Linux Dependencies for Dioxus (Fedora) Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/getting_started/index.md Installs additional development dependencies on Fedora for Dioxus, specifically `libxdo-devel` which is required for certain functionalities. ```sh sudo dnf install libxdo-devel ``` -------------------------------- ### Non-Cancel-Safe Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/basics/async.md This example demonstrates a future that is not cancel-safe. If cancelled during the `sleep` operation, the global state might not be restored correctly, leading to potential issues. ```rust use dioxus::prelude::spawn; use dioxus::fermi::use_atom_root; use dioxus::fermi::Atom; use std::time::Duration; static GLOBAL_COUNTER: Atom = Atom::new(0); fn not_cancel_safe() { let counter = use_atom_root(GLOBAL_COUNTER); spawn(async move { *counter.write() += 1; // Simulate a long operation that might be cancelled dioxus::core::time::sleep(Duration::from_secs(5)).await; // If cancelled here, the increment might not be undone // This is not cancel-safe *counter.write() -= 1; }); } ``` -------------------------------- ### Create New Dioxus App Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/platforms/mobile.md Initialize a new Dioxus project using the Dioxus CLI. ```sh dx new my-app ``` -------------------------------- ### Websocket with Path and Query Parameters Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/websockets.md Demonstrates how to extract path and query parameters before establishing a websocket connection, allowing for additional context. ```rust #[get("/api/uppercase_ws?name&age")] async fn uppercase_ws( name: String, age: i32, options: WebSocketOptions, ) -> Result> { // ... } ``` -------------------------------- ### Install Linux Dependencies for Dioxus (Arch) Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/getting_started/index.md Installs necessary development packages on Arch Linux for Dioxus. This covers web rendering, build tools, and system utilities. ```sh sudo pacman -Syu sudo pacman -S --needed \ webkit2gtk-4.1 \ base-devel \ curl \ wget \ file \ openssl \ appmenu-gtk-module \ libappindicator-gtk3 \ librsvg \ xdotool ``` -------------------------------- ### Install Development Dependencies on Linux Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/beyond/contributing.md Install necessary development packages on Ubuntu/Debian systems before running other build commands. A Nix flake is also available in the repo root. ```sh sudo apt install libgdk3.0-cil libatk1.0-dev libcairo2-dev libpango1.0-dev libgdk-pixbuf2.0-dev libsoup-3.0-dev libjavascriptcoregtk-4.1-dev libwebkit2gtk-4.1-dev ``` -------------------------------- ### Cancel-Safe Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/basics/async.md This example shows a cancel-safe approach. It ensures that resources are cleaned up properly even if the future is cancelled. In this case, it correctly decrements the counter regardless of cancellation. ```rust use dioxus::prelude::spawn; use dioxus::fermi::use_atom_root; use dioxus::fermi::Atom; use std::time::Duration; static GLOBAL_COUNTER: Atom = Atom::new(0); fn cancel_safe() { let counter = use_atom_root(GLOBAL_COUNTER); spawn(async move { // Increment the counter *counter.write() += 1; // Use `defer` to ensure cleanup happens even if the future is cancelled // or completes normally. defer(async move { *counter.write() -= 1; }); // Simulate a long operation dioxus::core::time::sleep(Duration::from_secs(5)).await; }); } ``` -------------------------------- ### NSIS Installer Minimum WebView2 Version Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/deploy/config.md Ensures the WebView2 runtime version is at least the specified version. If the user's WebView2 is older, the installer will attempt to trigger an update. ```rust pub minimum_webview2_version: Option, ``` -------------------------------- ### Launch Dioxus App Cross-Platform Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-050.md Use the unified `dioxus::launch` function from the prelude to start your application. The CLI automatically handles build features based on the target platform. ```rust use dioxus::prelude::*; fn main() { dioxus::launch(|| rsx!{ "hello world" }) } ``` -------------------------------- ### Configure Bundle Copyright Information Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/tools/configure.md Set the copyright notice for the application. ```toml copyright = "Copyright 2023 DioxusLabs" ``` -------------------------------- ### Cancel-safe future example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/basics/resources.md This example shows how to make a future cancel-safe by ensuring that any global state is properly restored when the future is dropped. Async methods often document their cancel-safety. ```rust {{#include ../docs-router/src/doc_examples/asynchronous.rs:cancel_safe}} ``` -------------------------------- ### Non-cancel-safe future example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/basics/resources.md This example demonstrates a future that is not cancel-safe, meaning it can cause issues if stopped mid-execution. Ensure futures are cancel-safe by restoring global state upon drop. ```rust {{#include ../docs-router/src/doc_examples/asynchronous.rs:not_cancel_safe}} ``` -------------------------------- ### Build Static Site with Dioxus CLI Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-060.md Use the Dioxus CLI command `dx build` with the `--platform web` and `--ssg` flags to generate static HTML files for your project. ```bash dx build --platform web --ssg ``` -------------------------------- ### Dioxus Router Configuration Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-020.md Example of setting up navigation in a Dioxus application using the new `Router`, `Route`, and `Link` components. Includes basic routing for home, users, and blog posts. ```rust fn app(cx: Scope) -> Element { cx.render(rsx! { Router { onchange: move |_| log::info!("Route changed!"), ul { Link { to: "/", li { "Go home!" } } Link { to: "users", li { "List all users" } } Link { to: "blog", li { "Blog posts" } } } Route { to: "/", "Home" } Route { to: "/users", "User list" } Route { to: "/users/:name", User {} } Route { to: "/blog", "Blog list" } Route { to: "/blog/:post", BlogPost {} } Route { to: "", "Err 404 Route Not Found" } } }) } ``` -------------------------------- ### Install Linux Dependencies for Dioxus (Ubuntu) Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/getting_started/index.md Installs essential development packages on Ubuntu for Dioxus, particularly for desktop and web applications. This includes WebKitGTK, build tools, and SSL libraries. ```sh sudo apt update sudo apt install libwebkit2gtk-4.1-dev \ build-essential \ curl \ wget \ file \ libxdo-dev \ libssl-dev \ libayatana-appindicator3-dev \ librsvg2-dev \ lld ``` -------------------------------- ### Dockerfile: Runtime Phase Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/tutorial/deploy.md The final phase copies the built web assets into a slim runtime environment and configures the server to run on a specified port. ```dockerfile FROM chef AS runtime COPY --from=builder /app/target/dx/hot_dog/release/web/ /usr/local/app # set our port and make sure to listen for all connections ENV PORT=8080 ENV IP=0.0.0.0 # expose the port 8080 EXPOSE 8080 WORKDIR /usr/local/app ENTRYPOINT [ "/usr/local/app/server" ] ``` -------------------------------- ### Example Telemetry Data Collected Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-070.md This JSON snippet shows an example of the telemetry data collected by the Dioxus CLI, including identity information, command details, and build stage updates. ```json {"identity":{"device_triple":"aarch64-apple-darwin","is_ci":false,"cli_version":"0.7.0-alpha.3 (ba856ac)","session_id":218853676744316928865703503826531902998},"name":"cli_command","module":null,"message":"serve","stage":"start","time":"2025-07-24T14:34:07.684804Z","values":{"args":{"address":{"addr":null,"port":null},"always_on_top":null,"cross_origin_policy":false,"exit_on_error":false,"force_sequential":false,"hot_patch":false,"hot_reload":null,"interactive":null,"open":null,"platform_args":{"client":null,"server":null,"shared":{"args":false,"targets":{"build_arguments":{"all_features":false,"base_path":false,"bin":null,"bundle":null,"cargo_args":false,"debug_symbols":true,"device":false,"example":false,"features":false,"inject_loading_scripts":true,"no_default_features":false,"package":null,"platform":null,"profile":false,"release":false,"renderer":{"renderer":null},"rustc_args":false,"skip_assets":false,"target":null,"target_alias":"Unknown","wasm_split":false},"fullstack":null,"ssg":false}}},"watch":null,"wsl_file_poll_interval":null}}} {"identity":{"device_triple":"aarch64-apple-darwin","is_ci":false,"cli_version":"0.7.0-alpha.3 (ba856ac)","session_id":218853676744316928865703503826531902998},"name":"build_stage","module":null,"message":"Build stage update","stage":"installing_tooling","time":"2025-07-24T14:34:08.358050Z","values":{}} {"identity":{"device_triple":"aarch64-apple-darwin","is_ci":false,"cli_version":"0.7.0-alpha.3 (ba856ac)","session_id":218853676744316928865703503826531902998},"name":"build_stage","module":null,"message":"Build stage update","stage":"starting","time":"2025-07-24T14:34:08.950001Z","values":{}} {"identity":{"device_triple":"aarch64-apple-darwin","is_ci":false,"cli_version":"0.7.0-alpha.3 (ba856ac)","session_id":218853676744316928865703503826531902998},"name":"build_stage","module":null,"message":"Build stage update","stage":"compiling","time":"2025-07-24T14:34:09.543745Z","values":{}} {"identity":{"device_triple":"aarch64-apple-darwin","is_ci":false,"cli_version":"0.7.0-alpha.3 (ba856ac)","session_id":218853676744316928865703503826531902998},"name":"build_stage","module":null,"message":"Build stage update","stage":"extracting_assets","time":"2025-07-24T14:34:10.142290Z","values":{}} {"identity":{"device_triple":"aarch64-apple-darwin","is_ci":false,"cli_version":"0.7.0-alpha.3 (ba856ac)","session_id":218853676744316928865703503826531902998},"name":"build_stage","module":null,"message":"Build stage update","stage":"bundling","time":"2025-07-24T14:34:10.319760Z","values":{}} ``` -------------------------------- ### Dioxus 0.5 Element Type Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/migration/to_06.md In Dioxus 0.5, the Element type was Option, allowing None to be returned directly. This example shows the old way of returning None. ```rust use dioxus::prelude::*; fn app() -> Element { let number = use_signal(|| -1); if number() < 0 { // ❌ In dioxus 0.6, the element type is a result, so None values cannot be returned directly return None; } rsx! { "Positive number: {number}" } } ``` -------------------------------- ### Basic Enum Router Setup Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-040.md A minimal Dioxus app demonstrating the new enum router. Requires route declaration, a matching component, and router rendering. ```rust // 1. Declare our app's routes #[derive(Clone, Routable, PartialEq, Eq, Serialize, Deserialize)] enum Route { #[route("/")] Homepage {}, } // 2. Make sure we have a component in scope that matches the enum variant fn Homepage(cx: Scope) -> Element { render! { "Welcome home!" } } // 3. Now render our app, using the Router and Route fn app(cx: Scope) -> Element { render! { Router:: {} } } ``` -------------------------------- ### Axum Middleware Function Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/essentials/fullstack/middleware.md Demonstrates how to create a basic middleware function using Axum's `from_fn`. This function logs request headers and then proceeds to run the request, allowing modification of the response. ```rust axum::middleware::from_fn( |request: Request, next: Next| async move { // Read and write the contents of the incoming request println!("Headers: {:?}", request.headers()); // And then run the request, modifying and returning the response next.run(request).await }, ) ``` -------------------------------- ### Add Rust iOS Targets Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/platforms/mobile.md Install the necessary Rust toolchains for building iOS applications. ```sh rustup target add aarch64-apple-ios aarch64-apple-ios-sim ``` -------------------------------- ### Add Rust Android Targets Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/platforms/mobile.md Install the necessary Rust toolchains for building Android applications. ```sh rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android ``` -------------------------------- ### Serving Fullstack Dioxus Apps with CLI Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/release-050.md Use the `dx serve` command to launch your fullstack Dioxus application. The CLI supports a `fullstack` platform with hot reloading and parallel builds for client and server. ```shell dx serve # Or with an explicit platform dx serve --platform fullstack ``` -------------------------------- ### TypeScript/React Component Example Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/blog/src/introducing-dioxus.md Defines a simple Card component in TypeScript/React with state management for a counter. ```tsx type CardProps = { title: string; paragraph: string; }; const Card: FunctionComponent = (props) => { let [count, set_count] = use_state(0); return ( ); }; ``` -------------------------------- ### Create New Project with Cargo Source: https://github.com/dioxuslabs/docsite/blob/main/docs-src/0.7/src/guides/utilities/ssr.md Initializes a new Rust project and navigates into its directory. ```sh cargo new --bin demo cd demo ```