=============== LIBRARY RULES =============== From library maintainers: - Dioxus is a Rust framework for building cross-platform apps - Use RSX for JSX-like markup in Rust - Follow Dioxus signals and hooks patterns for state management - Documentation is written in English - Code examples use Rust language ### Install Dioxus CLI (Prebuilt Binary) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/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 ``` -------------------------------- ### Serve Specific Example Binary Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/project-setup.md Run a specific example binary of your Dioxus application using `dx serve` with the `--example` flag. ```sh dx serve --example dogs ``` -------------------------------- ### Configure WebView2 Install Modes Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/configure.md Specify the installation mode for WebView2, choosing between 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" ``` -------------------------------- ### Install Dioxus CLI (Cargo-Binstall) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/getting-started/index.md Installs the Dioxus CLI using `cargo-binstall`. Use the `--force` flag if you need to overwrite an existing installation. ```sh cargo binstall dioxus-cli --force ``` -------------------------------- ### SCSS Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/ui/styling.md An example of an SCSS file demonstrating variables, nesting, and basic styling for a card component. ```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; } } ``` -------------------------------- ### Example Bundle Output Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/bundle.md This is an example of the terminal output you might see after a successful bundle operation, indicating the app and package files generated. ```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] ``` -------------------------------- ### Run Dioxus Example with dx serve Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/examples.md Use `dx serve` to run a Dioxus example locally after cloning the repository. This command is useful for testing and development. ```sh git clone https://github.com/DioxusLabs/dioxus cd dioxus/examples/01-app-demos dx serve --example calculator ``` -------------------------------- ### Install Rust Toolchains Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/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 ``` -------------------------------- ### Install Dioxus CLI Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/index.md Install the `dioxus-cli` using `cargo install` to facilitate application packaging. ```sh cargo install dioxus-cli ``` -------------------------------- ### Run Dioxus Example with Cargo Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/examples.md Alternatively, run a Dioxus example directly using Cargo. This method is suitable for projects managed with Cargo. ```sh cargo run --example calculator ``` -------------------------------- ### Windows Installer Settings (Wix/NSIS) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/config.md Configures Windows-specific installer settings, including digest algorithm, certificate thumbprint, timestamp URL, and options for Wix and NSIS installers. It also allows specifying a custom command for signing binaries. ```rust pub digest_algorithm: Option, pub certificate_thumbprint: Option, pub timestamp_url: Option, pub tsp: bool, pub wix: Option, pub icon_path: Option, pub webview_install_mode: WebviewInstallMode, pub webview_fixed_runtime_path: Option, pub allow_downgrades: bool, pub nsis: Option, /// Specify a custom command to sign the binaries. /// This command needs to have a `%1` in it which is just a placeholder for the binary path, /// which we will detect and replace before calling the command. /// /// Example: /// ```text /// sign-cli --arg1 --arg2 %1 /// ``` /// /// By Default we use `signtool.exe` which can be found only on Windows so /// if you are on another platform and want to cross-compile and sign you will /// need to use another tool like `osslsigncode`. pub sign_command: Option, ``` -------------------------------- ### Simple UI Declaration Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/utilities/custom-renderer.md An example of a basic UI declaration using Dioxus' rsx! macro. This demonstrates how a component might be structured. ```rust rsx! { h1 { "count: {x}" } } ``` -------------------------------- ### Verify Dioxus CLI Version Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/tooling.md Run this command to ensure your `dioxus-cli` is installed and up-to-date with the version recommended in this guide. ```sh dx --version ``` -------------------------------- ### Full Dioxus Configuration Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/configure.md A comprehensive TOML configuration example for a Dioxus application, including application name, output directories, asset paths, web app settings, watcher configurations, resource definitions, proxy settings, and bundle identifiers. ```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 Installation Mode Enum Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/config.md Specifies how WebView2 should be handled during installation, including skipping, downloading, embedding, or using a fixed runtime path. ```rust Skip, DownloadBootstrapper { silent: bool }, EmbedBootstrapper { silent: bool }, OfflineInstaller { silent: bool }, FixedRuntime { path: PathBuf }, ``` -------------------------------- ### Axum Router Setup with Dioxus Extensions Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/axum.md Demonstrates the core setup of an Axum router in Dioxus, including automatic registration of server functions, static asset serving, and SSR handlers. ```rust axum::Router::new() .register_server_functions() .serve_static_assets() .fallback( get(render_handler).with_state(RenderHandleState::new(cfg, app)), ) ``` -------------------------------- ### Run the Dioxus Project Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/new-app.md Navigate to your project directory and use `dx serve` to build and run your Dioxus application. This command starts a development server. ```sh cd hot_dog dx serve ``` -------------------------------- ### Install Dioxus CLI with cargo-binstall Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/index.md Installs the Dioxus CLI using cargo-binstall, which provides prebuilt binaries for common platforms. ```bash cargo binstall dioxus-cli ``` -------------------------------- ### Install Linux Dependencies (Ubuntu) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/getting-started/index.md Installs essential development dependencies for building Dioxus applications on Ubuntu, including WebkitGtk and build tools. ```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 ``` -------------------------------- ### Dioxus App Entrypoint Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/new-app.md The `main.rs` file's entrypoint. It uses `dioxus::launch` to start the application, passing the root component `App`. ```rust use dioxus::prelude::*; fn main() { dioxus::launch(App); } ``` -------------------------------- ### dx CLI JSON Output Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/bundle.md This is an example of the JSON output generated by the `dx` CLI in JSON mode. It contains detailed information about the bundling process, including timestamps, log levels, and bundle details. ```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"} ``` -------------------------------- ### Install Linux Dependencies (Fedora) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/getting-started/index.md Installs the `libxdo-devel` package on Fedora, which is required for certain Dioxus desktop functionalities. ```sh sudo dnf install libxdo-devel ``` -------------------------------- ### Run Android Emulator Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/platforms/mobile.md Launch an Android emulator from the command line. Adjust the device name (`-avd`) to match your installed emulator. ```sh emulator -avd Pixel_6_API_34 -netdelay none -netspeed full ``` -------------------------------- ### Prop Drilling Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/basics/context.md This example demonstrates prop drilling, where state is passed down through multiple component layers. Use this approach when passing values through only a few layers is not overly cumbersome. ```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}" } } } ``` -------------------------------- ### Rust struct for Windows MSI bundling settings Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/config.md Configures Windows Installer (MSI) specific packaging options, including language localization, 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, } ``` -------------------------------- ### Zero-Cost Reactivity Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/basics/signals.md Demonstrates how a component avoids re-rendering when a signal is modified but not used in the UI markup. ```rust let mut loading = use_signal(|| false); rsx! { button { // Because we don't use "loading" in our markup, the component won't re-render! onclick: move |_| async move { if loading() { return; } loading.set(true); // .. do async work loading.set(false); } } } ``` -------------------------------- ### Axum dependencies in Cargo.toml Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/utilities/ssr.md Example `Cargo.toml` file showing the required dependencies for Dioxus SSR with Axum. ```toml [dependencies] axum = "0.7" dioxus = { version = "*" } dioxus-ssr = { version = "*" } tokio = { version = "1.15.0", features = ["full"] } ``` -------------------------------- ### Dioxus 0.5 Global Signals Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/migration/to-05-fermi.md Demonstrates the equivalent functionality in Dioxus 0.5 using global signals, which do not require explicit initialization hooks. ```rust use dioxus::prelude::* static NAME: GlobalSignal = Signal::global(|| "world".to_string()); // Global signals work for copy and clone types in the same way static NAMES: GlobalSignal> = Signal::global(|| vec!["world".to_string()]); fn app() -> Element { // No need to use use_init_atom_root, use_set, or use_atom_ref. Just use the global signal directly rsx! { button { onclick: move |_| *NAME.write() = "reset name".to_string(), "reset name" } "{NAMES:?}" } } ``` -------------------------------- ### Asset Options in Dioxus 0.6 Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/migration/to-07.md Example of defining image assets with specific options in Dioxus 0.6 using `ImageAssetOptions::new()`. ```rust use manganis::{ImageFormat, ImageAssetOptions, Asset, asset, ImageSize}; pub const RESIZED_PNG_ASSET: Asset = asset!("/assets/image.png", ImageAssetOptions::new().with_size(ImageSize::Manual { width: 52, height: 52 })); pub const AVIF_ASSET: Asset = asset!("/assets/image.png", ImageAssetOptions::new().with_format(ImageFormat::Avif)); ``` -------------------------------- ### Composing Components with `rsx!` Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/component.md An example of composing multiple components together using the `rsx!` macro. This demonstrates how to structure an application by nesting components. ```rust #[component] fn App() -> Element { rsx! { Header {} DogApp { breed: "corgi" } Footer {} } } ``` -------------------------------- ### HTML Output of Basic Layout Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/router/layouts.md Illustrates the resulting HTML structure when the basic layout example is rendered. This shows how the header, index content, and footer are combined. ```html
header

Index

footer
``` -------------------------------- ### NSIS Installer Customization Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/config.md Provides detailed configuration for NSIS installers, including template files, license agreements, images, language selection, start menu folder, and installer hooks. It also allows specifying a minimum WebView2 version. ```rust pub template: Option, pub license: Option, pub header_image: Option, pub sidebar_image: Option, pub installer_icon: Option, pub install_mode: NSISInstallerMode, pub languages: Option>, pub custom_language_files: Option>, pub display_language_selector: bool, pub start_menu_folder: Option, pub installer_hooks: Option, /// Try to ensure that the WebView2 version is equal to or newer than this version, /// if the user's WebView2 is older than this version, /// the installer will try to trigger a WebView2 update. pub minimum_webview2_version: Option, ``` -------------------------------- ### Windows MSI Upgrade Code Configuration Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/config.md Defines the upgrade code for MSI installers. This GUID must remain constant across updates to prevent duplicate installations. Tauri generates a default UUID v5 based on the product name, but it's recommended to set this explicitly in the Tauri config. ```rust pub upgrade_code: Option, ``` -------------------------------- ### Launch Server with Specific Binaries Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/project-setup.md Use the 'dx serve' command with '@client' and '@server' modifiers to specify different binaries for client and server execution in a workspace setup. ```sh dx serve @client --bin dog-app @server --bin pet-api ``` -------------------------------- ### NSIS Installer Mode Enum Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/config.md Defines the installation scope for NSIS installers, allowing installation for the current user, per machine, or both. ```rust CurrentUser, PerMachine, Both, ``` -------------------------------- ### Launch a Basic Dioxus App Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/index.md Launches a simple Dioxus application with a counter. This example demonstrates basic state management using `use_signal` and event handling with `onclick`. ```rust use dioxus::prelude::*; fn main() { launch(app); } fn app() -> Element { let mut count = use_signal(|| 0); rsx! { h1 { "High-Five counter: {count}" } button { onclick: move |_| count += 1, "Up high!" } button { onclick: move |_| count -= 1, "Down low!" } } } ``` -------------------------------- ### Dockerfile: Phase 3 - Runtime Environment Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/deploy.md This phase copies the built web application into a slim runtime environment, sets the port and IP, and defines the entrypoint. ```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" ] ``` -------------------------------- ### Define a Basic Server Function with GET Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/server-functions.md This snippet shows how to define a basic server function using the `#[get]` macro, which automatically creates an HTTP GET endpoint. The function must be async and return a Result. ```rust #[get("/api/hello-world")] async fn hello_world() -> Result { // Ok("Hello world!".to_string()) } ``` -------------------------------- ### Building Desktop Applications with `dioxus-desktop` Source: https://context7.com/rustgrow/dioxus-context7-en/llms.txt Launch desktop applications using `dioxus-desktop`, which renders using the system WebView. This example demonstrates opening a file dialog and reading its content asynchronously. ```rust use dioxus::prelude::*; fn main() { dioxus::launch(App); } fn App() -> Element { let mut file_text = use_signal(String::new); rsx! { document::Stylesheet { href: asset!("/assets/app.css") } div { class: "container", img { src: asset!("/assets/logo.png"), alt: "Logo" } button { onclick: move |_| async move { if let Some(path) = rfd::AsyncFileDialog::new().pick_file().await { if let Ok(content) = tokio::fs::read_to_string(path.path()).await { file_text.set(content); } } }, "Open file" } pre { "{file_text}" } } } } ``` -------------------------------- ### Dockerfile: Phase 2 - Building the Application Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/deploy.md This phase uses cargo-chef to load cached dependencies and build the application. It also installs the `dx` CLI and bundles the web application. ```dockerfile FROM chef AS builder COPY --from=planner /app/recipe.json recipe.json RUN cargo chef cook --release --recipe-path recipe.json COPY . . # Install `dx` RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash RUN cargo binstall dioxus-cli --root /.cargo -y --force ENV PATH="/.cargo/bin:$PATH" # Create the final bundle folder. Bundle with release build profile to enable optimizations. RUN dx bundle --web --release ``` -------------------------------- ### Dioxus CLI Help and Commands Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/tooling.md This output displays the available commands and options for the `dioxus-cli`. Use `dx help` to see this information. ```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 WASM Target for Rust Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/creating.md Before running Dioxus projects, ensure the WASM target is installed for Rust. This is necessary for building web applications. ```bash rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Serve Native App with Desktop Feature Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/native.md Use the Dioxus CLI to serve your application with the desktop platform enabled. ```sh dx serve --desktop ``` -------------------------------- ### Manual Logger Initialization (v0.6) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/migration/to-06.md If manual configuration of the logger is required before `launch`, use `initialize_default` to set up the logger. ```rust use dioxus::prelude::*; fn main() { dioxus::logger::initialize_default(); tracing::info!("Logs received!"); dioxus::launch(app); } ``` -------------------------------- ### Impure Function Example (Global State) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/ui/render.md An example of an impure function that modifies global state, leading to different outputs on subsequent calls. ```rust static GLOBAL_COUNT: AtomicI32 = AtomicI32::new(0); fn increment_global_count() -> i32 { GLOBAL_COUNT.fetch_add(1, Ordering::SeqCst) } ``` -------------------------------- ### Create a New Dioxus Project Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/creating.md Use the `dx new` command to initialize a new Dioxus project. This command clones a default template. ```bash dx new ``` -------------------------------- ### Install Rust iOS Targets Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/platforms/mobile.md Add the necessary Rust toolchains for building iOS applications. Ensure these targets are installed before proceeding with iOS development. ```sh rustup target add aarch64-apple-ios aarch64-apple-ios-sim ``` -------------------------------- ### Configure macOS Bundle Frameworks Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/configure.md List of frameworks to include in the macOS bundle. ```toml frameworks = ["CoreML"] ``` -------------------------------- ### Install Rust Android Targets Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/platforms/mobile.md Add the necessary Rust toolchains for building Android applications. Ensure these targets are installed before proceeding with Android development. ```sh rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android ``` -------------------------------- ### Install Linux Dependencies (Arch) Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/getting-started/index.md Installs necessary development packages for Dioxus on Arch Linux, covering WebkitGtk, base development tools, and 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 ``` -------------------------------- ### Launch iOS Simulator and Boot Device Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/platforms/mobile.md Open the iOS simulator and boot a specific device. This is a prerequisite for running Dioxus apps on iOS simulators. ```sh open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app xcrun simctl boot "iPhone 15 Pro Max" ``` -------------------------------- ### Custom Server Entrypoint with `dioxus::serve` Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/backend.md Use `dioxus::serve` as an alternative to `dioxus::launch` for more control over the server-side application, allowing customization of the axum router while retaining hot-reloading and devtools. ```rust fn main() { #[cfg(not(feature = "server"))] dioxus::launch(App); #[cfg(feature = "server")] dioxus::serve(|| async move { // Create a new axum router for our Dioxus app let router = dioxus::server::router(App); // .. customize it however you want .. // And then return it Ok(router) }) } ``` -------------------------------- ### Application Configuration Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/configure.md Configure application-wide settings like the static asset directory and the default sub-package for workspaces. ```toml [application] asset_dir = "public" sub_package = "my-crate" ``` -------------------------------- ### Importing Launch Function Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/migration/to-06.md The `launch` function is no longer part of the prelude and must be imported from the `dioxus` crate or used with its full path. ```rust use dioxus::prelude::*; fn main() { // ❌ launch(app); dioxus::launch(app); // ✅ } ``` -------------------------------- ### Get Cloned Signal Value Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/basics/signals.md For cheaply cloneable types, you can get a direct clone of the signal's value by calling the signal like a function or using `.cloned()`. ```rust let name = use_signal(|| "Bob".to_string()); // Call the signal like a function let inner = name(); // Or use `.cloned()` let inner = name.cloned(); ``` -------------------------------- ### Fullstack Server Functions with `#[get]` Source: https://context7.com/rustgrow/dioxus-context7-en/llms.txt Define server-only HTTP endpoints using attributes like `#[get]`. These functions are callable from the client as if they were local async functions, with automatic serialization. ```rust use dioxus::prelude::*; #[derive(serde::Serialize, serde::Deserialize)] struct UserData { id: u32, name: String } // Generates GET /api/users/{user_id} #[get("/api/users/{user_id}", db: SqlDb)] async fn get_user(user_id: u32) -> Result { // `db` is a server-only extractor, not sent from the client db.query_one("SELECT id, name FROM users WHERE id = $1", &[&user_id]) .await .map_err(|e| anyhow::anyhow!(e)) } // Invoke from client code exactly like a normal async function: fn UserCard() -> Element { let user = use_resource(move || get_user(42)); rsx! { match &*user.read() { Some(Ok(u)) => rsx! { h2 { "Hello, {u.name}!" } }, Some(Err(e)) => rsx! { "Error: {e}" }, None => rsx! { "Loading..." }, } } } ``` ```sh curl http://127.0.0.1:8080/api/users/42 # {"id":42,"name":"Alice"} ``` -------------------------------- ### Install Development Dependencies on Linux Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/beyond/contributing.md Install necessary development packages on Ubuntu/Debian systems required for certain Dioxus build or test 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 ``` -------------------------------- ### Create Dioxus Project from a Specific Template Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/creating.md To create a project from a different template, specify the template using the `--template` argument. This example uses a GitHub repository. ```bash dx new --template gh:dioxuslabs/dioxus-template ``` -------------------------------- ### Start Tailwind CSS Compiler Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/utilities/tailwind.md Run this command in your project's root directory to start the Tailwind CSS compiler in watch mode. It will automatically recompile `input.css` to `assets/tailwind.css` whenever changes are detected. ```bash npx @tailwindcss/cli -i ./input.css -o ./assets/tailwind.css --watch ``` -------------------------------- ### Initial Component with Signals and Memo Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/basics/hoisting.md This snippet shows an initial component that combines name, email, and validation logic using signals and a memo. Use this as a starting point before refactoring. ```rust #[component] fn EmailAndName() -> Element { let mut name = use_signal(|| "name".to_string()); let mut email = use_signal(|| "email".to_string()); let is_valid = use_memo(move || validate_name_and_email(name, email)) rsx! { if !is_valid() { "Invalid name or email" } input { oninput: move |e| name.set(e.value()) } input { oninput: move |e| email.set(e.value()) } } } ``` -------------------------------- ### Prepare Web App for Client-Side Routing Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/index.md Copy `index.html` to `404.html` in the `docs` directory to ensure client-side routing works correctly with GitHub Pages. ```sh cp docs/index.html docs/404.html ``` -------------------------------- ### Pure Function Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/ui/render.md A simple pure function that always returns the same output for a given input. ```rust fn double(x: i32) -> i32 { // x * 2 } ``` -------------------------------- ### Inspect Web Bundle Structure Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/bundle.md View the generated file structure of the web bundle. The `public` folder contains assets and the `server` binary is also generated. ```bash tree -L 3 --gitignore ``` -------------------------------- ### Basic Server Function Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/server-functions.md A basic server function that defines a GET endpoint and returns a string. ```APIDOC ## GET /api/hello-world ### Description This endpoint returns a simple "Hello world!" string. ### Method GET ### Endpoint /api/hello-world ### Response #### Success Response (200) - **string** - The "Hello world!" message. ``` -------------------------------- ### Configure Bundle Resources in Dioxus.toml Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/deploy/index.md Specify files and globs to include in the application bundle using the `resources` key in `Dioxus.toml`. ```toml [bundle] # The list of files to include in the bundle. These can contain globs. resources = ["main.css", "header.svg", "**/*.png"] ``` -------------------------------- ### Rust Unit Test Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/testing/index.md Demonstrates how to write a basic unit test for a Rust function using the `#[test]` attribute and `assert_eq!` macro. Ensure your test functions are annotated correctly. ```rust fn add(a: i32, b: i32) -> i32 { a + b } #[test] fn test_add() { assert_eq!(add(2, 3), 5); } ``` -------------------------------- ### Lazy Future Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/basics/async.md Demonstrates that a Future does nothing until it is awaited or spawned. This Future will not execute its `println!` statement. ```rust let future = async { println!("Ran"); }; ``` -------------------------------- ### Bundle Desktop App with Specific Package Types Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/tutorial/bundle.md Use `dx bundle` with `--desktop` and `--package-types` to build installable desktop applications. Note that not all package types are compatible with every platform. ```sh dx bundle --desktop \ --package-types "macos" \ --package-types "dmg" ``` -------------------------------- ### Matching ServerFnError on the Client Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/server-functions.md This client-side example shows how to match on the ServerFnError to provide specific feedback based on the error code. ```rust match login().await { Err(ServerFnError::ServerError { code, .. }) => { if code == 404 { // .. handle not found } if code == 401 { // .. handle unauthorized } } _ => { /* */ } } ``` -------------------------------- ### Define a Basic Dioxus Component Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/ui/components.md A fundamental component in Dioxus is a function that returns an `Element`. This example shows the simplest form. ```rust fn app() -> Element { rsx! { "hello world!" } } ``` -------------------------------- ### Using WebsocketOptions as Custom Body Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/server-functions.md Demonstrates how to use `WebsocketOptions` as a custom input type in a server function and how to instantiate it on the client. ```rust // We can now use `WebsocketOptions` as a custom body: #[get("/api/ws/")] async fn get_updates(options: WebsocketOptions) -> Result<()> { // ... } // Calling the endpoint is still quite simple: _ = get_updates(WebsocketOptions::new()).await?; ``` -------------------------------- ### API Versioning: Breaking Change Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/native.md Illustrates a breaking change in an API endpoint signature that will affect older clients. ```rust // version 1 #[post("/api/do_it")] async fn do_it() -> Result<()> { /* */ } ``` ```rust // version 2 // ❌ we are breaking old clients! #[post("/api/do_it")] async fn do_it(name: String) -> Result<()> { /* */ } ``` -------------------------------- ### Web Watcher Configuration Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/guides/tools/configure.md Configure the development server's behavior, including HTML reloading, directories to watch, and handling 404s with the index page. ```toml [web.watcher] reload_html = true watch_path = ["src", "public"] index_on_404 = true ``` -------------------------------- ### Using Global Signal and Global Memo Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/basics/context.md This example demonstrates how to use both a global signal and a global memo within a component. The UI updates reactively as the global signal is modified. ```rust fn app() -> Element { rsx! { div { "count: {COUNT}" } div { "double: {DOUBLE_COUNT}" } button { onclick: move |_| *COUNT.write() += 1 } } } ``` -------------------------------- ### Handle Form Submissions in Dioxus 0.6 Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/migration/to-07.md In Dioxus 0.6, forms automatically prevented submission. This example shows the old behavior. ```rust rsx!( form { onsubmit: |e| {}, // Forms used to automatically not submit and reload the page input { name: "username", type: "text" }, button { type: "submit", "Submit" } } ) ``` -------------------------------- ### Dioxus 0.4 Fermi Atoms Example Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/migration/to-05-fermi.md Illustrates the usage of fermi atoms in Dioxus 0.4, including initialization and state updates. ```rust use dioxus::prelude::* use fermi::* static NAME: Atom = Atom(|_| "world".to_string()); static NAMES: AtomRef> = AtomRef(|_| vec!["world".to_string()]); fn app(cx: Scope) -> Element { use_init_atom_root(cx); let set_name = use_set(cx, &NAME); let names = use_atom_ref(cx, &NAMES); cx.render(rsx! { button { onclick: move |_| set_name("dioxus".to_string()), "reset name" } "{names.read():?}" }) } ``` -------------------------------- ### Fetching Dog Images with use_resource Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/basics/resources.md This example demonstrates fetching dog images based on a breed input. The `use_resource` hook subscribes to the `breed` signal, causing the fetch to re-run whenever the input changes. ```rust let mut breed = use_signal(|| "hound".to_string()); let dogs = use_resource(move || async move { reqwest::Client::new() // Since breed is read inside the async closure, the resource will subscribe to the signal // and rerun when the breed is written to .get(format!("https://dog.ceo/api/breed/{breed}/images")) .send() .await? .json::() .await }); rsx! { input { value: "{breed}", // When the input is changed and the breed is set, the resource will rerun oninput: move |evt| breed.set(evt.value()), } div { display: "flex", flex_direction: "row", // You can read resource just like a signal. If the resource is still // running, it will return None if let Some(response) = &*dogs.read() { match response { Ok(urls) => rsx! { for image in urls.iter().take(3) { img { src: "{image}", width: "100px", height: "100px", } } }, Err(err) => rsx! { "Failed to fetch response: {err}" }, } } else { "Loading..." } } } ``` -------------------------------- ### Dioxus.toml Configuration for Static Publishing Source: https://github.com/rustgrow/dioxus-context7-en/blob/main/essentials/fullstack/publishing.md Configure your `Dioxus.toml` file to set the output directory to `docs` and specify the `base_path` for your repository. This ensures that the build output is correctly placed for static hosting. ```toml [application] # ... out_dir = "docs" [web.app] base_path = "your_repo" ```