repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/logging.rs | examples/08-apis/logging.rs | //! Dioxus ships out-of-the-box with tracing hooks that integrate with the Dioxus-CLI.
//!
//! The built-in tracing-subscriber automatically sets up a wasm panic hook and wires up output
//! to be consumed in a machine-readable format when running under `dx`.
//!
//! You can disable the built-in tracing-subscriber or customize the log level yourself.
//!
//! By default:
//! - in `dev` mode, the default log output is `debug`
//! - in `release` mode, the default log output is `info`
//!
//! To use the dioxus logger in your app, simply call any of the tracing functions (info!(), warn!(), error!())
use dioxus::logger::tracing::{Level, debug, error, info, warn};
use dioxus::prelude::*;
fn main() {
// `dioxus::logger::init` is optional and called automatically by `dioxus::launch`.
// In development mode, the `Debug` tracing level is set, and in release only the `Info` level is set.
// You can call it yourself manually in the cases you:
// - want to customize behavior
// - aren't using `dioxus::launch` (i.e. custom fullstack setups) but want the integration.
// The Tracing crate is the logging interface that the dioxus-logger uses.
dioxus::logger::init(Level::INFO).expect("Failed to initialize logger");
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
div {
h1 { "Logger demo" }
button {
onclick: move |_| warn!("Here's a warning!"),
"Warn!"
}
button {
onclick: move |_| error!("Here's an error!"),
"Error!"
}
button {
onclick: move |_| {
debug!("Here's a debug");
warn!("The log level is set to info so there should not be a debug message")
},
"Debug!"
}
button {
onclick: move |_| info!("Here's an info!"),
"Info!"
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/ssr.rs | examples/08-apis/ssr.rs | //! Example: SSR
//!
//! This example shows how we can render the Dioxus Virtualdom using SSR.
//! Dioxus' SSR is quite comprehensive and can generate a number of utility markers for things like hydration.
//!
//! You can also render without any markers to get a clean HTML output.
use dioxus::prelude::*;
fn main() {
// We can render VirtualDoms
let vdom = VirtualDom::prebuilt(app);
println!("{}", dioxus_ssr::render(&vdom));
// Or we can render rsx! calls themselves
println!(
"{}",
dioxus_ssr::render_element(rsx! {
div {
h1 { "Hello, world!" }
}
})
);
// We can configure the SSR rendering to add ids for rehydration
println!("{}", dioxus_ssr::pre_render(&vdom));
// We can render to a buf directly too
let mut file = String::new();
let mut renderer = dioxus_ssr::Renderer::default();
renderer.render_to(&mut file, &vdom).unwrap();
println!("{file}");
}
fn app() -> Element {
rsx!(
div {
h1 { "Title" }
p { "Body" }
}
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/control_focus.rs | examples/08-apis/control_focus.rs | //! Managing focus
//!
//! This example shows how to manage focus in a Dioxus application. We implement a "roulette" that focuses on each input
//! in the grid every few milliseconds until the user interacts with the inputs.
use std::rc::Rc;
use async_std::task::sleep;
use dioxus::prelude::*;
const STYLE: Asset = asset!("/examples/assets/roulette.css");
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Element data is stored as Rc<MountedData> so we can clone it and pass it around
let mut elements = use_signal(Vec::<Rc<MountedData>>::new);
let mut running = use_signal(|| true);
use_future(move || async move {
let mut focused = 0;
loop {
sleep(std::time::Duration::from_millis(50)).await;
if !running() {
continue;
}
if let Some(element) = elements.with(|f| f.get(focused).cloned()) {
_ = element.set_focus(true).await;
} else {
focused = 0;
}
focused += 1;
}
});
rsx! {
Stylesheet { href: STYLE }
h1 { "Input Roulette" }
button { onclick: move |_| running.toggle(), "Toggle roulette" }
div { id: "roulette-grid",
// Restart the roulette if the user presses escape
onkeydown: move |event| {
if event.code().to_string() == "Escape" {
running.set(true);
}
},
// Draw the grid of inputs
for i in 0..100 {
input {
r#type: "number",
value: "{i}",
onmounted: move |cx| elements.push(cx.data()),
oninput: move |_| running.set(false),
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/scroll_to_top.rs | examples/08-apis/scroll_to_top.rs | //! Scroll elements using their MountedData
//!
//! Dioxus exposes a few helpful APIs around elements (mimicking the DOM APIs) to allow you to interact with elements
//! across the renderers. This includes scrolling, reading dimensions, and more.
//!
//! In this example we demonstrate how to scroll to the top of the page using the `scroll_to` method on the `MountedData`
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut header_element = use_signal(|| None);
rsx! {
div {
h1 {
onmounted: move |cx| header_element.set(Some(cx.data())),
"Scroll to top example"
}
for i in 0..100 {
div { "Item {i}" }
}
button {
onclick: move |_| async move {
if let Some(header) = header_element.cloned() {
header.scroll_to(ScrollBehavior::Smooth).await.unwrap();
}
},
"Scroll to top"
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/custom_html.rs | examples/08-apis/custom_html.rs | //! This example shows how to use a custom index.html and custom <HEAD> extensions
//! to add things like stylesheets, scripts, and third-party JS libraries.
use dioxus::prelude::*;
fn main() {
dioxus::LaunchBuilder::new()
.with_cfg(
dioxus::desktop::Config::new().with_custom_index(
r#"
<!DOCTYPE html>
<html>
<head>
<title>Dioxus app</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>body { background-color: olive; }</style>
</head>
<body>
<h1>External HTML</h1>
<div id="main"></div>
</body>
</html>
"#
.into(),
),
)
.launch(app);
}
fn app() -> Element {
rsx! {
h1 { "Custom HTML!" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/08-apis/video_stream.rs | examples/08-apis/video_stream.rs | //! Using `wry`'s http module, we can stream a video file from the local file system.
//!
//! You could load in any file type, but this example uses a video file.
use dioxus::desktop::wry::http;
use dioxus::desktop::wry::http::Response;
use dioxus::desktop::{AssetRequest, use_asset_handler};
use dioxus::prelude::*;
use http::{header::*, response::Builder as ResponseBuilder, status::StatusCode};
use std::{io::SeekFrom, path::PathBuf};
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
const VIDEO_PATH: &str = "./examples/assets/test_video.mp4";
fn main() {
// For the sake of this example, we will download the video file if it doesn't exist
ensure_video_is_loaded();
dioxus::launch(app);
}
fn app() -> Element {
// Any request to /videos will be handled by this handler
use_asset_handler("videos", move |request, responder| {
// Using spawn works, but is slower than a dedicated thread
tokio::task::spawn(async move {
let video_file = PathBuf::from(VIDEO_PATH);
let mut file = tokio::fs::File::open(&video_file).await.unwrap();
match get_stream_response(&mut file, &request).await {
Ok(response) => responder.respond(response),
Err(err) => eprintln!("Error: {}", err),
}
});
});
rsx! {
div {
video {
src: "/videos/test_video.mp4",
autoplay: true,
controls: true,
width: 640,
height: 480
}
}
}
}
/// This was taken from wry's example
async fn get_stream_response(
asset: &mut (impl tokio::io::AsyncSeek + tokio::io::AsyncRead + Unpin + Send + Sync),
request: &AssetRequest,
) -> Result<Response<Vec<u8>>, Box<dyn std::error::Error>> {
// get stream length
let len = {
let old_pos = asset.stream_position().await?;
let len = asset.seek(SeekFrom::End(0)).await?;
asset.seek(SeekFrom::Start(old_pos)).await?;
len
};
let mut resp = ResponseBuilder::new().header(CONTENT_TYPE, "video/mp4");
// if the webview sent a range header, we need to send a 206 in return
// Actually only macOS and Windows are supported. Linux will ALWAYS return empty headers.
let http_response = if let Some(range_header) = request.headers().get("range") {
let not_satisfiable = || {
ResponseBuilder::new()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(CONTENT_RANGE, format!("bytes */{len}"))
.body(vec![])
};
// parse range header
let ranges = if let Ok(ranges) = http_range::HttpRange::parse(range_header.to_str()?, len) {
ranges
.iter()
// map the output back to spec range <start-end>, example: 0-499
.map(|r| (r.start, r.start + r.length - 1))
.collect::<Vec<_>>()
} else {
return Ok(not_satisfiable()?);
};
/// The Maximum bytes we send in one range
const MAX_LEN: u64 = 1000 * 1024;
if ranges.len() == 1 {
let &(start, mut end) = ranges.first().unwrap();
// check if a range is not satisfiable
//
// this should be already taken care of by HttpRange::parse
// but checking here again for extra assurance
if start >= len || end >= len || end < start {
return Ok(not_satisfiable()?);
}
// adjust end byte for MAX_LEN
end = start + (end - start).min(len - start).min(MAX_LEN - 1);
// calculate number of bytes needed to be read
let bytes_to_read = end + 1 - start;
// allocate a buf with a suitable capacity
let mut buf = Vec::with_capacity(bytes_to_read as usize);
// seek the file to the starting byte
asset.seek(SeekFrom::Start(start)).await?;
// read the needed bytes
asset.take(bytes_to_read).read_to_end(&mut buf).await?;
resp = resp.header(CONTENT_RANGE, format!("bytes {start}-{end}/{len}"));
resp = resp.header(CONTENT_LENGTH, end + 1 - start);
resp = resp.status(StatusCode::PARTIAL_CONTENT);
resp.body(buf)
} else {
let mut buf = Vec::new();
let ranges = ranges
.iter()
.filter_map(|&(start, mut end)| {
// filter out unsatisfiable ranges
//
// this should be already taken care of by HttpRange::parse
// but checking here again for extra assurance
if start >= len || end >= len || end < start {
None
} else {
// adjust end byte for MAX_LEN
end = start + (end - start).min(len - start).min(MAX_LEN - 1);
Some((start, end))
}
})
.collect::<Vec<_>>();
let boundary = format!("{:x}", rand::random::<u64>());
let boundary_sep = format!("\r\n--{boundary}\r\n");
let boundary_closer = format!("\r\n--{boundary}\r\n");
resp = resp.header(
CONTENT_TYPE,
format!("multipart/byteranges; boundary={boundary}"),
);
for (end, start) in ranges {
// a new range is being written, write the range boundary
buf.write_all(boundary_sep.as_bytes()).await?;
// write the needed headers `Content-Type` and `Content-Range`
buf.write_all(format!("{CONTENT_TYPE}: video/mp4\r\n").as_bytes())
.await?;
buf.write_all(format!("{CONTENT_RANGE}: bytes {start}-{end}/{len}\r\n").as_bytes())
.await?;
// write the separator to indicate the start of the range body
buf.write_all("\r\n".as_bytes()).await?;
// calculate number of bytes needed to be read
let bytes_to_read = end + 1 - start;
let mut local_buf = vec![0_u8; bytes_to_read as usize];
asset.seek(SeekFrom::Start(start)).await?;
asset.read_exact(&mut local_buf).await?;
buf.extend_from_slice(&local_buf);
}
// all ranges have been written, write the closing boundary
buf.write_all(boundary_closer.as_bytes()).await?;
resp.body(buf)
}
} else {
resp = resp.header(CONTENT_LENGTH, len);
let mut buf = Vec::with_capacity(len as usize);
asset.read_to_end(&mut buf).await?;
resp.body(buf)
};
http_response.map_err(Into::into)
}
fn ensure_video_is_loaded() {
let video_file = PathBuf::from(VIDEO_PATH);
if !video_file.exists() {
tokio::runtime::Runtime::new()
.unwrap()
.block_on(async move {
println!("Downloading video file...");
let video_url =
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4";
let mut response = reqwest::get(video_url).await.unwrap();
let mut file = tokio::fs::File::create(&video_file).await.unwrap();
while let Some(chunk) = response.chunk().await.unwrap() {
file.write_all(&chunk).await.unwrap();
}
});
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/03-assets-styling/dynamic_assets.rs | examples/03-assets-styling/dynamic_assets.rs | //! This example shows how to load in custom assets with the use_asset_handler hook.
//!
//! This hook is currently only available on desktop and allows you to intercept any request made by the webview
//! and respond with your own data. You could use this to load in custom videos, streams, stylesheets, images,
//! or any asset that isn't known at compile time.
use dioxus::desktop::{use_asset_handler, wry::http::Response};
use dioxus::prelude::*;
const STYLE: Asset = asset!("/examples/assets/custom_assets.css");
fn main() {
dioxus::LaunchBuilder::desktop().launch(app);
}
fn app() -> Element {
use_asset_handler("logos", |request, response| {
// We get the original path - make sure you handle that!
if request.uri().path() != "/logos/logo.png" {
return;
}
response.respond(Response::new(include_bytes!("../assets/logo.png").to_vec()));
});
rsx! {
Stylesheet { href: STYLE }
h1 { "Dynamic Assets" }
img { src: "/logos/logo.png" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/03-assets-styling/meta_elements.rs | examples/03-assets-styling/meta_elements.rs | //! This example shows how to add metadata to the page with the Meta component
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
// You can use the Meta component to render a meta tag into the head of the page
// Meta tags are useful to provide information about the page to search engines and social media sites
// This example sets up meta tags for the open graph protocol for social media previews
Meta { property: "og:title", content: "My Site" }
Meta { property: "og:type", content: "website" }
Meta { property: "og:url", content: "https://www.example.com" }
Meta { property: "og:image", content: "https://example.com/image.jpg" }
Meta { name: "description", content: "My Site is a site" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/03-assets-styling/css_modules.rs | examples/03-assets-styling/css_modules.rs | //! This example shows how to use css modules with the `css_module` macro. Css modules convert css
//! class names to unique names to avoid class name collisions.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Each `css_module` macro will expand the annotated struct in the current scope
#[css_module("/examples/assets/css_module1.css")]
struct Styles;
#[css_module(
"/examples/assets/css_module2.css",
// `css_module` can take `AssetOptions` as well
AssetOptions::css_module()
.with_minify(true)
.with_preload(false)
)]
struct OtherStyles;
rsx! {
div { class: Styles::container,
div { class: OtherStyles::test, "Hello, world!" }
div { class: OtherStyles::highlight, "This is highlighted" }
div { class: Styles::global_class, "This uses a global class (no hash)" }
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/03-assets-styling/meta.rs | examples/03-assets-styling/meta.rs | //! This example shows how to add metadata to the page with the Meta component
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
// You can use the Meta component to render a meta tag into the head of the page
// Meta tags are useful to provide information about the page to search engines and social media sites
// This example sets up meta tags for the open graph protocol for social media previews
document::Meta {
property: "og:title",
content: "My Site",
}
document::Meta {
property: "og:type",
content: "website",
}
document::Meta {
property: "og:url",
content: "https://www.example.com",
}
document::Meta {
property: "og:image",
content: "https://example.com/image.jpg",
}
document::Meta {
name: "description",
content: "My Site is a site",
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/03-assets-styling/custom_assets.rs | examples/03-assets-styling/custom_assets.rs | //! A simple example on how to use assets loading from the filesystem.
//!
//! Dioxus provides the asset!() macro which is a convenient way to load assets from the filesystem.
//! This ensures the asset makes it into the bundle through dependencies and is accessible in environments
//! like web and android where assets are lazily loaded using platform-specific APIs.
use dioxus::prelude::*;
static ASSET_PATH: Asset = asset!("/examples/assets/logo.png");
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
div {
h1 { "This should show an image:" }
img { src: ASSET_PATH }
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/04-managing-state/reducer.rs | examples/04-managing-state/reducer.rs | //! Example: Reducer Pattern
//! -----------------
//!
//! This example shows how to encapsulate state in dioxus components with the reducer pattern.
//! This pattern is very useful when a single component can handle many types of input that can
//! be represented by an enum.
use dioxus::prelude::*;
const STYLE: Asset = asset!("/examples/assets/radio.css");
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut state = use_signal(|| PlayerState { is_playing: false });
rsx!(
Stylesheet { href: STYLE }
h1 {"Select an option"}
// Add some cute animations if the radio is playing!
div { class: if state.read().is_playing { "bounce" },
"The radio is... " {state.read().is_playing()} "!"
}
button { id: "play", onclick: move |_| state.write().reduce(PlayerAction::Pause), "Pause" }
button { id: "pause", onclick: move |_| state.write().reduce(PlayerAction::Play), "Play" }
)
}
enum PlayerAction {
Pause,
Play,
}
#[derive(Clone)]
struct PlayerState {
is_playing: bool,
}
impl PlayerState {
fn reduce(&mut self, action: PlayerAction) {
match action {
PlayerAction::Pause => self.is_playing = false,
PlayerAction::Play => self.is_playing = true,
}
}
fn is_playing(&self) -> &'static str {
match self.is_playing {
true => "currently playing!",
false => "not currently playing",
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/04-managing-state/global.rs | examples/04-managing-state/global.rs | //! Example: Global signals and memos
//!
//! This example demonstrates how to use global signals and memos to share state across your app.
//! Global signals are simply signals that live on the root of your app and are accessible from anywhere. To access a
//! global signal, simply use its methods like a regular signal. Calls to `read` and `write` will be forwarded to the
//! signal at the root of your app using the `static`'s address.
use dioxus::prelude::*;
const STYLE: Asset = asset!("/examples/assets/counter.css");
static COUNT: GlobalSignal<i32> = Signal::global(|| 0);
static DOUBLED_COUNT: GlobalMemo<i32> = Memo::global(|| COUNT() * 2);
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
Stylesheet { href: STYLE }
Increment {}
Decrement {}
Reset {}
Display {}
}
}
#[component]
fn Increment() -> Element {
rsx! {
button { onclick: move |_| *COUNT.write() += 1, "Up high!" }
}
}
#[component]
fn Decrement() -> Element {
rsx! {
button { onclick: move |_| *COUNT.write() -= 1, "Down low!" }
}
}
#[component]
fn Display() -> Element {
rsx! {
p { "Count: {COUNT}" }
p { "Doubled: {DOUBLED_COUNT}" }
}
}
#[component]
fn Reset() -> Element {
// Not all write methods are available on global signals since `write` requires a mutable reference. In these cases,
// We can simply pull out the actual signal using the signal() method.
let mut as_signal = use_hook(|| COUNT.resolve());
rsx! {
button { onclick: move |_| as_signal.set(0), "Reset" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/04-managing-state/memo_chain.rs | examples/04-managing-state/memo_chain.rs | //! This example shows how you can chain memos together to create a tree of memoized values.
//!
//! Memos will also pause when their parent component pauses, so if you have a memo that depends on a signal, and the
//! signal pauses, the memo will pause too.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut value = use_signal(|| 0);
let mut depth = use_signal(|| 0_usize);
let items = use_memo(move || (0..depth()).map(|f| f as _).collect::<Vec<isize>>());
let state = use_memo(move || value() + 1);
println!("rendering app");
rsx! {
button { onclick: move |_| value += 1, "Increment" }
button { onclick: move |_| depth += 1, "Add depth" }
button { onclick: move |_| depth -= 1, "Remove depth" }
if depth() > 0 {
Child { depth, items, state }
}
}
}
#[component]
fn Child(state: Memo<isize>, items: Memo<Vec<isize>>, depth: ReadSignal<usize>) -> Element {
// These memos don't get re-computed when early returns happen
let state = use_memo(move || state() + 1);
let item = use_memo(move || items()[depth() - 1]);
let depth = use_memo(move || depth() - 1);
println!("rendering child: {}", depth());
rsx! {
h3 { "Depth({depth})-Item({item}): {state}"}
if depth() > 0 {
Child { depth, state, items }
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/04-managing-state/error_handling.rs | examples/04-managing-state/error_handling.rs | //! This example showcases how to use the ErrorBoundary component to handle errors in your app.
//!
//! The ErrorBoundary component is a special component that can be used to catch panics and other errors that occur.
//! By default, Dioxus will catch panics during rendering, async, and handlers, and bubble them up to the nearest
//! error boundary. If no error boundary is present, it will be caught by the root error boundary and the app will
//! render the error message as just a string.
//!
//! NOTE: In wasm, panics can currently not be caught by the error boundary. This is a limitation of WASM in rust.
#![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
dioxus::launch(|| rsx! { Router::<Route> {} });
}
/// You can use an ErrorBoundary to catch errors in children and display a warning
fn Simple() -> Element {
rsx! {
GoBackButton { "Home" }
ErrorBoundary {
handle_error: |error: ErrorContext| rsx! {
h1 { "An error occurred" }
pre { "{error:#?}" }
},
ParseNumber {}
}
}
}
#[component]
fn ParseNumber() -> Element {
rsx! {
h1 { "Error handler demo" }
button {
onclick: move |_| {
// You can return a result from an event handler which lets you easily quit rendering early if something fails
let data: i32 = "0.5".parse()?;
println!("parsed {data}");
Ok(())
},
"Click to throw an error"
}
}
}
// You can provide additional context for the Error boundary to visualize
fn Show() -> Element {
rsx! {
GoBackButton { "Home" }
div {
ErrorBoundary {
handle_error: |errors: ErrorContext| {
rsx! {
for error in errors.error() {
// You can downcast the error to see if it's a specific type and render something specific for it
if let Some(_error) = error.downcast_ref::<std::num::ParseIntError>() {
div {
background_color: "red",
border: "black",
border_width: "2px",
border_radius: "5px",
p { "Failed to parse data" }
Link {
to: Route::Home {},
"Go back to the homepage"
}
}
} else {
pre {
color: "red",
"{error}"
}
}
}
}
},
ParseNumberWithShow {}
}
}
}
}
#[component]
fn ParseNumberWithShow() -> Element {
rsx! {
h1 { "Error handler demo" }
button {
onclick: move |_| {
let request_data = "0.5";
let data: i32 = request_data.parse()?;
println!("parsed {data}");
Ok(())
},
"Click to throw an error"
}
}
}
// On desktop, dioxus will catch panics in components and insert an error automatically
fn Panic() -> Element {
rsx! {
GoBackButton { "Home" }
ErrorBoundary {
handle_error: |errors: ErrorContext| rsx! {
h1 { "Another error occurred" }
pre { "{errors:#?}" }
},
ComponentPanic {}
}
}
}
#[component]
fn ComponentPanic() -> Element {
panic!("This component panics")
}
#[derive(Routable, Clone, Debug, PartialEq)]
enum Route {
#[route("/")]
Home {},
#[route("/simple")]
Simple {},
#[route("/panic")]
Panic {},
#[route("/show")]
Show {},
}
fn Home() -> Element {
rsx! {
ul {
li {
Link {
to: Route::Simple {},
"Simple errors"
}
}
li {
Link {
to: Route::Panic {},
"Capture panics"
}
}
li {
Link {
to: Route::Show {},
"Show errors"
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/04-managing-state/context_api.rs | examples/04-managing-state/context_api.rs | //! Demonstrates cross-component state sharing using Dioxus' Context API
//!
//! Features:
//! - Context provider initialization
//! - Nested component consumption
//! - Reactive state updates
//! - Error handling for missing context
//! - Platform-agnostic implementation
use dioxus::prelude::*;
const STYLE: Asset = asset!("/examples/assets/context_api.css");
fn main() {
launch(app);
}
#[component]
fn app() -> Element {
// Provide theme context at root level
use_context_provider(|| Signal::new(Theme::Light));
rsx! {
Stylesheet { href: STYLE }
main {
class: "main-container",
h1 { "Theme Switcher" }
ThemeControls {}
ThemeDisplay {}
}
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Theme {
Light,
Dark,
}
impl Theme {
fn stylesheet(&self) -> &'static str {
match self {
Theme::Light => "light-theme",
Theme::Dark => "dark-theme",
}
}
}
#[component]
fn ThemeControls() -> Element {
let mut theme = use_theme_context();
let current_theme = *theme.read();
rsx! {
div {
class: "controls",
button {
class: "btn",
onclick: move |_| theme.set(Theme::Light),
disabled: current_theme== Theme::Light,
"Switch to Light"
}
button {
class: "btn",
onclick: move |_| theme.set(Theme::Dark),
disabled: current_theme == Theme::Dark,
"Switch to Dark"
}
}
}
}
#[component]
fn ThemeDisplay() -> Element {
let theme = use_theme_context();
rsx! {
div {
class: "display {theme.read().stylesheet()}",
p { "Current theme: {theme:?}" }
p { "Try switching themes using the buttons above!" }
}
}
}
fn use_theme_context() -> Signal<Theme> {
try_use_context::<Signal<Theme>>()
.expect("Theme context not found. Ensure <App> is the root component.")
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/04-managing-state/signals.rs | examples/04-managing-state/signals.rs | //! A simple example demonstrating how to use signals to modify state from several different places.
//!
//! This simple example implements a counter that can be incremented, decremented, and paused. It also demonstrates
//! that background tasks in use_futures can modify the value as well.
//!
//! Most signals implement Into<ReadSignal<T>>, making ReadSignal a good default type when building new
//! library components that don't need to modify their values.
use async_std::task::sleep;
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut running = use_signal(|| true);
let mut count = use_signal(|| 0);
let mut saved_values = use_signal(|| vec![0.to_string()]);
// use_memo will recompute the value of the signal whenever the captured signals change
let doubled_count = use_memo(move || count() * 2);
// use_effect will subscribe to any changes in the signal values it captures
// effects will always run after first mount and then whenever the signal values change
use_effect(move || println!("Count changed to {count}"));
// We can do early returns and conditional rendering which will pause all futures that haven't been polled
if count() > 30 {
return rsx! {
h1 { "Count is too high!" }
button { onclick: move |_| count.set(0), "Press to reset" }
};
}
// use_future will spawn an infinitely running future that can be started and stopped
use_future(move || async move {
loop {
if running() {
count += 1;
}
sleep(std::time::Duration::from_millis(400)).await;
}
});
// use_resource will spawn a future that resolves to a value
let _slow_count = use_resource(move || async move {
sleep(std::time::Duration::from_millis(200)).await;
count() * 2
});
rsx! {
h1 { "High-Five counter: {count}" }
button { onclick: move |_| count += 1, "Up high!" }
button { onclick: move |_| count -= 1, "Down low!" }
button { onclick: move |_| running.toggle(), "Toggle counter" }
button { onclick: move |_| saved_values.push(count.to_string()), "Save this value" }
button { onclick: move |_| saved_values.clear(), "Clear saved values" }
// We can do boolean operations on the current signal value
if count() > 5 {
h2 { "High five!" }
}
// We can cleanly map signals with iterators
for value in saved_values.iter() {
h3 { "Saved value: {value}" }
}
// We can also use the signal value as a slice
if let [first, .., last] = saved_values.read().as_slice() {
li { "First and last: {first}, {last}" }
} else {
"No saved values"
}
// You can pass a value directly to any prop that accepts a signal
Child { count: doubled_count() }
Child { count: doubled_count }
}
}
#[component]
fn Child(mut count: ReadSignal<i32>) -> Element {
println!("rendering child with count {count}");
rsx! {
h1 { "{count}" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/todomvc_store.rs | examples/01-app-demos/todomvc_store.rs | //! The typical TodoMVC app, implemented in Dioxus with stores. Stores let us
//! share nested reactive state between components. They let us keep our todomvc
//! state in a single struct without wrapping every type in a signal while still
//! maintaining fine grained reactivity.
use dioxus::prelude::*;
use std::{collections::HashMap, vec};
const STYLE: Asset = asset!("/examples/assets/todomvc.css");
/// Deriving the store macro on a struct will automatically generate an extension trait
/// for Store<TodoState> with method to zoom into the fields of the struct.
///
/// For this struct, the macro derives the following methods for Store<TodoState>:
/// - `todos(self) -> Store<HashMap<u32, TodoItem>, _>`
/// - `filter(self) -> Store<FilterState, _>`
#[derive(Store, PartialEq, Clone, Debug)]
struct TodoState {
todos: HashMap<u32, TodoItem>,
filter: FilterState,
}
// We can also add custom methods to the store by using the `store` attribute on an impl block.
// The store attribute turns the impl block into an extension trait for Store<TodoState>.
// Methods that take &self will automatically get a bound that Lens: Readable<Target = TodoState>
// Methods that take &mut self will automatically get a bound that Lens: Writable<Target = TodoState>
#[store]
impl<Lens> Store<TodoState, Lens> {
fn active_items(&self) -> Vec<u32> {
let filter = self.filter().cloned();
let mut active_ids: Vec<u32> = self
.todos()
.iter()
.filter_map(|(id, item)| item.active(filter).then_some(id))
.collect();
active_ids.sort_unstable();
active_ids
}
fn incomplete_count(&self) -> usize {
self.todos()
.values()
.filter(|item| item.incomplete())
.count()
}
fn toggle_all(&mut self) {
let check = self.incomplete_count() != 0;
for item in self.todos().values() {
item.checked().set(check);
}
}
fn has_todos(&self) -> bool {
!self.todos().is_empty()
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum FilterState {
All,
Active,
Completed,
}
#[derive(Store, PartialEq, Clone, Debug)]
struct TodoItem {
checked: bool,
contents: String,
}
impl TodoItem {
fn new(contents: impl ToString) -> Self {
Self {
checked: false,
contents: contents.to_string(),
}
}
}
#[store]
impl<Lens> Store<TodoItem, Lens> {
fn complete(&self) -> bool {
self.checked().cloned()
}
fn incomplete(&self) -> bool {
!self.complete()
}
fn active(&self, filter: FilterState) -> bool {
match filter {
FilterState::All => true,
FilterState::Active => self.incomplete(),
FilterState::Completed => self.complete(),
}
}
}
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// We store the state of our todo list in a store to use throughout the app.
let mut todos = use_store(|| TodoState {
todos: HashMap::new(),
filter: FilterState::All,
});
// We use a simple memo to calculate the number of active todos.
// Whenever the todos change, the active_todo_count will be recalculated.
let active_todo_count = use_memo(move || todos.incomplete_count());
// We use a memo to filter the todos based on the current filter state.
// Whenever the todos or filter change, the filtered_todos will be recalculated.
// Note that we're only storing the IDs of the todos, not the todos themselves.
let filtered_todos = use_memo(move || todos.active_items());
// Toggle all the todos to the opposite of the current state.
// If all todos are checked, uncheck them all. If any are unchecked, check them all.
let toggle_all = move |_| {
todos.toggle_all();
};
rsx! {
Stylesheet { href: STYLE }
section { class: "todoapp",
TodoHeader { todos }
section { class: "main",
if todos.has_todos() {
input {
id: "toggle-all",
class: "toggle-all",
r#type: "checkbox",
onchange: toggle_all,
checked: active_todo_count() == 0
}
label { r#for: "toggle-all" }
}
// Render the todos using the filtered_todos memo
// We pass the ID along with the hashmap into the TodoEntry component so it can access the todo from the todos store.
ul { class: "todo-list",
for id in filtered_todos() {
TodoEntry { key: "{id}", id, todos }
}
}
// We only show the footer if there are todos.
if todos.has_todos() {
ListFooter { active_todo_count, todos }
}
}
}
// A simple info footer
footer { class: "info",
p { "Double-click to edit a todo" }
p {
"Created by "
a { href: "http://github.com/jkelleyrtp/", "jkelleyrtp" }
}
p {
"Part of "
a { href: "http://todomvc.com", "TodoMVC" }
}
}
}
}
#[component]
fn TodoHeader(mut todos: Store<TodoState>) -> Element {
let mut draft = use_signal(|| "".to_string());
let mut todo_id = use_signal(|| 0);
let onkeydown = move |evt: KeyboardEvent| {
if evt.key() == Key::Enter && !draft.is_empty() {
let id = todo_id();
let todo = TodoItem::new(draft.take());
todos.todos().insert(id, todo);
todo_id += 1;
}
};
rsx! {
header { class: "header",
h1 { "todos" }
input {
class: "new-todo",
placeholder: "What needs to be done?",
value: "{draft}",
autofocus: "true",
oninput: move |evt| draft.set(evt.value()),
onkeydown
}
}
}
}
/// A single todo entry
/// This takes the ID of the todo and the todos store as props
/// We can use these together to memoize the todo contents and checked state
#[component]
fn TodoEntry(mut todos: Store<TodoState>, id: u32) -> Element {
let mut is_editing = use_signal(|| false);
// When we get an item out of the store, it will only subscribe to that specific item.
// Since we only get the single todo item, the component will only rerender when that item changes.
let entry = todos.todos().get(id).unwrap();
let checked = entry.checked();
let contents = entry.contents();
rsx! {
li {
// Dioxus lets you use if statements in rsx to conditionally render attributes
// These will get merged into a single class attribute
class: if checked() { "completed" },
class: if is_editing() { "editing" },
// Some basic controls for the todo
div { class: "view",
input {
class: "toggle",
r#type: "checkbox",
id: "cbg-{id}",
checked: "{checked}",
oninput: move |evt| entry.checked().set(evt.checked())
}
label {
r#for: "cbg-{id}",
ondoubleclick: move |_| is_editing.set(true),
onclick: |evt| evt.prevent_default(),
"{contents}"
}
button {
class: "destroy",
onclick: move |evt| {
evt.prevent_default();
todos.todos().remove(&id);
},
}
}
// Only render the actual input if we're editing
if is_editing() {
input {
class: "edit",
value: "{contents}",
oninput: move |evt| entry.contents().set(evt.value()),
autofocus: "true",
onfocusout: move |_| is_editing.set(false),
onkeydown: move |evt| {
match evt.key() {
Key::Enter | Key::Escape | Key::Tab => is_editing.set(false),
_ => {}
}
}
}
}
}
}
}
#[component]
fn ListFooter(mut todos: Store<TodoState>, active_todo_count: ReadSignal<usize>) -> Element {
// We use a memo to calculate whether we should show the "Clear completed" button.
// This will recompute whenever the number of todos change or the checked state of an existing
// todo changes
let show_clear_completed = use_memo(move || todos.todos().values().any(|todo| todo.complete()));
let mut filter = todos.filter();
rsx! {
footer { class: "footer",
span { class: "todo-count",
strong { "{active_todo_count} " }
span {
match active_todo_count() {
1 => "item",
_ => "items",
}
" left"
}
}
ul { class: "filters",
for (state , state_text , url) in [
(FilterState::All, "All", "#/"),
(FilterState::Active, "Active", "#/active"),
(FilterState::Completed, "Completed", "#/completed"),
] {
li {
a {
href: url,
class: if filter() == state { "selected" },
onclick: move |evt| {
evt.prevent_default();
filter.set(state)
},
{state_text}
}
}
}
}
if show_clear_completed() {
button {
class: "clear-completed",
onclick: move |_| todos.todos().retain(|_, todo| !todo.checked),
"Clear completed"
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/repo_readme.rs | examples/01-app-demos/repo_readme.rs | //! The example from the readme!
//!
//! This example demonstrates how to create a simple counter app with dioxus. The `Signal` type wraps inner values,
//! making them `Copy`, allowing them to be freely used in closures and async functions. `Signal` also provides
//! helper methods like AddAssign, SubAssign, toggle, etc, to make it easy to update the value without running
//! into lock issues.
use dioxus::prelude::*;
fn main() {
dioxus::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!" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/hello_world.rs | examples/01-app-demos/hello_world.rs | //! The simplest example of a Dioxus app.
//!
//! In this example we:
//! - import a number of important items from the prelude (launch, Element, rsx, div, etc.)
//! - define a main function that calls the launch function with our app function
//! - define an app function that returns a div element with the text "Hello, world!"
//!
//! The `launch` function is the entry point for all Dioxus apps. It takes a function that returns an Element. This function
//! calls "launch" on the currently-configured renderer you have. So if the `web` feature is enabled, it will launch a web
//! app, and if the `desktop` feature is enabled, it will launch a desktop app.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
div { "Hello, world!" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/calculator_mutable.rs | examples/01-app-demos/calculator_mutable.rs | //! This example showcases a simple calculator using an approach to state management where the state is composed of only
//! a single signal. Since Dioxus implements traditional React diffing, state can be consolidated into a typical Rust struct
//! with methods that take `&mut self`. For many use cases, this is a simple way to manage complex state without wrapping
//! everything in a signal.
//!
//! Generally, you'll want to split your state into several signals if you have a large application, but for small
//! applications, or focused components, this is a great way to manage state.
use dioxus::desktop::tao::dpi::LogicalSize;
use dioxus::desktop::{Config, WindowBuilder};
use dioxus::html::MouseEvent;
use dioxus::html::input_data::keyboard_types::Key;
use dioxus::prelude::*;
fn main() {
dioxus::LaunchBuilder::desktop()
.with_cfg(
Config::new().with_window(
WindowBuilder::new()
.with_title("Calculator Demo")
.with_resizable(false)
.with_inner_size(LogicalSize::new(320.0, 530.0)),
),
)
.launch(app);
}
fn app() -> Element {
let mut state = use_signal(Calculator::new);
rsx! {
Stylesheet { href: asset!("/examples/assets/calculator.css") }
div { id: "wrapper",
div { class: "app",
div {
class: "calculator",
onkeypress: move |evt| state.write().handle_keydown(evt),
div { class: "calculator-display", {state.read().formatted_display()} }
div { class: "calculator-keypad",
div { class: "input-keys",
div { class: "function-keys",
CalculatorKey {
name: "key-clear",
onclick: move |_| state.write().clear_display(),
if state.read().display_value == "0" {
"C"
} else {
"AC"
}
}
CalculatorKey {
name: "key-sign",
onclick: move |_| state.write().toggle_sign(),
"±"
}
CalculatorKey {
name: "key-percent",
onclick: move |_| state.write().toggle_percent(),
"%"
}
}
div { class: "digit-keys",
CalculatorKey {
name: "key-0",
onclick: move |_| state.write().input_digit(0),
"0"
}
CalculatorKey {
name: "key-dot",
onclick: move |_| state.write().input_dot(),
"●"
}
for k in 1..10 {
CalculatorKey {
key: "{k}",
name: "key-{k}",
onclick: move |_| state.write().input_digit(k),
"{k}"
}
}
}
}
div { class: "operator-keys",
CalculatorKey {
name: "key-divide",
onclick: move |_| state.write().set_operator(Operator::Div),
"÷"
}
CalculatorKey {
name: "key-multiply",
onclick: move |_| state.write().set_operator(Operator::Mul),
"×"
}
CalculatorKey {
name: "key-subtract",
onclick: move |_| state.write().set_operator(Operator::Sub),
"−"
}
CalculatorKey {
name: "key-add",
onclick: move |_| state.write().set_operator(Operator::Add),
"+"
}
CalculatorKey {
name: "key-equals",
onclick: move |_| state.write().perform_operation(),
"="
}
}
}
}
}
}
}
}
#[component]
fn CalculatorKey(name: String, onclick: EventHandler<MouseEvent>, children: Element) -> Element {
rsx! {
button { class: "calculator-key {name}", onclick, {children} }
}
}
struct Calculator {
display_value: String,
operator: Option<Operator>,
waiting_for_operand: bool,
cur_val: f64,
}
#[derive(Clone)]
enum Operator {
Add,
Sub,
Mul,
Div,
}
impl Calculator {
fn new() -> Self {
Calculator {
display_value: "0".to_string(),
operator: None,
waiting_for_operand: false,
cur_val: 0.0,
}
}
fn formatted_display(&self) -> String {
use separator::Separatable;
self.display_value
.parse::<f64>()
.unwrap()
.separated_string()
}
fn clear_display(&mut self) {
self.display_value = "0".to_string();
}
fn input_digit(&mut self, digit: u8) {
let content = digit.to_string();
if self.waiting_for_operand || self.display_value == "0" {
self.waiting_for_operand = false;
self.display_value = content;
} else {
self.display_value.push_str(content.as_str());
}
}
fn input_dot(&mut self) {
if !self.display_value.contains('.') {
self.display_value.push('.');
}
}
fn perform_operation(&mut self) {
if let Some(op) = &self.operator {
let rhs = self.display_value.parse::<f64>().unwrap();
let new_val = match op {
Operator::Add => self.cur_val + rhs,
Operator::Sub => self.cur_val - rhs,
Operator::Mul => self.cur_val * rhs,
Operator::Div => self.cur_val / rhs,
};
self.cur_val = new_val;
self.display_value = new_val.to_string();
self.operator = None;
}
}
fn toggle_sign(&mut self) {
if self.display_value.starts_with('-') {
self.display_value = self.display_value.trim_start_matches('-').to_string();
} else {
self.display_value = format!("-{}", self.display_value);
}
}
fn toggle_percent(&mut self) {
self.display_value = (self.display_value.parse::<f64>().unwrap() / 100.0).to_string();
}
fn backspace(&mut self) {
if !self.display_value.as_str().eq("0") {
self.display_value.pop();
}
}
fn set_operator(&mut self, operator: Operator) {
self.operator = Some(operator);
self.cur_val = self.display_value.parse::<f64>().unwrap();
self.waiting_for_operand = true;
}
fn handle_keydown(&mut self, evt: KeyboardEvent) {
match evt.key() {
Key::Backspace => self.backspace(),
Key::Character(c) => match c.as_str() {
"0" => self.input_digit(0),
"1" => self.input_digit(1),
"2" => self.input_digit(2),
"3" => self.input_digit(3),
"4" => self.input_digit(4),
"5" => self.input_digit(5),
"6" => self.input_digit(6),
"7" => self.input_digit(7),
"8" => self.input_digit(8),
"9" => self.input_digit(9),
"+" => self.operator = Some(Operator::Add),
"-" => self.operator = Some(Operator::Sub),
"/" => self.operator = Some(Operator::Div),
"*" => self.operator = Some(Operator::Mul),
_ => {}
},
_ => {}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/websocket_chat.rs | examples/01-app-demos/websocket_chat.rs | //! A websocket chat demo using Dioxus' built-in websocket support.
//!
//! We setup an endpoint at `/api/chat` that accepts a `name` and `user_id` query parameter.
//! Each client connects to that endpoint, and we use a `tokio::broadcast` channel
//! to send messages to all connected clients.
//!
//! In practice, you'd use a distributed messaging system (Redis PubSub / Kafka / etc) to coordinate
//! between multiple server instances and an additional database to persist chat history.
use dioxus::fullstack::{WebSocketOptions, Websocket, use_websocket};
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// store the user's current input
let mut input = use_signal(|| "".to_string());
// Select a unique id for the user, and then use that entropy to pick a random name
let user_id = use_signal(uuid::Uuid::new_v4);
let user_name = use_signal(|| {
match user_id.read().as_bytes()[0] % 7 {
0 => "Alice",
1 => "Bob",
2 => "Eve",
3 => "Mallory",
4 => "Trent",
5 => "Peggy",
6 => "Victor",
_ => "Charlie",
}
.to_string()
});
// Store the messages we've received from the server
let mut message_list = use_signal(Vec::<ChatMessage>::new);
// Connect to the websocket endpoint
let mut socket =
use_websocket(move || uppercase_ws(user_name(), user_id(), Default::default()));
use_future(move || async move {
while let Ok(msg) = socket.recv().await {
match msg {
ServerEvent::ReceiveMessage(message) => message_list.push(message),
ServerEvent::Connected { messages } => message_list.set(messages),
}
}
});
rsx! {
h1 { "WebSocket Chat" }
p { "Connection status: {socket.status():?} as {user_name}" }
input {
placeholder: "Type a message",
value: "{input}",
oninput: move |e| async move { input.set(e.value()) },
onkeydown: move |e| async move {
if e.key() == Key::Enter {
_ = socket.send(ClientEvent::SendMessage(input.read().clone())).await;
input.set("".to_string());
}
}
}
div {
for message in message_list.read().iter().rev() {
pre { "{message.name}: {message.message}" }
}
}
}
}
/// The events that the client can send to the server
#[derive(Serialize, Deserialize, Debug)]
enum ClientEvent {
SendMessage(String),
}
/// The events that the server can send to the client
#[derive(Serialize, Deserialize, Debug)]
enum ServerEvent {
Connected { messages: Vec<ChatMessage> },
ReceiveMessage(ChatMessage),
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
struct ChatMessage {
user_id: Uuid,
name: String,
message: String,
}
#[get("/api/chat?name&user_id")]
async fn uppercase_ws(
name: String,
user_id: Uuid,
options: WebSocketOptions,
) -> Result<Websocket<ClientEvent, ServerEvent>> {
use std::sync::LazyLock;
use tokio::sync::{
Mutex,
broadcast::{self, Sender},
};
// Every chat app needs a chat room! For this demo, we just use a tokio broadcast channel and a mutex-protected
// list of messages to store chat history.
//
// We place these types in the body of this serverfn since they're not used on the client, only the server.
static MESSAGES: LazyLock<Mutex<Vec<ChatMessage>>> = LazyLock::new(|| Mutex::new(Vec::new()));
static BROADCAST: LazyLock<Sender<ChatMessage>> = LazyLock::new(|| broadcast::channel(100).0);
Ok(options.on_upgrade(move |mut socket| async move {
// Send back all the messages from the room to the new client
let messages = MESSAGES.lock().await.clone();
_ = socket.send(ServerEvent::Connected { messages }).await;
// Subscriber to the broadcast channel
let sender = BROADCAST.clone();
let mut broadcast = sender.subscribe();
// Announce that we've joined
let _ = sender.send(ChatMessage {
message: format!("{name} has connected."),
user_id,
name: "[CONSOLE]".to_string(),
});
// Loop poll the broadcast receiver and the websocket for new messages
// If we receive a message from the broadcast channel, send it to the client
// If we receive a message from the client, broadcast it to all other clients and save it to the message list
loop {
tokio::select! {
Ok(msg) = broadcast.recv() => {
let _ = socket.send(ServerEvent::ReceiveMessage(msg)).await;
}
Ok(ClientEvent::SendMessage(message)) = socket.recv() => {
let chat_message = ChatMessage {
user_id,
name: name.clone(),
message,
};
let _ = sender.send(chat_message.clone());
MESSAGES.lock().await.push(chat_message.clone());
},
else => break,
}
}
_ = sender.send(ChatMessage {
name: "[CONSOLE]".to_string(),
message: format!("{name} has disconnected."),
user_id,
});
}))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/weather_app.rs | examples/01-app-demos/weather_app.rs | #![allow(non_snake_case)]
use dioxus::{fullstack::Loading, prelude::*};
use serde::{Deserialize, Serialize};
use std::fmt::Display;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let country = use_signal(|| WeatherLocation {
name: "Berlin".to_string(),
country: "Germany".to_string(),
latitude: 52.5244,
longitude: 13.4105,
id: 2950159,
});
let current_weather = use_loader(move || get_weather(country()));
rsx! {
Stylesheet { href: asset!("/examples/assets/weatherapp.css") }
div { class: "mx-auto p-4 bg-gray-100 h-screen flex justify-center",
div { class: "flex items-center justify-center flex-row",
div { class: "flex items-start justify-center flex-row",
SearchBox { country }
div { class: "flex flex-wrap w-full px-2",
div { class: "bg-gray-900 text-white relative min-w-0 break-words rounded-lg overflow-hidden shadow-sm mb-4 w-full dark:bg-gray-600",
div { class: "px-6 py-6 relative",
match current_weather {
Ok(weather) => rsx! {
CountryData {
country: country.read().clone(),
weather: weather.cloned(),
}
Forecast { weather: weather.cloned() }
div { height: "20px", margin_top: "10px",
if weather.loading() {
"Fetching weather data..."
}
}
},
Err(Loading::Pending(_)) => rsx! {
div { "Loading weather data..." }
},
Err(Loading::Failed(_)) => rsx! {
div { "Failed to load weather data." }
}
}
}
}
}
}
}
}
}
}
#[allow(non_snake_case)]
#[component]
fn CountryData(weather: WeatherResponse, country: WeatherLocation) -> Element {
let today = "Today";
let max_temp = weather.daily.temperature_2m_max[0];
let min_temp = weather.daily.temperature_2m_min[0];
rsx! {
div { class: "flex mb-4 justify-between items-center",
div {
h5 { class: "mb-0 font-medium text-xl", "{country.name} 🏞️" }
h6 { class: "mb-0", "{today}" }
}
div {
div { class: "flex items-center",
span { "Temp min" }
span { class: "px-2 inline-block", "👉 {min_temp}°" }
}
div { class: "flex items-center",
span { "Temp max" }
span { class: "px-2 inline-block ", "👉 {max_temp}º" }
}
}
}
}
}
#[allow(non_snake_case)]
#[component]
fn Forecast(weather: WeatherResponse) -> Element {
let today = (weather.daily.temperature_2m_max[0] + weather.daily.temperature_2m_max[0]) / 2.0;
let tomorrow =
(weather.daily.temperature_2m_max[1] + weather.daily.temperature_2m_max[1]) / 2.0;
let past_tomorrow =
(weather.daily.temperature_2m_max[2] + weather.daily.temperature_2m_max[2]) / 2.0;
rsx! {
div { class: "px-6 pt-4 relative",
div { class: "w-full h-px bg-gray-100 mb-4" }
div { p { class: "text-center w-full mb-4", "👇 Forecast 📆" } }
div { class: "text-center justify-between items-center flex",
div { class: "text-center mb-0 flex items-center justify-center flex-col mx-4 w-16",
span { class: "block my-1", "Today" }
span { class: "block my-1", "{today}°" }
}
div { class: "text-center mb-0 flex items-center justify-center flex-col mx-8 w-16",
span { class: "block my-1", "Tomorrow" }
span { class: "block my-1", "{tomorrow}°" }
}
div { class: "text-center mb-0 flex items-center justify-center flex-col mx-2 w-30",
span { class: "block my-1", "Past Tomorrow" }
span { class: "block my-1", "{past_tomorrow}°" }
}
}
}
}
}
#[component]
fn SearchBox(mut country: WriteSignal<WeatherLocation>) -> Element {
let mut input = use_signal(|| "".to_string());
let locations = use_loader(move || get_locations(input()));
rsx! {
div {
div { class: "inline-flex flex-col justify-center relative text-gray-500",
div { class: "relative",
input {
class: "p-2 pl-8 rounded-lg border border-gray-200 bg-gray-200 focus:bg-white focus:outline-none focus:ring-2 focus:ring-yellow-600 focus:border-transparent",
placeholder: "Country name",
"type": "text",
autofocus: true,
oninput: move |e: FormEvent| input.set(e.value())
}
svg {
class: "w-4 h-4 absolute left-2.5 top-3.5",
"viewBox": "0 0 24 24",
fill: "none",
stroke: "currentColor",
xmlns: "http://www.w3.org/2000/svg",
path {
d: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z",
"stroke-linejoin": "round",
"stroke-linecap": "round",
"stroke-width": "2"
}
}
}
ul { class: "bg-white border border-gray-100 w-full mt-2 max-h-72 overflow-auto",
match locations {
Ok(locs) if locs.is_empty() => rsx! {
li { class: "pl-8 pr-2 py-1 border-b-2 border-gray-100 relative",
"No locations found"
}
},
Ok(locs) => rsx! {
for wl in locs.read().iter().take(5).cloned() {
li { class: "pl-8 pr-2 py-1 border-b-2 border-gray-100 relative cursor-pointer hover:bg-yellow-50 hover:text-gray-900",
onclick: move |_| country.set(wl.clone()),
MapIcon {}
b { "{wl.name}" }
" · {wl.country}"
}
}
},
Err(Loading::Pending(_)) => rsx! {
li { class: "pl-8 pr-2 py-1 border-b-2 border-gray-100 relative",
"Searching..."
}
},
Err(Loading::Failed(handle)) => rsx! {
li { class: "pl-8 pr-2 py-1 border-b-2 border-gray-100 relative",
"Failed to search: {handle.error():?}"
}
}
}
}
}
}
}
}
fn MapIcon() -> Element {
rsx! {
svg {
class: "stroke-current absolute w-4 h-4 left-2 top-2",
stroke: "currentColor",
xmlns: "http://www.w3.org/2000/svg",
"viewBox": "0 0 24 24",
fill: "none",
path {
"stroke-linejoin": "round",
"stroke-width": "2",
"stroke-linecap": "round",
d: "M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
}
path {
"stroke-linecap": "round",
"stroke-linejoin": "round",
d: "M15 11a3 3 0 11-6 0 3 3 0 016 0z",
"stroke-width": "2"
}
}
}
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone)]
struct WeatherLocation {
id: usize,
name: String,
latitude: f32,
longitude: f32,
country: String,
}
type WeatherLocations = Vec<WeatherLocation>;
#[derive(Debug, Default, Serialize, Deserialize)]
struct SearchResponse {
#[serde(default)]
results: WeatherLocations,
}
async fn get_locations(input: impl Display) -> Result<WeatherLocations> {
let res = reqwest::get(&format!(
"https://geocoding-api.open-meteo.com/v1/search?name={input}"
))
.await?
.json::<SearchResponse>()
.await?;
Ok(res.results)
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone)]
struct WeatherResponse {
daily: DailyWeather,
hourly: HourlyWeather,
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone)]
struct HourlyWeather {
time: Vec<String>,
temperature_2m: Vec<f32>,
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Clone)]
struct DailyWeather {
temperature_2m_min: Vec<f32>,
temperature_2m_max: Vec<f32>,
}
async fn get_weather(location: WeatherLocation) -> reqwest::Result<WeatherResponse> {
reqwest::get(&format!("https://api.open-meteo.com/v1/forecast?latitude={}&longitude={}&hourly=temperature_2m&daily=temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min&timezone=GMT", location.latitude, location.longitude))
.await?
.json::<WeatherResponse>()
.await
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/counters.rs | examples/01-app-demos/counters.rs | //! A simple counters example that stores a list of items in a vec and then iterates over them.
use dioxus::prelude::*;
const STYLE: Asset = asset!("/examples/assets/counter.css");
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Store the counters in a signal
let mut counters = use_signal(|| vec![0, 0, 0]);
// Whenever the counters change, sum them up
let sum = use_memo(move || counters.read().iter().copied().sum::<i32>());
rsx! {
Stylesheet { href: STYLE }
div { id: "controls",
button { onclick: move |_| counters.push(0), "Add counter" }
button { onclick: move |_| { counters.pop(); }, "Remove counter" }
}
h3 { "Total: {sum}" }
// Calling `iter` on a Signal<Vec<>> gives you a GenerationalRef to each entry in the vec
// We enumerate to get the idx of each counter, which we use later to modify the vec
for (i, counter) in counters.iter().enumerate() {
// We need a key to uniquely identify each counter. You really shouldn't be using the index, so we're using
// the counter value itself.
//
// If we used the index, and a counter is removed, dioxus would need to re-write the contents of all following
// counters instead of simply removing the one that was removed
//
// You should use a stable identifier for the key, like a unique id or the value of the counter itself
li { key: "{i}",
button { onclick: move |_| counters.write()[i] -= 1, "-1" }
input {
r#type: "number",
value: "{counter}",
oninput: move |e| {
if let Ok(value) = e.parsed() {
counters.write()[i] = value;
}
}
}
button { onclick: move |_| counters.write()[i] += 1, "+1" }
button { onclick: move |_| { counters.remove(i); }, "x" }
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/dog_app.rs | examples/01-app-demos/dog_app.rs | //! This example demonstrates a simple app that fetches a list of dog breeds and displays a random dog.
//!
//! This app combines `use_loader` and `use_action` to fetch data from the Dog API.
//! - `use_loader` automatically fetches the list of dog breeds when the component mounts.
//! - `use_action` fetches a random dog image whenever the `.dispatch` method is called.
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Fetch the list of breeds from the Dog API, using the `?` syntax to suspend or throw errors
let breed_list = use_loader(move || async move {
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
struct ListBreeds {
message: HashMap<String, Vec<String>>,
}
reqwest::get("https://dog.ceo/api/breeds/list/all")
.await?
.json::<ListBreeds>()
.await
})?;
// Whenever this action is called, it will re-run the future and return the result.
let mut breed = use_action(move |breed| async move {
#[derive(Deserialize, Serialize, Debug, PartialEq)]
struct DogApi {
message: String,
}
reqwest::get(format!("https://dog.ceo/api/breed/{breed}/images/random"))
.await
.unwrap()
.json::<DogApi>()
.await
});
rsx! {
h1 { "Doggo selector" }
div { width: "400px",
for cur_breed in breed_list.read().message.keys().take(20).cloned() {
button {
onclick: move |_| {
breed.call(cur_breed.clone());
},
"{cur_breed}"
}
}
}
div {
match breed.value() {
None => rsx! { div { "Click the button to fetch a dog!" } },
Some(Err(_e)) => rsx! { div { "Failed to fetch a dog, please try again." } },
Some(Ok(res)) => rsx! {
img {
max_width: "500px",
max_height: "500px",
src: "{res.read().message}"
}
},
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/image_generator_openai.rs | examples/01-app-demos/image_generator_openai.rs | use dioxus::prelude::*;
fn main() {
dioxus::launch(app)
}
fn app() -> Element {
let mut api_key = use_signal(|| "".to_string());
let mut prompt = use_signal(|| "".to_string());
let mut num_images = use_signal(|| 1.to_string());
let mut image = use_action(move || async move {
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Props, Clone, Default)]
struct ImageResponse {
created: i32,
data: Vec<UrlImage>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Props, Clone)]
struct UrlImage {
url: String,
}
if api_key.peek().is_empty() || prompt.peek().is_empty() || num_images.peek().is_empty() {
return dioxus::Ok(ImageResponse::default());
}
let res = reqwest::Client::new()
.post("https://api.openai.com/v1/images/generations")
.json(&serde_json::json!({
"prompt": prompt.cloned(),
"n": num_images.cloned().parse::<i32>().unwrap_or(1),
"size":"1024x1024",
}))
.bearer_auth(api_key)
.send()
.await?
.json::<ImageResponse>()
.await?;
Ok(res)
});
rsx! {
Stylesheet { href: "https://unpkg.com/bulma@0.9.0/css/bulma.min.css" }
div { class: "container",
div { class: "columns",
div { class: "column",
input { class: "input is-primary mt-4",
value: "{api_key}",
r#type: "text",
placeholder: "Your OpenAI API Key",
oninput: move |evt| api_key.set(evt.value()),
}
input { class: "input is-primary mt-4",
placeholder: "MAX 1000 Dgts",
r#type: "text",
value:"{prompt}",
oninput: move |evt| prompt.set(evt.value())
}
input { class: "input is-primary mt-4",
r#type: "number",
min:"1",
max:"10",
value:"{num_images}",
oninput: move |evt| num_images.set(evt.value()),
}
}
}
button {
class: "button is-primary",
class: if image.pending() { "is-loading" },
onclick: move |_| {
image.call();
},
"Generate image"
}
if let Some(Ok(image)) = image.value() {
for image in image.read().data.as_slice() {
section { class: "is-flex",
div { class: "container is-fluid",
div { class: "container has-text-centered",
div { class: "is-justify-content-center",
div { class: "level",
div { class: "level-item",
figure { class: "image", img { alt: "", src: "{image.url}", } }
}
}
}
}
}
}
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/todomvc.rs | examples/01-app-demos/todomvc.rs | //! The typical TodoMVC app, implemented in Dioxus.
use dioxus::prelude::*;
use std::collections::HashMap;
const STYLE: Asset = asset!("/examples/assets/todomvc.css");
fn main() {
dioxus::launch(app);
}
#[derive(PartialEq, Eq, Clone, Copy)]
enum FilterState {
All,
Active,
Completed,
}
struct TodoItem {
checked: bool,
contents: String,
}
fn app() -> Element {
// We store the todos in a HashMap in a Signal.
// Each key is the id of the todo, and the value is the todo itself.
let mut todos = use_signal(HashMap::<u32, TodoItem>::new);
let filter = use_signal(|| FilterState::All);
// We use a simple memoized signal to calculate the number of active todos.
// Whenever the todos change, the active_todo_count will be recalculated.
let active_todo_count =
use_memo(move || todos.read().values().filter(|item| !item.checked).count());
// We use a memoized signal to filter the todos based on the current filter state.
// Whenever the todos or filter change, the filtered_todos will be recalculated.
// Note that we're only storing the IDs of the todos, not the todos themselves.
let filtered_todos = use_memo(move || {
let mut filtered_todos = todos
.read()
.iter()
.filter(|(_, item)| match filter() {
FilterState::All => true,
FilterState::Active => !item.checked,
FilterState::Completed => item.checked,
})
.map(|f| *f.0)
.collect::<Vec<_>>();
filtered_todos.sort_unstable();
filtered_todos
});
// Toggle all the todos to the opposite of the current state.
// If all todos are checked, uncheck them all. If any are unchecked, check them all.
let toggle_all = move |_| {
let check = active_todo_count() != 0;
for (_, item) in todos.write().iter_mut() {
item.checked = check;
}
};
rsx! {
Stylesheet { href: STYLE }
section { class: "todoapp",
TodoHeader { todos }
section { class: "main",
if !todos.read().is_empty() {
input {
id: "toggle-all",
class: "toggle-all",
r#type: "checkbox",
onchange: toggle_all,
checked: active_todo_count() == 0
}
label { r#for: "toggle-all" }
}
// Render the todos using the filtered_todos signal
// We pass the ID into the TodoEntry component so it can access the todo from the todos signal.
// Since we store the todos in a signal too, we also need to send down the todo list
ul { class: "todo-list",
for id in filtered_todos() {
TodoEntry { key: "{id}", id, todos }
}
}
// We only show the footer if there are todos.
if !todos.read().is_empty() {
ListFooter { active_todo_count, todos, filter }
}
}
}
// A simple info footer
footer { class: "info",
p { "Double-click to edit a todo" }
p {
"Created by "
a { href: "http://github.com/jkelleyrtp/", "jkelleyrtp" }
}
p {
"Part of "
a { href: "http://todomvc.com", "TodoMVC" }
}
}
}
}
#[component]
fn TodoHeader(mut todos: WriteSignal<HashMap<u32, TodoItem>>) -> Element {
let mut draft = use_signal(|| "".to_string());
let mut todo_id = use_signal(|| 0);
let onkeydown = move |evt: KeyboardEvent| {
if evt.key() == Key::Enter && !draft.is_empty() {
let id = todo_id();
let todo = TodoItem {
checked: false,
contents: draft.to_string(),
};
todos.insert(id, todo);
todo_id += 1;
draft.set("".to_string());
}
};
rsx! {
header { class: "header",
h1 { "todos" }
input {
class: "new-todo",
placeholder: "What needs to be done?",
value: "{draft}",
autofocus: "true",
oninput: move |evt| draft.set(evt.value()),
onkeydown
}
}
}
}
/// A single todo entry
/// This takes the ID of the todo and the todos signal as props
/// We can use these together to memoize the todo contents and checked state
#[component]
fn TodoEntry(mut todos: WriteSignal<HashMap<u32, TodoItem>>, id: u32) -> Element {
let mut is_editing = use_signal(|| false);
// To avoid re-rendering this component when the todo list changes, we isolate our reads to memos
// This way, the component will only re-render when the contents of the todo change, or when the editing state changes.
// This does involve taking a local clone of the todo contents, but it allows us to prevent this component from re-rendering
let checked = use_memo(move || todos.read().get(&id).unwrap().checked);
let contents = use_memo(move || todos.read().get(&id).unwrap().contents.clone());
rsx! {
li {
// Dioxus lets you use if statements in rsx to conditionally render attributes
// These will get merged into a single class attribute
class: if checked() { "completed" },
class: if is_editing() { "editing" },
// Some basic controls for the todo
div { class: "view",
input {
class: "toggle",
r#type: "checkbox",
id: "cbg-{id}",
checked: "{checked}",
oninput: move |evt| todos.get_mut(&id).unwrap().checked = evt.checked()
}
label {
r#for: "cbg-{id}",
ondoubleclick: move |_| is_editing.set(true),
onclick: |evt| evt.prevent_default(),
"{contents}"
}
button {
class: "destroy",
onclick: move |evt| {
evt.prevent_default();
todos.remove(&id);
},
}
}
// Only render the actual input if we're editing
if is_editing() {
input {
class: "edit",
value: "{contents}",
oninput: move |evt| todos.get_mut(&id).unwrap().contents = evt.value(),
autofocus: "true",
onfocusout: move |_| is_editing.set(false),
onkeydown: move |evt| {
match evt.key() {
Key::Enter | Key::Escape | Key::Tab => is_editing.set(false),
_ => {}
}
}
}
}
}
}
}
#[component]
fn ListFooter(
mut todos: WriteSignal<HashMap<u32, TodoItem>>,
active_todo_count: ReadSignal<usize>,
mut filter: WriteSignal<FilterState>,
) -> Element {
// We use a memoized signal to calculate whether we should show the "Clear completed" button.
// This will recompute whenever the todos change, and if the value is true, the button will be shown.
let show_clear_completed = use_memo(move || todos.read().values().any(|todo| todo.checked));
rsx! {
footer { class: "footer",
span { class: "todo-count",
strong { "{active_todo_count} " }
span {
match active_todo_count() {
1 => "item",
_ => "items",
}
" left"
}
}
ul { class: "filters",
for (state , state_text , url) in [
(FilterState::All, "All", "#/"),
(FilterState::Active, "Active", "#/active"),
(FilterState::Completed, "Completed", "#/completed"),
] {
li {
a {
href: url,
class: if filter() == state { "selected" },
onclick: move |evt| {
evt.prevent_default();
filter.set(state)
},
{state_text}
}
}
}
}
if show_clear_completed() {
button {
class: "clear-completed",
onclick: move |_| todos.retain(|_, todo| !todo.checked),
"Clear completed"
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/crm.rs | examples/01-app-demos/crm.rs | //! Tiny CRM - A simple CRM app using the Router component and global signals
//!
//! This shows how to use the `Router` component to manage different views in your app. It also shows how to use global
//! signals to manage state across the entire app.
//!
//! We could simply pass the state as a prop to each component, but this is a good example of how to use global state
//! in a way that works across pages.
//!
//! We implement a number of important details here too, like focusing inputs, handling form submits, navigating the router,
//! platform-specific configuration, and importing 3rd party CSS libraries.
use dioxus::prelude::*;
fn main() {
dioxus::LaunchBuilder::new()
.with_cfg(desktop!({
use dioxus::desktop::{LogicalSize, WindowBuilder};
dioxus::desktop::Config::default()
.with_window(WindowBuilder::new().with_inner_size(LogicalSize::new(800, 600)))
}))
.launch(|| {
rsx! {
Stylesheet {
href: "https://unpkg.com/purecss@2.0.6/build/pure-min.css",
integrity: "sha384-Uu6IeWbM+gzNVXJcM9XV3SohHtmWE+3VGi496jvgX1jyvDTXfdK+rfZc8C1Aehk5",
crossorigin: "anonymous",
}
Stylesheet { href: asset!("/examples/assets/crm.css") }
h1 { "Dioxus CRM Example" }
Router::<Route> {}
}
});
}
/// We only have one list of clients for the whole app, so we can use a global signal.
static CLIENTS: GlobalSignal<Vec<Client>> = Signal::global(Vec::new);
struct Client {
first_name: String,
last_name: String,
description: String,
}
/// The pages of the app, each with a route
#[derive(Routable, Clone)]
enum Route {
#[route("/")]
List,
#[route("/new")]
New,
#[route("/settings")]
Settings,
}
#[component]
fn List() -> Element {
rsx! {
h2 { "List of Clients" }
Link { to: Route::New, class: "pure-button pure-button-primary", "Add Client" }
Link { to: Route::Settings, class: "pure-button", "Settings" }
for client in CLIENTS.read().iter() {
div { class: "client", style: "margin-bottom: 50px",
p { "Name: {client.first_name} {client.last_name}" }
p { "Description: {client.description}" }
}
}
}
}
#[component]
fn New() -> Element {
let mut first_name = use_signal(String::new);
let mut last_name = use_signal(String::new);
let mut description = use_signal(String::new);
let submit_client = move |_| {
// Write the client
CLIENTS.write().push(Client {
first_name: first_name(),
last_name: last_name(),
description: description(),
});
// And then navigate back to the client list
router().push(Route::List);
};
rsx! {
h2 { "Add new Client" }
form { class: "pure-form pure-form-aligned", onsubmit: submit_client,
fieldset {
div { class: "pure-control-group",
label { r#for: "first_name", "First Name" }
input {
id: "first_name",
r#type: "text",
placeholder: "First Name…",
required: true,
value: "{first_name}",
oninput: move |e| first_name.set(e.value()),
// when the form mounts, focus the first name input
onmounted: move |e| async move {
_ = e.set_focus(true).await;
},
}
}
div { class: "pure-control-group",
label { r#for: "last_name", "Last Name" }
input {
id: "last_name",
r#type: "text",
placeholder: "Last Name…",
required: true,
value: "{last_name}",
oninput: move |e| last_name.set(e.value()),
}
}
div { class: "pure-control-group",
label { r#for: "description", "Description" }
textarea {
id: "description",
placeholder: "Description…",
value: "{description}",
oninput: move |e| description.set(e.value()),
}
}
div { class: "pure-controls",
button {
r#type: "submit",
class: "pure-button pure-button-primary",
"Save"
}
Link {
to: Route::List,
class: "pure-button pure-button-primary red",
"Cancel"
}
}
}
}
}
}
#[component]
fn Settings() -> Element {
rsx! {
h2 { "Settings" }
button {
class: "pure-button pure-button-primary red",
onclick: move |_| {
CLIENTS.write().clear();
dioxus::router::router().push(Route::List);
},
"Remove all Clients"
}
Link { to: Route::List, class: "pure-button", "Go back" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/calculator.rs | examples/01-app-demos/calculator.rs | //! Calculator
//!
//! This example is a simple iOS-style calculator. Instead of wrapping the state in a single struct like the
//! `calculate_mutable` example, this example uses several closures to manage actions with the state. Most
//! components will start like this since it's the quickest way to start adding state to your app. The `Signal` type
//! in Dioxus is `Copy` - meaning you don't need to clone it to use it in a closure.
//!
//! Notice how our logic is consolidated into just a few callbacks instead of a single struct. This is a rather organic
//! way to start building state management in Dioxus, and it's a great way to start.
use dioxus::events::*;
use dioxus::html::input_data::keyboard_types::Key;
use dioxus::prelude::*;
const STYLE: Asset = asset!("/examples/assets/calculator.css");
fn main() {
dioxus::LaunchBuilder::desktop()
.with_cfg(desktop!({
use dioxus::desktop::{Config, LogicalSize, WindowBuilder};
Config::new().with_window(
WindowBuilder::default()
.with_title("Calculator")
.with_inner_size(LogicalSize::new(300.0, 525.0)),
)
}))
.launch(app);
}
fn app() -> Element {
let mut val = use_signal(|| String::from("0"));
let mut input_digit = move |num: String| {
if val() == "0" {
val.set(String::new());
}
val.push_str(num.as_str());
};
let mut input_operator = move |key: &str| val.push_str(key);
let handle_key_down_event = move |evt: KeyboardEvent| match evt.key() {
Key::Backspace => {
if !val().is_empty() {
val.pop();
}
}
Key::Character(character) => match character.as_str() {
"+" | "-" | "/" | "*" => input_operator(&character),
"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" => input_digit(character),
_ => {}
},
_ => {}
};
rsx! {
Stylesheet { href: STYLE }
div { id: "wrapper",
div { class: "app",
div { class: "calculator", tabindex: "0", onkeydown: handle_key_down_event,
div { class: "calculator-display",
if val().is_empty() {
"0"
} else {
"{val}"
}
}
div { class: "calculator-keypad",
div { class: "input-keys",
div { class: "function-keys",
button {
class: "calculator-key key-clear",
onclick: move |_| {
val.set(String::new());
if !val.cloned().is_empty() {
val.set("0".into());
}
},
if val.cloned().is_empty() { "C" } else { "AC" }
}
button {
class: "calculator-key key-sign",
onclick: move |_| {
let new_val = calc_val(val.cloned().as_str());
if new_val > 0.0 {
val.set(format!("-{new_val}"));
} else {
val.set(format!("{}", new_val.abs()));
}
},
"±"
}
button {
class: "calculator-key key-percent",
onclick: move |_| val.set(format!("{}", calc_val(val.cloned().as_str()) / 100.0)),
"%"
}
}
div { class: "digit-keys",
button {
class: "calculator-key key-0",
onclick: move |_| input_digit(0.to_string()),
"0"
}
button {
class: "calculator-key key-dot",
onclick: move |_| val.push('.'),
"●"
}
for k in 1..10 {
button {
class: "calculator-key {k}",
name: "key-{k}",
onclick: move |_| input_digit(k.to_string()),
"{k}"
}
}
}
}
div { class: "operator-keys",
for (key, class) in [("/", "key-divide"), ("*", "key-multiply"), ("-", "key-subtract"), ("+", "key-add")] {
button {
class: "calculator-key {class}",
onclick: move |_| input_operator(key),
"{key}"
}
}
button {
class: "calculator-key key-equals",
onclick: move |_| val.set(format!("{}", calc_val(val.cloned().as_str()))),
"="
}
}
}
}
}
}
}
}
fn calc_val(val: &str) -> f64 {
let mut temp = String::new();
let mut operation = "+".to_string();
let mut start_index = 0;
let mut temp_value;
let mut fin_index = 0;
if &val[0..1] == "-" {
temp_value = String::from("-");
fin_index = 1;
start_index += 1;
} else {
temp_value = String::from("");
}
for c in val[fin_index..].chars() {
if c == '+' || c == '-' || c == '*' || c == '/' {
break;
}
temp_value.push(c);
start_index += 1;
}
let mut result = temp_value.parse::<f64>().unwrap();
if start_index + 1 >= val.len() {
return result;
}
for c in val[start_index..].chars() {
if c == '+' || c == '-' || c == '*' || c == '/' {
if !temp.is_empty() {
match &operation as &str {
"+" => result += temp.parse::<f64>().unwrap(),
"-" => result -= temp.parse::<f64>().unwrap(),
"*" => result *= temp.parse::<f64>().unwrap(),
"/" => result /= temp.parse::<f64>().unwrap(),
_ => unreachable!(),
};
}
operation = c.to_string();
temp = String::new();
} else {
temp.push(c);
}
}
if !temp.is_empty() {
match &operation as &str {
"+" => result += temp.parse::<f64>().unwrap(),
"-" => result -= temp.parse::<f64>().unwrap(),
"*" => result *= temp.parse::<f64>().unwrap(),
"/" => result /= temp.parse::<f64>().unwrap(),
_ => unreachable!(),
};
}
result
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/bluetooth-scanner/src/main.rs | examples/01-app-demos/bluetooth-scanner/src/main.rs | use dioxus::prelude::*;
fn main() {
dioxus::launch(app)
}
fn app() -> Element {
let mut scan = use_action(|| async {
use btleplug::api::{Central, Manager as _, Peripheral, ScanFilter};
let manager = btleplug::platform::Manager::new().await?;
// get the first bluetooth adapter
let adapters = manager.adapters().await?;
let central = adapters
.into_iter()
.next()
.context("No Bluetooth adapter found")?;
// start scanning for devices
central.start_scan(ScanFilter::default()).await?;
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
// Return the list of peripherals after scanning
let mut devices = vec![];
for p in central.peripherals().await? {
if let Some(p) = p.properties().await? {
devices.push(p);
}
}
// Sort them by RSSI (signal strength)
devices.sort_by_key(|p| p.rssi.unwrap_or(-100));
dioxus::Ok(devices)
});
rsx! {
Stylesheet { href: asset!("/assets/tailwind.css") }
div {
div { class: "py-8 px-6",
div { class: "container px-4 mx-auto",
h2 { class: "text-2xl font-bold", "Scan for Bluetooth Devices" }
button {
class: "inline-block w-full md:w-auto px-6 py-3 font-medium text-white bg-indigo-500 hover:bg-indigo-600 rounded transition duration-200",
disabled: scan.pending(),
onclick: move |_| {
scan.call();
},
if scan.pending() { "Scanning" } else { "Scan" }
}
}
}
section { class: "py-8",
div { class: "container px-4 mx-auto",
div { class: "p-4 mb-6 bg-white shadow rounded overflow-x-auto",
table { class: "table-auto w-full",
thead {
tr { class: "text-xs text-gray-500 text-left",
th { class: "pl-6 pb-3 font-medium", "Strength" }
th { class: "pb-3 font-medium", "Network" }
th { class: "pb-3 font-medium", "Channel" }
th { class: "pb-3 px-2 font-medium", "Security" }
}
}
match scan.value() {
None if scan.pending() => rsx! { "Scanning..." },
None => rsx! { "Press Scan to start scanning" },
Some(Err(_err)) => rsx! { "Failed to scan" },
Some(Ok(peripherals)) => rsx! {
tbody {
for peripheral in peripherals.read().iter().rev() {
tr { class: "text-xs bg-gray-50",
td { class: "py-5 px-6 font-medium", "{peripheral.rssi.unwrap_or(-100)}" }
td { class: "flex py-3 font-medium", "{peripheral.local_name.clone().unwrap_or_default()}" }
td { span { class: "inline-block py-1 px-2 text-white bg-green-500 rounded-full", "{peripheral.address}" } }
td { span { class: "inline-block py-1 px-2 text-purple-500 bg-purple-50 rounded-full", "{peripheral.tx_power_level.unwrap_or_default()}" } }
}
}
}
}
}
}
}
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/api.rs | examples/01-app-demos/ecommerce-site/src/api.rs | use dioxus::prelude::Result;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
// Cache up to 100 requests, invalidating them after 60 seconds
pub(crate) async fn fetch_product(product_id: usize) -> Result<Product> {
Ok(
reqwest::get(format!("https://fakestoreapi.com/products/{product_id}"))
.await?
.json()
.await?,
)
}
// Cache up to 100 requests, invalidating them after 60 seconds
pub(crate) async fn fetch_products(count: usize, sort: Sort) -> Result<Vec<Product>> {
Ok(reqwest::get(format!(
"https://fakestoreapi.com/products/?sort={sort}&limit={count}"
))
.await?
.json()
.await?)
}
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]
pub(crate) struct Product {
pub(crate) id: u32,
pub(crate) title: String,
pub(crate) price: f32,
pub(crate) description: String,
pub(crate) category: String,
pub(crate) image: String,
pub(crate) rating: Rating,
}
#[derive(Serialize, Deserialize, PartialEq, Clone, Debug, Default)]
pub(crate) struct Rating {
pub(crate) rate: f32,
pub(crate) count: u32,
}
impl Display for Rating {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let rounded = self.rate.round() as usize;
for _ in 0..rounded {
"★".fmt(f)?;
}
for _ in 0..(5 - rounded) {
"☆".fmt(f)?;
}
write!(f, " ({:01}) ({} ratings)", self.rate, self.count)?;
Ok(())
}
}
#[allow(unused)]
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd)]
pub(crate) enum Sort {
Descending,
Ascending,
}
impl Display for Sort {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Sort::Descending => write!(f, "desc"),
Sort::Ascending => write!(f, "asc"),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/main.rs | examples/01-app-demos/ecommerce-site/src/main.rs | #![allow(non_snake_case)]
use components::home::Home;
use components::loading::ChildrenOrLoading;
use dioxus::prelude::*;
mod components {
pub mod error;
pub mod home;
pub mod loading;
pub mod nav;
pub mod product_item;
pub mod product_page;
}
mod api;
fn main() {
dioxus::launch(|| {
rsx! {
document::Link {
rel: "stylesheet",
href: asset!("/public/tailwind.css")
}
ChildrenOrLoading {
Router::<Route> {}
}
}
});
}
#[derive(Clone, Routable, Debug, PartialEq)]
enum Route {
#[route("/")]
Home {},
#[route("/details/:product_id")]
Details { product_id: usize },
}
#[component]
/// Render a more sophisticated page with ssr
fn Details(product_id: usize) -> Element {
rsx! {
div {
components::nav::Nav {}
components::product_page::ProductPage {
product_id
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/components/loading.rs | examples/01-app-demos/ecommerce-site/src/components/loading.rs | use dioxus::prelude::*;
#[component]
pub(crate) fn ChildrenOrLoading(children: Element) -> Element {
rsx! {
Stylesheet { href: asset!("/public/loading.css") }
SuspenseBoundary {
fallback: |_| rsx! { div { class: "spinner", } },
{children}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/components/home.rs | examples/01-app-demos/ecommerce-site/src/components/home.rs | // The homepage is statically rendered, so we don't need to a persistent websocket connection.
use crate::{
api::{fetch_products, Sort},
components::nav::Nav,
components::product_item::ProductItem,
};
use dioxus::prelude::*;
pub(crate) fn Home() -> Element {
let products = use_loader(|| fetch_products(10, Sort::Ascending))?;
rsx! {
Nav {}
section { class: "p-10",
for product in products.iter() {
ProductItem {
product: product.clone()
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/components/error.rs | examples/01-app-demos/ecommerce-site/src/components/error.rs | use dioxus::prelude::*;
#[component]
pub fn error_page() -> Element {
rsx! {
section { class: "py-20",
div { class: "container mx-auto px-4",
div { class: "flex flex-wrap -mx-4 mb-24 text-center",
"An internal error has occurred"
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/components/nav.rs | examples/01-app-demos/ecommerce-site/src/components/nav.rs | use dioxus::prelude::*;
#[component]
pub fn Nav() -> Element {
rsx! {
section { class: "relative",
nav { class: "flex justify-between border-b",
div { class: "px-12 py-8 flex w-full items-center",
a { class: "hidden xl:block mr-16",
href: "/",
icons::cart_icon {}
}
ul { class: "hidden xl:flex font-semibold font-heading",
li { class: "mr-12",
a { class: "hover:text-gray-600",
href: "/",
"Category"
}
}
li { class: "mr-12",
a { class: "hover:text-gray-600",
href: "/",
"Collection"
}
}
li { class: "mr-12",
a { class: "hover:text-gray-600",
href: "/",
"Story"
}
}
li {
a { class: "hover:text-gray-600",
href: "/",
"Brand"
}
}
}
a { class: "shrink-0 xl:mx-auto text-3xl font-bold font-heading",
href: "/",
img { class: "h-9",
width: "auto",
alt: "",
src: "https://shuffle.dev/yofte-assets/logos/yofte-logo.svg",
}
}
div { class: "hidden xl:inline-block mr-14",
input { class: "py-5 px-8 w-full placeholder-gray-400 text-xs uppercase font-semibold font-heading bg-gray-50 border border-gray-200 focus:ring-blue-300 focus:border-blue-300 rounded-md",
placeholder: "Search",
r#type: "text",
}
}
div { class: "hidden xl:flex items-center",
a { class: "mr-10 hover:text-gray-600",
href: "",
icons::icon_1 {}
}
a { class: "flex items-center hover:text-gray-600",
href: "/",
icons::icon_2 {}
span { class: "inline-block w-6 h-6 text-center bg-gray-50 rounded-full font-semibold font-heading",
"3"
}
}
}
}
a { class: "hidden xl:flex items-center px-12 border-l font-semibold font-heading hover:text-gray-600",
href: "/",
icons::icon_3 {}
span {
"Sign In"
}
}
a { class: "xl:hidden flex mr-6 items-center text-gray-600",
href: "/",
icons::icon_4 {}
span { class: "inline-block w-6 h-6 text-center bg-gray-50 rounded-full font-semibold font-heading",
"3"
}
}
a { class: "navbar-burger self-center mr-12 xl:hidden",
href: "/",
icons::icon_5 {}
}
}
div { class: "hidden navbar-menu fixed top-0 left-0 bottom-0 w-5/6 max-w-sm z-50",
div { class: "navbar-backdrop fixed inset-0 bg-gray-800 opacity-25",
}
nav { class: "relative flex flex-col py-6 px-6 w-full h-full bg-white border-r overflow-y-auto",
div { class: "flex items-center mb-8",
a { class: "mr-auto text-3xl font-bold font-heading",
href: "/",
img { class: "h-9",
src: "https://shuffle.dev/yofte-assets/logos/yofte-logo.svg",
width: "auto",
alt: "",
}
}
button { class: "navbar-close",
icons::icon_6 {}
}
}
div { class: "flex mb-8 justify-between",
a { class: "inline-flex items-center font-semibold font-heading",
href: "/",
icons::icon_7 {}
span {
"Sign In"
}
}
div { class: "flex items-center",
a { class: "mr-10",
href: "/",
icons::icon_8 {}
}
a { class: "flex items-center",
href: "/",
icons::icon_9 {}
span { class: "inline-block w-6 h-6 text-center bg-gray-100 rounded-full font-semibold font-heading",
"3"
}
}
}
}
input { class: "block mb-10 py-5 px-8 bg-gray-100 rounded-md border-transparent focus:ring-blue-300 focus:border-blue-300 focus:outline-hidden",
r#type: "search",
placeholder: "Search",
}
ul { class: "text-3xl font-bold font-heading",
li { class: "mb-8",
a {
href: "/",
"Category"
}
}
li { class: "mb-8",
a {
href: "/",
"Collection"
}
}
li { class: "mb-8",
a {
href: "/",
"Story"
}
}
li {
a {
href: "/",
"Brand"
}
}
}
}
}
}
}
}
mod icons {
use super::*;
pub(super) fn cart_icon() -> Element {
rsx! {
svg { class: "mr-3",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
view_box: "0 0 23 23",
width: "23",
height: "23",
path {
stroke_linejoin: "round",
d: "M18.1159 8.72461H2.50427C1.99709 8.72461 1.58594 9.12704 1.58594 9.62346V21.3085C1.58594 21.8049 1.99709 22.2074 2.50427 22.2074H18.1159C18.6231 22.2074 19.0342 21.8049 19.0342 21.3085V9.62346C19.0342 9.12704 18.6231 8.72461 18.1159 8.72461Z",
stroke: "currentColor",
stroke_linecap: "round",
stroke_width: "1.5",
}
path {
stroke: "currentColor",
stroke_linecap: "round",
d: "M6.34473 6.34469V4.95676C6.34473 3.85246 6.76252 2.79338 7.5062 2.01252C8.24988 1.23165 9.25852 0.792969 10.3102 0.792969C11.362 0.792969 12.3706 1.23165 13.1143 2.01252C13.858 2.79338 14.2758 3.85246 14.2758 4.95676V6.34469",
stroke_width: "1.5",
stroke_linejoin: "round",
}
}
}
}
pub(super) fn icon_1() -> Element {
rsx! {
svg {
xmlns: "http://www.w3.org/2000/svg",
height: "20",
view_box: "0 0 23 20",
width: "23",
fill: "none",
path {
d: "M11.4998 19.2061L2.70115 9.92527C1.92859 9.14433 1.41864 8.1374 1.24355 7.04712C1.06847 5.95684 1.23713 4.8385 1.72563 3.85053V3.85053C2.09464 3.10462 2.63366 2.45803 3.29828 1.96406C3.9629 1.47008 4.73408 1.14284 5.5483 1.00931C6.36252 0.875782 7.19647 0.939779 7.98144 1.19603C8.7664 1.45228 9.47991 1.89345 10.0632 2.48319L11.4998 3.93577L12.9364 2.48319C13.5197 1.89345 14.2332 1.45228 15.0182 1.19603C15.8031 0.939779 16.6371 0.875782 17.4513 1.00931C18.2655 1.14284 19.0367 1.47008 19.7013 1.96406C20.3659 2.45803 20.905 3.10462 21.274 3.85053V3.85053C21.7625 4.8385 21.9311 5.95684 21.756 7.04712C21.581 8.1374 21.071 9.14433 20.2984 9.92527L11.4998 19.2061Z",
stroke: "currentColor",
stroke_width: "1.5",
stroke_linejoin: "round",
stroke_linecap: "round",
}
}
}
}
pub(super) fn icon_2() -> Element {
rsx! {
svg { class: "mr-3",
fill: "none",
height: "31",
xmlns: "http://www.w3.org/2000/svg",
width: "32",
view_box: "0 0 32 31",
path {
stroke_linejoin: "round",
stroke_width: "1.5",
d: "M16.0006 16.3154C19.1303 16.3154 21.6673 13.799 21.6673 10.6948C21.6673 7.59064 19.1303 5.07422 16.0006 5.07422C12.871 5.07422 10.334 7.59064 10.334 10.6948C10.334 13.799 12.871 16.3154 16.0006 16.3154Z",
stroke_linecap: "round",
stroke: "currentColor",
}
path {
stroke_width: "1.5",
d: "M24.4225 23.8963C23.6678 22.3507 22.4756 21.0445 20.9845 20.1298C19.4934 19.2151 17.7647 18.7295 15.9998 18.7295C14.2349 18.7295 12.5063 19.2151 11.0152 20.1298C9.52406 21.0445 8.33179 22.3507 7.57715 23.8963",
stroke: "currentColor",
stroke_linecap: "round",
stroke_linejoin: "round",
}
}
}
}
pub(super) fn icon_3() -> Element {
rsx! {
svg { class: "h-2 w-2 text-gray-500 cursor-pointer",
height: "10",
width: "10",
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
view_box: "0 0 10 10",
path {
stroke_width: "1.5",
stroke_linejoin: "round",
d: "M9.00002 1L1 9.00002M1.00003 1L9.00005 9.00002",
stroke: "black",
stroke_linecap: "round",
}
}
}
}
pub(super) fn icon_4() -> Element {
rsx! {
svg {
view_box: "0 0 20 12",
fill: "none",
width: "20",
xmlns: "http://www.w3.org/2000/svg",
height: "12",
path {
d: "M1 2H19C19.2652 2 19.5196 1.89464 19.7071 1.70711C19.8946 1.51957 20 1.26522 20 1C20 0.734784 19.8946 0.48043 19.7071 0.292893C19.5196 0.105357 19.2652 0 19 0H1C0.734784 0 0.48043 0.105357 0.292893 0.292893C0.105357 0.48043 0 0.734784 0 1C0 1.26522 0.105357 1.51957 0.292893 1.70711C0.48043 1.89464 0.734784 2 1 2ZM19 10H1C0.734784 10 0.48043 10.1054 0.292893 10.2929C0.105357 10.4804 0 10.7348 0 11C0 11.2652 0.105357 11.5196 0.292893 11.7071C0.48043 11.8946 0.734784 12 1 12H19C19.2652 12 19.5196 11.8946 19.7071 11.7071C19.8946 11.5196 20 11.2652 20 11C20 10.7348 19.8946 10.4804 19.7071 10.2929C19.5196 10.1054 19.2652 10 19 10ZM19 5H1C0.734784 5 0.48043 5.10536 0.292893 5.29289C0.105357 5.48043 0 5.73478 0 6C0 6.26522 0.105357 6.51957 0.292893 6.70711C0.48043 6.89464 0.734784 7 1 7H19C19.2652 7 19.5196 6.89464 19.7071 6.70711C19.8946 6.51957 20 6.26522 20 6C20 5.73478 19.8946 5.48043 19.7071 5.29289C19.5196 5.10536 19.2652 5 19 5Z",
fill: "#8594A5",
}
}
}
}
pub(super) fn icon_5() -> Element {
rsx! {
svg { class: "mr-2",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
width: "23",
height: "23",
view_box: "0 0 23 23",
path {
stroke_width: "1.5",
stroke_linecap: "round",
stroke_linejoin: "round",
d: "M18.1159 8.72461H2.50427C1.99709 8.72461 1.58594 9.12704 1.58594 9.62346V21.3085C1.58594 21.8049 1.99709 22.2074 2.50427 22.2074H18.1159C18.6231 22.2074 19.0342 21.8049 19.0342 21.3085V9.62346C19.0342 9.12704 18.6231 8.72461 18.1159 8.72461Z",
stroke: "currentColor",
}
path {
d: "M6.34473 6.34469V4.95676C6.34473 3.85246 6.76252 2.79338 7.5062 2.01252C8.24988 1.23165 9.25852 0.792969 10.3102 0.792969C11.362 0.792969 12.3706 1.23165 13.1143 2.01252C13.858 2.79338 14.2758 3.85246 14.2758 4.95676V6.34469",
stroke_linejoin: "round",
stroke_width: "1.5",
stroke_linecap: "round",
stroke: "currentColor",
}
}
}
}
pub(super) fn icon_6() -> Element {
rsx! {
svg { class: "mr-3",
height: "31",
xmlns: "http://www.w3.org/2000/svg",
view_box: "0 0 32 31",
width: "32",
fill: "none",
path {
stroke: "currentColor",
stroke_width: "1.5",
d: "M16.0006 16.3154C19.1303 16.3154 21.6673 13.799 21.6673 10.6948C21.6673 7.59064 19.1303 5.07422 16.0006 5.07422C12.871 5.07422 10.334 7.59064 10.334 10.6948C10.334 13.799 12.871 16.3154 16.0006 16.3154Z",
stroke_linecap: "round",
stroke_linejoin: "round",
}
path {
stroke_linecap: "round",
stroke_width: "1.5",
stroke: "currentColor",
stroke_linejoin: "round",
d: "M24.4225 23.8963C23.6678 22.3507 22.4756 21.0445 20.9845 20.1298C19.4934 19.2151 17.7647 18.7295 15.9998 18.7295C14.2349 18.7295 12.5063 19.2151 11.0152 20.1298C9.52406 21.0445 8.33179 22.3507 7.57715 23.8963",
}
}
}
}
pub(super) fn icon_7() -> Element {
rsx! {
svg { class: "mr-3",
view_box: "0 0 23 23",
fill: "none",
height: "23",
width: "23",
xmlns: "http://www.w3.org/2000/svg",
path {
stroke_linecap: "round",
stroke: "currentColor",
stroke_width: "1.5",
stroke_linejoin: "round",
d: "M18.1159 8.72461H2.50427C1.99709 8.72461 1.58594 9.12704 1.58594 9.62346V21.3085C1.58594 21.8049 1.99709 22.2074 2.50427 22.2074H18.1159C18.6231 22.2074 19.0342 21.8049 19.0342 21.3085V9.62346C19.0342 9.12704 18.6231 8.72461 18.1159 8.72461Z",
}
path {
d: "M6.34473 6.34469V4.95676C6.34473 3.85246 6.76252 2.79338 7.5062 2.01252C8.24988 1.23165 9.25852 0.792969 10.3102 0.792969C11.362 0.792969 12.3706 1.23165 13.1143 2.01252C13.858 2.79338 14.2758 3.85246 14.2758 4.95676V6.34469",
stroke_width: "1.5",
stroke_linecap: "round",
stroke: "currentColor",
stroke_linejoin: "round",
}
}
}
}
pub(super) fn icon_8() -> Element {
rsx! {
svg {
height: "20",
width: "23",
fill: "none",
view_box: "0 0 23 20",
xmlns: "http://www.w3.org/2000/svg",
path {
d: "M11.4998 19.2061L2.70115 9.92527C1.92859 9.14433 1.41864 8.1374 1.24355 7.04712C1.06847 5.95684 1.23713 4.8385 1.72563 3.85053V3.85053C2.09464 3.10462 2.63366 2.45803 3.29828 1.96406C3.9629 1.47008 4.73408 1.14284 5.5483 1.00931C6.36252 0.875782 7.19647 0.939779 7.98144 1.19603C8.7664 1.45228 9.47991 1.89345 10.0632 2.48319L11.4998 3.93577L12.9364 2.48319C13.5197 1.89345 14.2332 1.45228 15.0182 1.19603C15.8031 0.939779 16.6371 0.875782 17.4513 1.00931C18.2655 1.14284 19.0367 1.47008 19.7013 1.96406C20.3659 2.45803 20.905 3.10462 21.274 3.85053V3.85053C21.7625 4.8385 21.9311 5.95684 21.756 7.04712C21.581 8.1374 21.071 9.14433 20.2984 9.92527L11.4998 19.2061Z",
stroke_linejoin: "round",
stroke: "currentColor",
stroke_width: "1.5",
stroke_linecap: "round",
}
}
}
}
pub(super) fn icon_9() -> Element {
rsx! {
svg {
view_box: "0 0 18 18",
xmlns: "http://www.w3.org/2000/svg",
width: "18",
height: "18",
fill: "none",
path {
fill: "black",
d: "M18 15.4688H0V17.7207H18V15.4688Z",
}
path {
fill: "black",
d: "M11.0226 7.87402H0V10.126H11.0226V7.87402Z",
}
path {
fill: "black",
d: "M18 0.279297H0V2.53127H18V0.279297Z",
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/components/product_page.rs | examples/01-app-demos/ecommerce-site/src/components/product_page.rs | use std::{fmt::Display, str::FromStr};
use crate::api::{fetch_product, Product};
use dioxus::prelude::*;
#[component]
pub fn ProductPage(product_id: ReadSignal<usize>) -> Element {
let mut quantity = use_signal(|| 1);
let mut size = use_signal(Size::default);
let product = use_loader(move || fetch_product(product_id()))?;
let Product {
title,
price,
description,
category,
image,
rating,
..
} = product();
rsx! {
section { class: "py-20",
div { class: "container mx-auto px-4",
div { class: "flex flex-wrap -mx-4 mb-24",
div { class: "w-full md:w-1/2 px-4 mb-8 md:mb-0",
div { class: "relative mb-10",
style: "height: 564px;",
a { class: "absolute top-1/2 left-0 ml-8 transform translate-1/2",
href: "#",
icons::icon_0 {}
}
img { class: "object-cover w-full h-full",
alt: "",
src: "{image}",
}
a { class: "absolute top-1/2 right-0 mr-8 transform translate-1/2",
href: "#",
icons::icon_1 {}
}
}
}
div { class: "w-full md:w-1/2 px-4",
div { class: "lg:pl-20",
div { class: "mb-10 pb-10 border-b",
h2 { class: "mt-2 mb-6 max-w-xl text-5xl md:text-6xl font-bold font-heading",
"{title}"
}
div { class: "mb-8",
"{rating}"
}
p { class: "inline-block mb-8 text-2xl font-bold font-heading text-blue-300",
span {
"${price}"
}
}
p { class: "max-w-md text-gray-500",
"{description}"
}
}
div { class: "flex mb-12",
div { class: "mr-6",
span { class: "block mb-4 font-bold font-heading text-gray-400 uppercase",
"QTY"
}
div { class: "inline-flex items-center px-4 font-semibold font-heading text-gray-500 border border-gray-200 focus:ring-blue-300 focus:border-blue-300 rounded-md",
button { class: "py-2 hover:text-gray-700",
onclick: move |_| quantity += 1,
icons::icon_2 {}
}
input { class: "w-12 m-0 px-2 py-4 text-center md:text-right border-0 focus:ring-transparent focus:outline-hidden rounded-md",
placeholder: "1",
r#type: "number",
value: "{quantity}",
oninput: move |evt| if let Ok(as_number) = evt.value().parse() { quantity.set(as_number) },
}
button { class: "py-2 hover:text-gray-700",
onclick: move |_| quantity -= 1,
icons::icon_3 {}
}
}
}
div {
span { class: "block mb-4 font-bold font-heading text-gray-400 uppercase",
"Size"
}
select { class: "pl-6 pr-10 py-4 font-semibold font-heading text-gray-500 border border-gray-200 focus:ring-blue-300 focus:border-blue-300 rounded-md",
id: "",
name: "",
onchange: move |evt| {
if let Ok(new_size) = evt.value().parse() {
size.set(new_size);
}
},
option {
value: "1",
"Medium"
}
option {
value: "2",
"Small"
}
option {
value: "3",
"Large"
}
}
}
}
div { class: "flex flex-wrap -mx-4 mb-14 items-center",
div { class: "w-full xl:w-2/3 px-4 mb-4 xl:mb-0",
a { class: "block bg-orange-300 hover:bg-orange-400 text-center text-white font-bold font-heading py-5 px-8 rounded-md uppercase transition duration-200",
href: "#",
"Add to cart"
}
}
}
div { class: "flex items-center",
span { class: "mr-8 text-gray-500 font-bold font-heading uppercase",
"SHARE IT"
}
a { class: "mr-1 w-8 h-8",
href: "#",
img {
alt: "",
src: "https://shuffle.dev/yofte-assets/buttons/facebook-circle.svg",
}
}
a { class: "mr-1 w-8 h-8",
href: "#",
img {
alt: "",
src: "https://shuffle.dev/yofte-assets/buttons/instagram-circle.svg",
}
}
a { class: "w-8 h-8",
href: "#",
img {
src: "https://shuffle.dev/yofte-assets/buttons/twitter-circle.svg",
alt: "",
}
}
}
}
}
}
div {
ul { class: "flex flex-wrap mb-16 border-b-2",
li { class: "w-1/2 md:w-auto",
a { class: "inline-block py-6 px-10 bg-white text-gray-500 font-bold font-heading shadow-2xl",
href: "#",
"Description"
}
}
li { class: "w-1/2 md:w-auto",
a { class: "inline-block py-6 px-10 text-gray-500 font-bold font-heading",
href: "#",
"Customer reviews"
}
}
li { class: "w-1/2 md:w-auto",
a { class: "inline-block py-6 px-10 text-gray-500 font-bold font-heading",
href: "#",
"Shipping & returns"
}
}
li { class: "w-1/2 md:w-auto",
a { class: "inline-block py-6 px-10 text-gray-500 font-bold font-heading",
href: "#",
"Brand"
}
}
}
h3 { class: "mb-8 text-3xl font-bold font-heading text-blue-300",
"{category}"
}
p { class: "max-w-2xl text-gray-500",
"{description}"
}
}
}
}
}
}
#[derive(Default)]
enum Size {
Small,
#[default]
Medium,
Large,
}
impl Display for Size {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Size::Small => "small".fmt(f),
Size::Medium => "medium".fmt(f),
Size::Large => "large".fmt(f),
}
}
}
impl FromStr for Size {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
use Size::*;
match s.to_lowercase().as_str() {
"small" => Ok(Small),
"medium" => Ok(Medium),
"large" => Ok(Large),
_ => Err(()),
}
}
}
mod icons {
use super::*;
pub(super) fn icon_0() -> Element {
rsx! {
svg { class: "w-6 h-6",
view_box: "0 0 24 23",
xmlns: "http://www.w3.org/2000/svg",
height: "23",
fill: "none",
width: "24",
path {
stroke: "black",
fill: "black",
d: "M2.01328 18.9877C2.05682 16.7902 2.71436 12.9275 6.3326 9.87096L6.33277 9.87116L6.33979 9.86454L6.3398 9.86452C6.34682 9.85809 8.64847 7.74859 13.4997 7.74859C13.6702 7.74859 13.8443 7.75111 14.0206 7.757L14.0213 7.75702L14.453 7.76978L14.6331 7.77511V7.59486V3.49068L21.5728 10.5736L14.6331 17.6562V13.6558V13.5186L14.4998 13.4859L14.1812 13.4077C14.1807 13.4075 14.1801 13.4074 14.1792 13.4072M2.01328 18.9877L14.1792 13.4072M2.01328 18.9877C7.16281 11.8391 14.012 13.3662 14.1792 13.4072M2.01328 18.9877L14.1792 13.4072M23.125 10.6961L23.245 10.5736L23.125 10.4512L13.7449 0.877527L13.4449 0.571334V1V6.5473C8.22585 6.54663 5.70981 8.81683 5.54923 8.96832C-0.317573 13.927 0.931279 20.8573 0.946581 20.938L0.946636 20.9383L1.15618 22.0329L1.24364 22.4898L1.47901 22.0885L2.041 21.1305L2.04103 21.1305C4.18034 17.4815 6.71668 15.7763 8.8873 15.0074C10.9246 14.2858 12.6517 14.385 13.4449 14.4935V20.1473V20.576L13.7449 20.2698L23.125 10.6961Z",
stroke_width: "0.35",
}
}
}
}
pub(super) fn icon_1() -> Element {
rsx! {
svg { class: "w-6 h-6",
height: "27",
view_box: "0 0 27 27",
fill: "none",
width: "27",
xmlns: "http://www.w3.org/2000/svg",
path {
d: "M13.4993 26.2061L4.70067 16.9253C3.9281 16.1443 3.41815 15.1374 3.24307 14.0471C3.06798 12.9568 3.23664 11.8385 3.72514 10.8505V10.8505C4.09415 10.1046 4.63318 9.45803 5.29779 8.96406C5.96241 8.47008 6.73359 8.14284 7.54782 8.00931C8.36204 7.87578 9.19599 7.93978 9.98095 8.19603C10.7659 8.45228 11.4794 8.89345 12.0627 9.48319L13.4993 10.9358L14.9359 9.48319C15.5192 8.89345 16.2327 8.45228 17.0177 8.19603C17.8026 7.93978 18.6366 7.87578 19.4508 8.00931C20.265 8.14284 21.0362 8.47008 21.7008 8.96406C22.3654 9.45803 22.9045 10.1046 23.2735 10.8505V10.8505C23.762 11.8385 23.9306 12.9568 23.7556 14.0471C23.5805 15.1374 23.0705 16.1443 22.298 16.9253L13.4993 26.2061Z",
stroke: "black",
stroke_width: "1.5",
stroke_linecap: "round",
stroke_linejoin: "round",
}
}
}
}
pub(super) fn icon_2() -> Element {
rsx! {
svg {
view_box: "0 0 12 12",
height: "12",
width: "12",
fill: "none",
xmlns: "http://www.w3.org/2000/svg",
g {
opacity: "0.35",
rect {
height: "12",
x: "5",
fill: "currentColor",
width: "2",
}
rect {
fill: "currentColor",
width: "2",
height: "12",
x: "12",
y: "5",
transform: "rotate(90 12 5)",
}
}
}
}
}
pub(super) fn icon_3() -> Element {
rsx! {
svg {
width: "12",
fill: "none",
view_box: "0 0 12 2",
height: "2",
xmlns: "http://www.w3.org/2000/svg",
g {
opacity: "0.35",
rect {
transform: "rotate(90 12 0)",
height: "12",
fill: "currentColor",
x: "12",
width: "2",
}
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/ecommerce-site/src/components/product_item.rs | examples/01-app-demos/ecommerce-site/src/components/product_item.rs | use dioxus::prelude::*;
use crate::api::Product;
#[component]
pub(crate) fn ProductItem(product: Product) -> Element {
let Product {
id,
title,
price,
category,
image,
rating,
..
} = product;
rsx! {
section { class: "h-40 p-2 m-2 shadow-lg ring-1 rounded-lg flex flex-row place-items-center hover:ring-4 hover:shadow-2xl transition-all duration-200",
img {
class: "object-scale-down w-1/6 h-full",
src: "{image}",
}
div { class: "pl-4 text-left text-ellipsis",
a {
href: "/details/{id}",
class: "w-full text-center",
"{title}"
}
p {
class: "w-full",
"{rating}"
}
p {
class: "w-full",
"{category}"
}
p {
class: "w-1/4",
"${price}"
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/hackernews/src/main.rs | examples/01-app-demos/hackernews/src/main.rs | #![allow(non_snake_case, unused)]
use dioxus::prelude::*;
// Define the Hackernews API and types
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::{
fmt::{Display, Formatter},
num::ParseIntError,
str::FromStr,
};
use svg_attributes::to;
fn main() {
LaunchBuilder::new()
.with_cfg(server_only! {
dioxus::server::ServeConfig::builder().enable_out_of_order_streaming()
})
.launch(|| {
rsx! {
Stylesheet { href: asset!("/assets/hackernews.css") }
Router::<Route> {}
}
});
}
#[derive(Clone, Routable)]
enum Route {
#[route("/story&:story")]
StoryPreview { story: Option<i64> },
}
#[component]
fn StoryPreview(story: ReadSignal<Option<i64>>) -> Element {
rsx! {
div { display: "flex", flex_direction: "row", width: "100%",
div { width: "50%",
SuspenseBoundary { fallback: |context| rsx! { "Loading..." },
Stories {}
}
}
div { width: "50%",
SuspenseBoundary { fallback: |context| rsx! { "Loading preview..." },
if let Some(story) = story() {
Preview { story_id: story }
} else {
div { padding: "0.5rem", "Select a story to preview" }
}
}
}
}
}
}
#[component]
fn Stories() -> Element {
let stories = use_loader(move || async move {
let stories_ids = reqwest::get(&format!("{}topstories.json", BASE_API_URL))
.await?
.json::<Vec<i64>>()
.await?
.into_iter()
.take(30)
.collect::<Vec<i64>>();
dioxus::Ok(stories_ids)
})?;
rsx! {
div {
for story in stories() {
ChildrenOrLoading { key: "{story}",
StoryListing { story }
}
}
}
}
}
#[component]
fn StoryListing(story: ReadSignal<i64>) -> Element {
let story = use_loader(move || get_story(story()))?;
let StoryItem {
title,
url,
by,
score,
time,
kids,
id,
..
} = story().item;
let url = url.as_deref().unwrap_or_default();
let hostname = url
.trim_start_matches("https://")
.trim_start_matches("http://")
.trim_start_matches("www.");
let score = format!("{score} {}", if score == 1 { " point" } else { " points" });
let comments = format!(
"{} {}",
kids.len(),
if kids.len() == 1 {
" comment"
} else {
" comments"
}
);
let time = time.format("%D %l:%M %p");
rsx! {
div {
padding: "0.5rem",
position: "relative",
div { font_size: "1.5rem",
Link {
to: Route::StoryPreview { story: Some(id) },
"{title}"
}
a {
color: "gray",
href: "https://news.ycombinator.com/from?site={hostname}",
text_decoration: "none",
" ({hostname})"
}
}
div { display: "flex", flex_direction: "row", color: "gray",
div { "{score}" }
div { padding_left: "0.5rem", "by {by}" }
div { padding_left: "0.5rem", "{time}" }
div { padding_left: "0.5rem", "{comments}" }
}
}
}
}
#[component]
fn Preview(story_id: ReadSignal<i64>) -> Element {
let story = use_loader(move || get_story(story_id()))?.cloned();
rsx! {
div { padding: "0.5rem",
div { font_size: "1.5rem", a { href: story.item.url, "{story.item.title}" } }
if let Some(text) = &story.item.text { div { dangerous_inner_html: "{text}" } }
for comment in story.item.kids.iter().copied() {
ChildrenOrLoading {
key: "{comment}",
Comment { comment }
}
}
}
}
}
#[component]
fn Comment(comment: ReadSignal<i64>) -> Element {
let comment = use_loader(move || async move {
let mut comment = reqwest::get(&format!("{}{}{}.json", BASE_API_URL, ITEM_API, comment))
.await?
.json::<CommentData>()
.await?;
dioxus::Ok(comment)
})?;
let CommentData {
by,
time,
text,
id,
kids,
..
} = comment();
rsx! {
div { padding: "0.5rem",
div { color: "gray", "by {by}" }
div { dangerous_inner_html: "{text}" }
for comment in kids.iter().copied() {
ChildrenOrLoading {
key: "{comment}",
Comment { comment }
}
}
}
}
}
pub static BASE_API_URL: &str = "https://hacker-news.firebaseio.com/v0/";
pub static ITEM_API: &str = "item/";
pub static USER_API: &str = "user/";
const COMMENT_DEPTH: i64 = 1;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StoryPageData {
#[serde(flatten)]
pub item: StoryItem,
#[serde(default)]
pub comments: Vec<CommentData>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CommentData {
pub id: i64,
/// there will be no by field if the comment was deleted
#[serde(default)]
pub by: String,
#[serde(default)]
pub text: String,
#[serde(with = "chrono::serde::ts_seconds")]
pub time: DateTime<Utc>,
#[serde(default)]
pub kids: Vec<i64>,
pub r#type: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StoryItem {
pub id: i64,
pub title: String,
pub url: Option<String>,
pub text: Option<String>,
#[serde(default)]
pub by: String,
#[serde(default)]
pub score: i64,
#[serde(default)]
pub descendants: i64,
#[serde(with = "chrono::serde::ts_seconds")]
pub time: DateTime<Utc>,
#[serde(default)]
pub kids: Vec<i64>,
pub r#type: String,
}
pub async fn get_story(id: i64) -> Result<StoryPageData> {
Ok(
reqwest::get(&format!("{}{}{}.json", BASE_API_URL, ITEM_API, id))
.await?
.json::<StoryPageData>()
.await?,
)
}
#[component]
fn ChildrenOrLoading(children: Element) -> Element {
rsx! {
SuspenseBoundary {
fallback: |_| rsx! { div { class: "spinner", } },
children
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/hotdog/src/backend.rs | examples/01-app-demos/hotdog/src/backend.rs | use anyhow::Result;
use dioxus::prelude::*;
#[cfg(feature = "server")]
thread_local! {
static DB: std::sync::LazyLock<rusqlite::Connection> = std::sync::LazyLock::new(|| {
std::fs::create_dir("hotdogdb").unwrap();
let conn = rusqlite::Connection::open("hotdogdb/hotdog.db").expect("Failed to open database");
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS dogs (
id INTEGER PRIMARY KEY,
url TEXT NOT NULL
);",
)
.unwrap();
conn
});
}
#[get("/api/dogs")]
pub async fn list_dogs() -> Result<Vec<(usize, String)>> {
DB.with(|db| {
Ok(db
.prepare("SELECT id, url FROM dogs ORDER BY id DESC LIMIT 10")?
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
.collect::<Result<Vec<(usize, String)>, rusqlite::Error>>()?)
})
}
#[delete("/api/dogs/{id}")]
pub async fn remove_dog(id: usize) -> Result<()> {
DB.with(|db| db.execute("DELETE FROM dogs WHERE id = ?1", [id]))?;
Ok(())
}
#[post("/api/dogs")]
pub async fn save_dog(image: String) -> Result<()> {
DB.with(|db| db.execute("INSERT INTO dogs (url) VALUES (?1)", [&image]))?;
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/hotdog/src/main.rs | examples/01-app-demos/hotdog/src/main.rs | mod backend;
mod frontend;
use dioxus::prelude::*;
use frontend::*;
#[derive(Routable, PartialEq, Clone)]
enum Route {
#[layout(NavBar)]
#[route("/")]
DogView,
#[route("/favorites")]
Favorites,
}
fn main() {
#[cfg(not(feature = "server"))]
dioxus::fullstack::set_server_url("https://hot-dog.fly.dev");
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
Stylesheet { href: asset!("/assets/main.css") }
Router::<Route> {}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/hotdog/src/frontend.rs | examples/01-app-demos/hotdog/src/frontend.rs | use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
use crate::{
backend::{list_dogs, remove_dog, save_dog},
Route,
};
#[component]
pub fn Favorites() -> Element {
let mut favorites = use_loader(list_dogs)?;
rsx! {
div { id: "favorites",
for (id , url) in favorites.cloned() {
div { class: "favorite-dog", key: "{id}",
img { src: "{url}" }
button {
onclick: move |_| async move {
_ = remove_dog(id).await;
favorites.restart();
},
"❌"
}
}
}
}
}
}
#[component]
pub fn NavBar() -> Element {
rsx! {
div { id: "title",
span {}
Link { to: Route::DogView, h1 { "🌭 HotDog! " } }
Link { to: Route::Favorites, id: "heart", "♥️" }
}
Outlet::<Route> {}
}
}
#[component]
pub fn DogView() -> Element {
let mut img_src = use_loader(|| async move {
#[derive(Deserialize, Serialize, Debug, PartialEq)]
struct DogApi {
message: String,
}
let json = reqwest::get("https://dog.ceo/api/breeds/image/random")
.await?
.json::<DogApi>()
.await?;
let url = json.message;
dioxus::Ok(url)
})?;
rsx! {
div { id: "dogview",
img { id: "dogimg", src: "{img_src}" }
}
div { id: "buttons",
button {
id: "skip",
onclick: move |_| img_src.restart(),
"skip"
}
button {
id: "save",
onclick: move |_| async move { _ = save_dog(img_src()).await },
"save!"
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/01-app-demos/file-explorer/src/main.rs | examples/01-app-demos/file-explorer/src/main.rs | //! Example: File Explorer
//!
//! This is a fun little desktop application that lets you explore the file system.
//!
//! This example is interesting because it's mixing filesystem operations and GUI, which is typically hard for UI to do.
//! We store the state entirely in a single signal, making the explorer logic fairly easy to reason about.
use std::env::current_dir;
use std::path::PathBuf;
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut files = use_signal(Files::new);
rsx! {
Stylesheet { href: asset!("/assets/fileexplorer.css") }
Stylesheet { href: "https://fonts.googleapis.com/icon?family=Material+Icons" }
div {
header {
i { class: "material-icons icon-menu", "menu" }
h1 { "Files: " {files.read().current()} }
span { }
i { class: "material-icons", onclick: move |_| files.write().go_up(), "logout" }
}
main {
for (dir_id, path) in files.read().path_names.iter().enumerate() {
{
let path_end = path.components().next_back().map(|p|p.as_os_str()).unwrap_or(path.as_os_str()).to_string_lossy();
let path = path.display();
rsx! {
div { class: "folder", key: "{path}",
i { class: "material-icons",
onclick: move |_| files.write().enter_dir(dir_id),
if path_end.contains('.') {
"description"
} else {
"folder"
}
p { class: "cooltip", "0 folders / 0 files" }
}
h1 { "{path_end}" }
}
}
}
}
if let Some(err) = files.read().err.as_ref() {
div {
code { "{err}" }
button { onclick: move |_| files.write().clear_err(), "x" }
}
}
}
}
}
}
/// A simple little struct to hold the file explorer state
///
/// We don't use any fancy signals or memoization here - Dioxus is so fast that even a file explorer can be done with a
/// single signal.
struct Files {
current_path: PathBuf,
path_names: Vec<PathBuf>,
err: Option<String>,
}
impl Files {
fn new() -> Self {
let mut files = Self {
current_path: std::path::absolute(current_dir().unwrap()).unwrap(),
path_names: vec![],
err: None,
};
files.reload_path_list();
files
}
fn reload_path_list(&mut self) {
let paths = match std::fs::read_dir(&self.current_path) {
Ok(e) => e,
Err(err) => {
let err = format!("An error occurred: {err:?}");
self.err = Some(err);
return;
}
};
let collected = paths.collect::<Vec<_>>();
// clear the current state
self.clear_err();
self.path_names.clear();
for path in collected {
self.path_names.push(path.unwrap().path().to_path_buf());
}
}
fn go_up(&mut self) {
self.current_path = match self.current_path.parent() {
Some(path) => path.to_path_buf(),
None => {
self.err = Some("Cannot go up from the root directory".to_string());
return;
}
};
self.reload_path_list();
}
fn enter_dir(&mut self, dir_id: usize) {
let path = &self.path_names[dir_id];
self.current_path.clone_from(path);
self.reload_path_list();
}
fn current(&self) -> String {
self.current_path.display().to_string()
}
fn clear_err(&mut self) {
self.err = None;
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/web_component.rs | examples/09-reference/web_component.rs | //! Dioxus allows webcomponents to be created with a simple syntax.
//!
//! Read more about webcomponents [here](https://developer.mozilla.org/en-US/docs/Web/Web_Components)
//!
//! We typically suggest wrapping webcomponents in a strongly typed interface using a component.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
div {
h1 { "Web Components" }
CoolWebComponent { my_prop: "Hello, world!".to_string() }
}
}
}
/// A web-component wrapped with a strongly typed interface using a component
#[component]
fn CoolWebComponent(my_prop: String) -> Element {
rsx! {
// rsx! takes a webcomponent as long as its tag name is separated with dashes
web-component {
// Since web-components don't have built-in attributes, the attribute names must be passed as a string
"my-prop": my_prop,
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/xss_safety.rs | examples/09-reference/xss_safety.rs | //! XSS Safety
//!
//! This example proves that Dioxus is safe from XSS attacks.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut contents = use_signal(|| String::from("<script>alert(\"hello world\")</script>"));
rsx! {
div {
h1 {"Dioxus is XSS-Safe"}
h3 { "{contents}" }
input {
value: "{contents}",
r#type: "text",
oninput: move |e| contents.set(e.value()),
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/rsx_usage.rs | examples/09-reference/rsx_usage.rs | //! A tour of the rsx! macro
//! ------------------------
//!
//! This example serves as an informal quick reference of all the things that the rsx! macro can do.
//!
//! A full in-depth reference guide is available at: https://www.notion.so/rsx-macro-basics-ef6e367dec124f4784e736d91b0d0b19
//!
//! ### Elements
//! - Create any element from its tag
//! - Accept compile-safe attributes for each tag
//! - Display documentation for elements
//! - Arguments instead of String
//! - Text
//! - Inline Styles
//!
//! ## General Concepts
//! - Iterators
//! - Keys
//! - Match statements
//! - Conditional Rendering
//!
//! ### Events
//! - Handle events with the "onXYZ" syntax
//! - Closures can capture their environment with the 'static lifetime
//!
//!
//! ### Components
//! - Components can be made by specifying the name
//! - Components can be referenced by path
//! - Components may have optional parameters
//! - Components may have their properties specified by spread syntax
//! - Components may accept child nodes
//! - Components that accept "onXYZ" get those closures bump allocated
//!
//! ### Fragments
//! - Allow fragments using the built-in `Fragment` component
//! - Accept a list of vnodes as children for a Fragment component
//! - Allow keyed fragments in iterators
//! - Allow top-level fragments
fn main() {
dioxus::launch(app)
}
use core::{fmt, str::FromStr};
use std::fmt::Display;
use baller::Baller;
use dioxus::prelude::*;
fn app() -> Element {
let formatting = "formatting!";
let formatting_tuple = ("a", "b");
let lazy_fmt = format_args!("lazily formatted text");
let asd = 123;
rsx! {
div {
// Elements
div {}
h1 {"Some text"}
h1 {"Some text with {formatting}"}
h1 {"Formatting basic expressions {formatting_tuple.0} and {formatting_tuple.1}"}
h1 {"Formatting without interpolation " {formatting_tuple.0} "and" {formatting_tuple.1} }
h2 {
"Multiple"
"Text"
"Blocks"
"Use comments as separators in html"
}
div {
h1 {"multiple"}
h2 {"nested"}
h3 {"elements"}
}
div {
class: "my special div",
h1 {"Headers and attributes!"}
}
div {
h1 {"Style attributes!"}
p {
"hello"
b {
"world"
}
i {
"foo"
}
span {
style: "color: red;font-style:italic",
"red"
}
span {
color: "blue",
font_weight: "bold",
"attr_blue"
}
}
}
div {
// pass simple rust expressions in
class: "{lazy_fmt}",
id: format_args!("attributes can be passed lazily with std::fmt::Arguments"),
class: "asd",
class: "{asd}",
// if statements can be used to conditionally render attributes
class: if formatting.contains("form") { "{asd}" },
// longer if chains also work
class: if formatting.contains("form") { "{asd}" } else if formatting.contains("my other form") { "{asd}" },
class: if formatting.contains("form") { "{asd}" } else if formatting.contains("my other form") { "{asd}" } else { "{asd}" },
div {
class: format_args!("Arguments can be passed in through curly braces for complex {asd}")
}
}
// dangerous_inner_html for both html and svg
div { dangerous_inner_html: "<p>hello dangerous inner html</p>" }
svg { dangerous_inner_html: "<circle r='50' cx='50' cy='50' />" }
// Built-in idents can be used
use {}
link {
as: "asd"
}
// Expressions can be used in element position too:
{rsx!(p { "More templating!" })}
// Iterators
{(0..10).map(|i| rsx!(li { "{i}" }))}
// Iterators within expressions
{
let data = std::collections::HashMap::<&'static str, &'static str>::new();
// Iterators *should* have keys when you can provide them.
// Keys make your app run faster. Make sure your keys are stable, unique, and predictable.
// Using an "ID" associated with your data is a good idea.
data.into_iter().map(|(k, v)| rsx!(li { key: "{k}", "{v}" }))
}
// Matching
match true {
true => rsx!( h1 {"Top text"}),
false => rsx!( h1 {"Bottom text"})
}
// Conditional rendering
// Dioxus conditional rendering is based around None/Some. We have no special syntax for conditionals.
// You can convert a bool condition to rsx! with .then and .or
{true.then(|| rsx!(div {}))}
// Alternatively, you can use the "if" syntax - but both branches must be resolve to Element
if false {
h1 {"Top text"}
} else {
h1 {"Bottom text"}
}
// Using optionals for diverging branches
// Note that since this is wrapped in curlies, it's interpreted as an expression
{if true {
Some(rsx!(h1 {"Top text"}))
} else {
None
}}
// returning "None" without a diverging branch is a bit noisy... but rare in practice
{None as Option<()>}
// can also just use empty fragments
Fragment {}
// Fragments let you insert groups of nodes without a parent.
// This lets you make components that insert elements as siblings without a container.
div {"A"}
Fragment {
div {"B"}
div {"C"}
Fragment {
"D"
Fragment {
"E"
"F"
}
}
}
// Components
// Can accept any paths
// Notice how you still get syntax highlighting and IDE support :)
Baller {}
baller::Baller {}
crate::baller::Baller {}
// Can take properties
Taller { a: "asd" }
// Can take optional properties
Taller { a: "asd" }
// Can pass in props directly as an expression
{
let props = TallerProps {a: "hello", children: VNode::empty() };
rsx!(Taller { ..props })
}
// Spreading can also be overridden manually
Taller {
a: "not ballin!",
..TallerProps { a: "ballin!", children: VNode::empty() }
}
// Can take children too!
Taller { a: "asd", div {"hello world!"} }
// This component's props are defined *inline* with the `component` macro
WithInline { text: "using functionc all syntax" }
// Components can be generic too
// This component takes i32 type to give you typed input
TypedInput::<i32> {}
// Type inference can be used too
TypedInput { initial: 10.0 }
// generic with the `component` macro
Label { text: "hello generic world!" }
Label { text: 99.9 }
// Lowercase components work too, as long as they are access using a path
baller::lowercase_component {}
// For in-scope lowercase components, use the `self` keyword
self::lowercase_helper {}
// helper functions
// Anything that implements IntoVnode can be dropped directly into Rsx
{helper("hello world!")}
// Strings can be supplied directly
{String::from("Hello world!")}
// So can format_args
// todo(jon): this is broken in edition 2024
// {format_args!("Hello {}!", "world")}
// Or we can shell out to a helper function
{format_dollars(10, 50)}
}
}
}
fn format_dollars(dollars: u32, cents: u32) -> String {
format!("${dollars}.{cents:02}")
}
fn helper(text: &str) -> Element {
rsx! {
p { "{text}" }
}
}
// no_case_check disables PascalCase checking if you *really* want a snake_case component.
// This will likely be deprecated/removed in a future update that will introduce a more polished linting system,
// something like Clippy.
#[component(no_case_check)]
fn lowercase_helper() -> Element {
rsx! {
"asd"
}
}
mod baller {
use super::*;
#[component]
/// This component totally balls
pub fn Baller() -> Element {
rsx! { "ballin'" }
}
// no_case_check disables PascalCase checking if you *really* want a snake_case component.
// This will likely be deprecated/removed in a future update that will introduce a more polished linting system,
// something like Clippy.
#[component(no_case_check)]
pub fn lowercase_component() -> Element {
rsx! { "look ma, no uppercase" }
}
}
/// Documentation for this component is visible within the rsx macro
#[component]
pub fn Taller(
/// Fields are documented and accessible in rsx!
a: &'static str,
children: Element,
) -> Element {
rsx! { {&children} }
}
#[derive(Props, Clone, PartialEq, Eq)]
pub struct TypedInputProps<T: 'static + Clone + PartialEq> {
#[props(optional, default)]
initial: Option<T>,
}
#[allow(non_snake_case)]
pub fn TypedInput<T>(props: TypedInputProps<T>) -> Element
where
T: FromStr + fmt::Display + PartialEq + Clone + 'static,
<T as FromStr>::Err: std::fmt::Display,
{
if let Some(props) = props.initial {
return rsx! { "{props}" };
}
VNode::empty()
}
#[component]
fn WithInline(text: String) -> Element {
rsx! {
p { "{text}" }
}
}
#[component]
fn Label<T: Clone + PartialEq + Display + 'static>(text: T) -> Element {
rsx! {
p { "{text}" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/generic_component.rs | examples/09-reference/generic_component.rs | //! This example demonstrates how to create a generic component in Dioxus.
//!
//! Generic components can be useful when you want to create a component that renders differently depending on the type
//! of data it receives. In this particular example, we're just using a type that implements `Display` and `PartialEq`,
use dioxus::prelude::*;
use std::fmt::Display;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
generic_child { data: 0 }
}
}
#[derive(PartialEq, Props, Clone)]
struct GenericChildProps<T: Display + PartialEq + Clone + 'static> {
data: T,
}
fn generic_child<T: Display + PartialEq + Clone>(props: GenericChildProps<T>) -> Element {
rsx! {
div { "{props.data}" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/shorthand.rs | examples/09-reference/shorthand.rs | //! Dioxus supports shorthand syntax for creating elements and components.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let a = 123;
let b = 456;
let c = 789;
let class = "class";
let id = "id";
// todo: i'd like it for children on elements to be inferred as the children of the element
// also should shorthands understand references/dereferences?
// ie **a, *a, &a, &mut a, etc
let children = rsx! { "Child" };
let onclick = move |_| println!("Clicked!");
rsx! {
div { class, id, {&children} }
Component { a, b, c, children, onclick }
Component { a, ..ComponentProps { a: 1, b: 2, c: 3, children: VNode::empty(), onclick: Default::default() } }
}
}
#[component]
fn Component(
a: i32,
b: i32,
c: i32,
children: Element,
onclick: EventHandler<MouseEvent>,
) -> Element {
rsx! {
div { "{a}" }
div { "{b}" }
div { "{c}" }
div { {children} }
div { onclick }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/simple_list.rs | examples/09-reference/simple_list.rs | //! A few ways of mapping elements into rsx! syntax
//!
//! Rsx allows anything that's an iterator where the output type implements Into<Element>, so you can use any of the following:
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx!(
div {
// Use Map directly to lazily pull elements
{(0..10).map(|f| rsx! { "{f}" })}
// Collect into an intermediate collection if necessary, and call into_iter
{["a", "b", "c", "d", "e", "f"]
.into_iter()
.map(|f| rsx! { "{f}" })
.collect::<Vec<_>>()
.into_iter()}
// Use optionals
{Some(rsx! { "Some" })}
// use a for loop where the body itself is RSX
for name in 0..10 {
div { "{name}" }
}
// Or even use an unterminated conditional
if true {
"hello world!"
}
}
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/spread.rs | examples/09-reference/spread.rs | //! This example demonstrates how to use the spread operator to pass attributes to child components.
//!
//! This lets components like the `Link` allow the user to extend the attributes of the underlying `a` tag.
//! These attributes are bundled into a `Vec<Attribute>` which can be spread into the child component using the `..` operator.
use dioxus::prelude::*;
fn main() {
let dom = VirtualDom::prebuilt(app);
let html = dioxus_ssr::render(&dom);
println!("{}", html);
}
fn app() -> Element {
rsx! {
SpreadableComponent {
width: "10px",
extra_data: "hello{1}",
extra_data2: "hello{2}",
height: "10px",
left: 1,
"data-custom-attribute": "value",
}
}
}
#[derive(Props, PartialEq, Clone)]
struct Props {
#[props(extends = GlobalAttributes)]
attributes: Vec<Attribute>,
extra_data: String,
extra_data2: String,
}
#[component]
fn SpreadableComponent(props: Props) -> Element {
rsx! {
audio { ..props.attributes, "1: {props.extra_data}\n2: {props.extra_data2}" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/all_events.rs | examples/09-reference/all_events.rs | //! This example shows how to listen to all events on a div and log them to the console.
//!
//! The primary demonstration here is the properties on the events themselves, hoping to give you some inspiration
//! on adding interactivity to your own application.
use dioxus::prelude::*;
use std::{collections::VecDeque, fmt::Debug, rc::Rc};
const STYLE: Asset = asset!("/examples/assets/events.css");
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Using a VecDeque so its cheap to pop old events off the front
let mut events = use_signal(VecDeque::new);
// All events and their data implement Debug, so we can re-cast them as Rc<dyn Debug> instead of their specific type
let mut log_event = move |event: Rc<dyn Debug>| {
// Only store the last 20 events
if events.read().len() >= 20 {
events.write().pop_front();
}
events.write().push_back(event);
};
let random_text = "This is some random repeating text. ".repeat(1000);
rsx! {
Stylesheet { href: STYLE }
div { id: "container",
// focusing is necessary to catch keyboard events
div { id: "receiver", tabindex: 0,
onmousemove: move |event| log_event(event.data()),
onclick: move |event| log_event(event.data()),
ondoubleclick: move |event| log_event(event.data()),
onmousedown: move |event| log_event(event.data()),
onmouseup: move |event| log_event(event.data()),
onwheel: move |event| log_event(event.data()),
onkeydown: move |event| log_event(event.data()),
onkeyup: move |event| log_event(event.data()),
onkeypress: move |event| log_event(event.data()),
onfocusin: move |event| log_event(event.data()),
onfocusout: move |event| log_event(event.data()),
"Hover, click, type or scroll to see the info down below"
}
div {
style: "padding: 50px;",
div {
style: "text-align: center; padding: 20px; font-family: sans-serif; overflow: auto; height: 400px;",
onscroll: move |event: Event<ScrollData>| {
log_event(event.data());
},
div { style: "margin: 20px; padding: 15px; border: 1px solid #ccc; border-radius: 5px;",
p { "{random_text}" }
}
}
}
div { id: "log",
for event in events.read().iter() {
div { "{event:?}" }
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/09-reference/optional_props.rs | examples/09-reference/optional_props.rs | //! Optional props
//!
//! This example demonstrates how to use optional props in your components. The `Button` component has several props,
//! and we use a variety of attributes to set them.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
// We can set some of the props, and the rest will be filled with their default values
// By default `c` can take a `None` value, but `d` is required to wrap a `Some` value
Button {
a: "asd".to_string(),
// b can be omitted, and it will be filled with its default value
c: "asd".to_string(),
d: Some("asd".to_string()),
e: Some("asd".to_string()),
}
Button {
a: "asd".to_string(),
b: "asd".to_string(),
// We can omit the `Some` on `c` since Dioxus automatically transforms Option<T> into optional
c: "asd".to_string(),
d: Some("asd".to_string()),
e: "asd".to_string(),
}
// `b` and `e` are omitted
Button {
a: "asd".to_string(),
c: "asd".to_string(),
d: Some("asd".to_string()),
}
}
}
#[derive(Props, PartialEq, Clone)]
struct ButtonProps {
a: String,
#[props(default)]
b: String,
c: Option<String>,
#[props(!optional)]
d: Option<String>,
#[props(optional)]
e: SthElse<String>,
}
type SthElse<T> = Option<T>;
#[allow(non_snake_case)]
fn Button(props: ButtonProps) -> Element {
rsx! {
button {
"{props.a} | "
"{props.b:?} | "
"{props.c:?} | "
"{props.d:?} | "
"{props.e:?}"
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/bevy/src/bevy_scene_plugin.rs | examples/10-integrations/bevy/src/bevy_scene_plugin.rs | use crate::bevy_renderer::UIData;
use bevy::prelude::*;
#[derive(Component)]
pub struct DynamicColoredCube;
pub struct BevyScenePlugin {}
impl Plugin for BevyScenePlugin {
fn build(&self, app: &mut App) {
app.insert_resource(ClearColor(bevy::color::Color::srgba(0.0, 0.0, 0.0, 0.0)));
app.add_systems(Startup, setup);
app.add_systems(Update, (animate, update_cube_color));
}
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: bevy::color::Color::srgb(1.0, 0.0, 0.0),
metallic: 0.0,
perceptual_roughness: 0.5,
..default()
})),
Transform::from_xyz(0.0, 0.0, 0.0),
DynamicColoredCube,
));
commands.spawn((
DirectionalLight {
color: bevy::color::Color::WHITE,
illuminance: 10000.0,
shadows_enabled: false,
..default()
},
Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
));
commands.insert_resource(AmbientLight {
color: bevy::color::Color::WHITE,
brightness: 100.0,
affects_lightmapped_meshes: true,
});
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 0.0, 3.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
Name::new("MainCamera"),
));
}
fn animate(time: Res<Time>, mut cube_query: Query<&mut Transform, With<DynamicColoredCube>>) {
for mut transform in cube_query.iter_mut() {
transform.rotation = Quat::from_rotation_y(time.elapsed_secs());
transform.translation.x = (time.elapsed_secs() * 2.0).sin() * 0.5;
}
}
fn update_cube_color(
ui: Res<UIData>,
cube_query: Query<&MeshMaterial3d<StandardMaterial>, With<DynamicColoredCube>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
if ui.is_changed() {
for mesh_material in cube_query.iter() {
if let Some(material) = materials.get_mut(&mesh_material.0) {
let [r, g, b] = ui.color;
material.base_color = bevy::color::Color::srgb(r, g, b);
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/bevy/src/bevy_renderer.rs | examples/10-integrations/bevy/src/bevy_renderer.rs | use crate::bevy_scene_plugin::BevyScenePlugin;
use bevy::{
camera::{ManualTextureViewHandle, RenderTarget},
prelude::*,
render::{
render_resource::TextureFormat,
renderer::{
RenderAdapter, RenderAdapterInfo, RenderDevice, RenderInstance, RenderQueue,
WgpuWrapper,
},
settings::{RenderCreation, RenderResources},
texture::ManualTextureView,
RenderPlugin,
},
};
use dioxus_native::{CustomPaintCtx, DeviceHandle, TextureHandle};
use std::sync::Arc;
#[derive(Resource, Default)]
pub struct UIData {
pub color: [f32; 3],
}
pub struct BevyRenderer {
app: App,
wgpu_device: wgpu::Device,
last_texture_size: (u32, u32),
texture_handle: Option<TextureHandle>,
manual_texture_view_handle: Option<ManualTextureViewHandle>,
}
impl BevyRenderer {
pub fn new(device_handle: &DeviceHandle) -> Self {
// Create a headless Bevy App.
let mut app = App::new();
app.add_plugins(
DefaultPlugins
.set(RenderPlugin {
// Reuse the render resources from the Dioxus native renderer.
render_creation: RenderCreation::Manual(RenderResources(
RenderDevice::new(WgpuWrapper::new(device_handle.device.clone())),
RenderQueue(Arc::new(WgpuWrapper::new(device_handle.queue.clone()))),
RenderAdapterInfo(WgpuWrapper::new(device_handle.adapter.get_info())),
RenderAdapter(Arc::new(WgpuWrapper::new(device_handle.adapter.clone()))),
RenderInstance(Arc::new(WgpuWrapper::new(device_handle.instance.clone()))),
)),
synchronous_pipeline_compilation: true,
..default()
})
.set(WindowPlugin {
primary_window: None,
exit_condition: bevy::window::ExitCondition::DontExit,
close_when_requested: false,
..Default::default()
})
.disable::<bevy::winit::WinitPlugin>(),
);
// Setup the rendering to texture.
app.insert_resource(ManualTextureViews::default());
// Add data from the UI.
app.insert_resource(UIData::default());
// Add the Bevy scene.
app.add_plugins(BevyScenePlugin {});
// Initialize the app to set up the render world properly.
app.finish();
app.cleanup();
Self {
app,
wgpu_device: device_handle.device.clone(),
last_texture_size: (0, 0),
texture_handle: None,
manual_texture_view_handle: None,
}
}
pub fn render(
&mut self,
ctx: CustomPaintCtx<'_>,
color: [f32; 3],
width: u32,
height: u32,
_start_time: &std::time::Instant,
) -> Option<TextureHandle> {
// Update the UI data.
if let Some(mut ui) = self.app.world_mut().get_resource_mut::<UIData>() {
ui.color = color;
}
// Init self.texture_handle if None or if width/height changed.
self.init_texture(ctx, width, height);
// Run one frame of the Bevy app to render the 3D scene.
self.app.update();
self.texture_handle.clone()
}
fn init_texture(&mut self, mut ctx: CustomPaintCtx<'_>, width: u32, height: u32) {
// Reuse self.texture_handle if already initialized to the correct size.
let current_size = (width, height);
if self.texture_handle.is_some() && self.last_texture_size == current_size {
return;
}
let world = self.app.world_mut();
// Skip if no camera.
if world.query::<&Camera>().single(world).is_err() {
return;
}
if let Some(mut manual_texture_views) = world.get_resource_mut::<ManualTextureViews>() {
// Clean previous texture if any.
if self.texture_handle.is_some() {
ctx.unregister_texture(self.texture_handle.take().unwrap());
}
if let Some(old_handle) = self.manual_texture_view_handle {
manual_texture_views.remove(&old_handle);
self.manual_texture_view_handle = None;
}
// Create the texture for the camera target and the CustomPaintCtx.
let format = TextureFormat::Rgba8UnormSrgb;
let wgpu_texture = self.wgpu_device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let wgpu_texture_view =
wgpu_texture.create_view(&wgpu::TextureViewDescriptor::default());
let manual_texture_view = ManualTextureView {
texture_view: wgpu_texture_view.into(),
size: bevy::math::UVec2::new(width, height),
format,
};
let manual_texture_view_handle = ManualTextureViewHandle(0);
manual_texture_views.insert(manual_texture_view_handle, manual_texture_view);
if let Ok(mut camera) = world.query::<&mut Camera>().single_mut(world) {
camera.target = RenderTarget::TextureView(manual_texture_view_handle);
self.last_texture_size = current_size;
self.manual_texture_view_handle = Some(manual_texture_view_handle);
self.texture_handle = Some(ctx.register_texture(wgpu_texture));
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/bevy/src/main.rs | examples/10-integrations/bevy/src/main.rs | use std::any::Any;
use color::{palette::css::WHITE, parse_color};
use color::{OpaqueColor, Srgb};
use demo_renderer::{DemoMessage, DemoPaintSource};
use dioxus_native::prelude::*;
use dioxus_native::use_wgpu;
use wgpu::Limits;
mod bevy_renderer;
mod bevy_scene_plugin;
mod demo_renderer;
// CSS Styles
static STYLES: Asset = asset!("/src/styles.css");
type Color = OpaqueColor<Srgb>;
fn limits() -> Limits {
Limits {
max_storage_buffers_per_shader_stage: 12,
..Limits::default()
}
}
fn main() {
#[cfg(feature = "tracing")]
tracing_subscriber::fmt::init();
let config: Vec<Box<dyn Any>> = vec![Box::new(limits())];
dioxus_native::launch_cfg(app, Vec::new(), config);
}
fn app() -> Element {
let mut show_cube = use_signal(|| true);
let color_str = use_signal(|| String::from("red"));
let color = use_memo(move || {
parse_color(&color_str())
.map(|c| c.to_alpha_color())
.unwrap_or(WHITE)
.split()
.0
});
use_effect(move || println!("{:?}", color().components));
rsx!(
Stylesheet { href: STYLES }
div { id:"overlay",
h2 { "Control Panel" },
button {
onclick: move |_| show_cube.toggle(),
if show_cube() {
"Hide cube"
} else {
"Show cube"
}
}
br {}
ColorControl { label: "Color:", color_str },
p { "This overlay demonstrates that the custom Bevy content can be rendered beneath layers of HTML content" }
}
div { id:"underlay",
h2 { "Underlay" },
p { "This underlay demonstrates that the custom Bevy content can be rendered above layers and blended with the content underneath" }
}
header {
h1 { "Blitz Bevy Demo" }
}
if show_cube() {
SpinningCube { color }
}
)
}
#[component]
fn ColorControl(label: &'static str, color_str: WriteSignal<String>) -> Element {
rsx!(div {
class: "color-control",
{ label },
input {
value: color_str(),
oninput: move |evt| {
*color_str.write() = evt.value()
}
}
})
}
#[component]
fn SpinningCube(color: Memo<Color>) -> Element {
// Create custom paint source and register it with the renderer
let paint_source = DemoPaintSource::new();
let sender = paint_source.sender();
let paint_source_id = use_wgpu(move || paint_source);
use_effect(move || {
sender.send(DemoMessage::SetColor(color())).unwrap();
});
rsx!(
div { id:"canvas-container",
canvas {
id: "demo-canvas",
"src": paint_source_id
}
}
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/bevy/src/demo_renderer.rs | examples/10-integrations/bevy/src/demo_renderer.rs | use crate::bevy_renderer::BevyRenderer;
use crate::Color;
use dioxus_native::{CustomPaintCtx, CustomPaintSource, DeviceHandle, TextureHandle};
use std::sync::mpsc::{channel, Receiver, Sender};
pub enum DemoMessage {
// Color in RGB format
SetColor(Color),
}
enum DemoRendererState {
Active(Box<BevyRenderer>),
Suspended,
}
pub struct DemoPaintSource {
state: DemoRendererState,
start_time: std::time::Instant,
tx: Sender<DemoMessage>,
rx: Receiver<DemoMessage>,
color: Color,
}
impl DemoPaintSource {
pub fn new() -> Self {
let (tx, rx) = channel();
Self::with_channel(tx, rx)
}
pub fn with_channel(tx: Sender<DemoMessage>, rx: Receiver<DemoMessage>) -> Self {
Self {
state: DemoRendererState::Suspended,
start_time: std::time::Instant::now(),
tx,
rx,
color: Color::WHITE,
}
}
pub fn sender(&self) -> Sender<DemoMessage> {
self.tx.clone()
}
fn process_messages(&mut self) {
loop {
match self.rx.try_recv() {
Err(_) => return,
Ok(msg) => match msg {
DemoMessage::SetColor(color) => self.color = color,
},
}
}
}
fn render(
&mut self,
ctx: CustomPaintCtx<'_>,
width: u32,
height: u32,
) -> Option<TextureHandle> {
if width == 0 || height == 0 {
return None;
}
let DemoRendererState::Active(state) = &mut self.state else {
return None;
};
state.render(ctx, self.color.components, width, height, &self.start_time)
}
}
impl CustomPaintSource for DemoPaintSource {
fn resume(&mut self, device_handle: &DeviceHandle) {
let active_state = BevyRenderer::new(device_handle);
self.state = DemoRendererState::Active(Box::new(active_state));
}
fn suspend(&mut self) {
self.state = DemoRendererState::Suspended;
}
fn render(
&mut self,
ctx: CustomPaintCtx<'_>,
width: u32,
height: u32,
_scale: f64,
) -> Option<TextureHandle> {
self.process_messages();
self.render(ctx, width, height)
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/native-headless-in-bevy/src/bevy_scene_plugin.rs | examples/10-integrations/native-headless-in-bevy/src/bevy_scene_plugin.rs | use crate::ui::{UIMessage, UiState};
use bevy::input::mouse::{MouseButton, MouseMotion};
use bevy::prelude::*;
use crossbeam_channel::{Receiver, Sender};
#[derive(Component)]
pub struct DynamicCube;
#[derive(Component)]
pub struct OrbitCamera {
pub distance: f32,
pub yaw: f32,
pub pitch: f32,
pub sensitivity: f32,
}
impl Default for OrbitCamera {
fn default() -> Self {
Self {
distance: 3.0,
yaw: 0.0,
pitch: 0.0,
sensitivity: 0.01,
}
}
}
#[derive(Resource, Deref)]
struct UIMessageSender(Sender<UIMessage>);
#[derive(Resource, Deref)]
struct UIMessageReceiver(Receiver<UIMessage>);
#[derive(Resource)]
struct CubeTranslationSpeed(f32);
impl Default for CubeTranslationSpeed {
fn default() -> Self {
Self(UiState::DEFAULT_CUBE_TRANSLATION_SPEED)
}
}
#[derive(Resource)]
struct CubeRotationSpeed(f32);
impl Default for CubeRotationSpeed {
fn default() -> Self {
Self(UiState::DEFAULT_CUBE_ROTATION_SPEED)
}
}
pub struct BevyScenePlugin {
pub app_sender: Sender<UIMessage>,
pub ui_receiver: Receiver<UIMessage>,
}
impl Plugin for BevyScenePlugin {
fn build(&self, app: &mut App) {
app.insert_resource(ClearColor(bevy::color::Color::srgba(0.0, 0.0, 0.0, 0.0)));
app.insert_resource(UIMessageSender(self.app_sender.clone()));
app.insert_resource(UIMessageReceiver(self.ui_receiver.clone()));
app.insert_resource(CubeTranslationSpeed::default());
app.insert_resource(CubeRotationSpeed::default());
app.add_systems(Startup, setup);
app.add_systems(Update, (sync_with_ui, animate, orbit_camera_system));
}
}
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(StandardMaterial {
base_color: Color::Srgba(bevy::color::Srgba::from_f32_array(
UiState::DEFAULT_CUBE_COLOR,
)),
metallic: 0.0,
perceptual_roughness: 0.5,
..default()
})),
Transform::from_xyz(0.0, 0.0, 0.0),
DynamicCube,
));
commands.spawn((
DirectionalLight {
color: bevy::color::Color::WHITE,
illuminance: 10000.0,
shadows_enabled: false,
..default()
},
Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
));
commands.insert_resource(AmbientLight {
color: bevy::color::Color::WHITE,
brightness: 100.0,
affects_lightmapped_meshes: true,
});
commands.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 0.0, 3.0).looking_at(Vec3::new(0.0, 0.0, 0.0), Vec3::Y),
Name::new("MainCamera"),
OrbitCamera::default(),
));
}
fn sync_with_ui(
sender: Res<UIMessageSender>,
receiver: Res<UIMessageReceiver>,
cube_query: Query<&MeshMaterial3d<StandardMaterial>, With<DynamicCube>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut translation_speed: ResMut<CubeTranslationSpeed>,
mut rotation_speed: ResMut<CubeRotationSpeed>,
time: Res<Time>,
) {
let fps = 1000.0 / time.delta().as_millis() as f32;
sender.send(UIMessage::Fps(fps)).unwrap();
while let Ok(message) = receiver.try_recv() {
match message {
UIMessage::CubeColor(c) => {
for cube_material in cube_query.iter() {
if let Some(material) = materials.get_mut(&cube_material.0) {
material.base_color = Color::Srgba(bevy::color::Srgba::from_f32_array(c));
}
}
}
UIMessage::CubeTranslationSpeed(speed) => {
translation_speed.0 = speed;
}
UIMessage::CubeRotationSpeed(speed) => {
rotation_speed.0 = speed;
}
_ => {}
}
}
}
fn animate(
time: Res<Time>,
mut cube_query: Query<&mut Transform, With<DynamicCube>>,
translation_speed: Res<CubeTranslationSpeed>,
rotation_speed: Res<CubeRotationSpeed>,
) {
for mut transform in cube_query.iter_mut() {
transform.rotation = Quat::from_rotation_y(time.elapsed_secs() * rotation_speed.0);
transform.translation.x = (time.elapsed_secs() * translation_speed.0).sin() * 0.5;
}
}
fn orbit_camera_system(
mut camera_query: Query<(&mut Transform, &mut OrbitCamera), With<Camera3d>>,
mut mouse_motion_events: MessageReader<MouseMotion>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
) {
for (mut transform, mut orbit_camera) in camera_query.iter_mut() {
// Handle mouse input for camera rotation
if mouse_button_input.pressed(MouseButton::Left) {
for mouse_motion in mouse_motion_events.read() {
orbit_camera.yaw -= mouse_motion.delta.x * orbit_camera.sensitivity;
orbit_camera.pitch -= mouse_motion.delta.y * orbit_camera.sensitivity;
// Clamp pitch to prevent camera flipping
orbit_camera.pitch = orbit_camera.pitch.clamp(-1.5, 1.5);
}
}
// Calculate camera position based on spherical coordinates
let yaw_quat = Quat::from_rotation_y(orbit_camera.yaw);
let pitch_quat = Quat::from_rotation_x(orbit_camera.pitch);
let rotation = yaw_quat * pitch_quat;
let position = rotation * Vec3::new(0.0, 0.0, orbit_camera.distance);
transform.translation = position;
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/native-headless-in-bevy/src/dioxus_in_bevy_plugin.rs | examples/10-integrations/native-headless-in-bevy/src/dioxus_in_bevy_plugin.rs | use std::rc::Rc;
use std::sync::Arc;
use std::time::Instant;
use bevy::asset::RenderAssetUsages;
use bevy::prelude::*;
use bevy::{
input::{
keyboard::{Key as BevyKey, KeyCode as BevyKeyCode, KeyboardInput},
mouse::{MouseButton, MouseButtonInput},
ButtonInput, ButtonState, InputSystems,
},
render::{
render_asset::RenderAssets,
render_graph::{self, NodeRunError, RenderGraph, RenderGraphContext, RenderLabel},
render_resource::{Extent3d, TextureDimension, TextureFormat},
renderer::{RenderContext, RenderDevice, RenderQueue},
texture::GpuImage,
Extract, RenderApp,
},
window::{CursorMoved, WindowResized},
};
use anyrender_vello::VelloScenePainter;
use blitz_dom::{Document as _, DocumentConfig};
use blitz_paint::paint_scene;
use blitz_traits::events::{
BlitzKeyEvent, BlitzMouseButtonEvent, KeyState, MouseEventButton, MouseEventButtons, UiEvent,
};
use blitz_traits::net::{NetCallback, NetProvider};
use blitz_traits::shell::{ColorScheme, Viewport};
use bytes::Bytes;
use crossbeam_channel::{Receiver, Sender};
use data_url::DataUrl;
use dioxus::prelude::*;
use dioxus_devtools::DevserverMsg;
use dioxus_native_dom::DioxusDocument;
use vello::{
peniko::color::AlphaColor, RenderParams, Renderer as VelloRenderer, RendererOptions, Scene,
};
// Constant scale factor and color scheme for example purposes
const SCALE_FACTOR: f32 = 1.0;
const COLOR_SCHEME: ColorScheme = ColorScheme::Light;
const CATCH_EVENTS_CLASS: &str = "catch-events";
pub struct DioxusInBevyPlugin<UIProps> {
pub ui: fn(props: UIProps) -> Element,
pub props: UIProps,
}
#[derive(Resource)]
struct AnimationTime(Instant);
impl<UIProps: std::marker::Send + std::marker::Sync + std::clone::Clone + 'static> Plugin
for DioxusInBevyPlugin<UIProps>
{
fn build(&self, app: &mut App) {
let epoch = AnimationTime(Instant::now());
let (s, r) = crossbeam_channel::unbounded();
// Create the dioxus virtual dom and the dioxus-native document
// The viewport will be set in setup_ui after we get the window size
let vdom = VirtualDom::new_with_props(self.ui, self.props.clone());
// FIXME add a NetProvider
let mut dioxus_doc = DioxusDocument::new(vdom, DocumentConfig::default());
// Setup NetProvider
let net_provider = BevyNetProvider::shared(s.clone());
dioxus_doc.set_net_provider(net_provider);
// Setup DocumentProxy to process CreateHeadElement messages
let proxy = Rc::new(DioxusDocumentProxy::new(s.clone()));
dioxus_doc.vdom.in_scope(ScopeId::ROOT, move || {
provide_context(proxy as Rc<dyn dioxus::document::Document>);
});
dioxus_doc.initial_build();
dioxus_doc.resolve(0.0);
// Dummy waker
struct NullWake;
impl std::task::Wake for NullWake {
fn wake(self: std::sync::Arc<Self>) {}
}
let waker = std::task::Waker::from(std::sync::Arc::new(NullWake));
// Setup devtools listener for hot-reloading
dioxus_devtools::connect(move |msg| s.send(DioxusMessage::Devserver(msg)).unwrap());
app.insert_resource(DioxusMessages(r));
app.insert_non_send_resource(dioxus_doc);
app.insert_non_send_resource(waker);
app.insert_resource(epoch);
app.add_systems(Startup, setup_ui);
app.add_systems(
PreUpdate,
(
handle_window_resize,
handle_mouse_events.after(InputSystems),
handle_keyboard_events.after(InputSystems),
)
.chain(),
);
app.add_systems(Update, update_ui);
}
fn finish(&self, app: &mut App) {
// Add the UI rendrer
let render_app = app.sub_app(RenderApp);
let render_device = render_app.world().resource::<RenderDevice>();
let device = render_device.wgpu_device();
let vello_renderer = VelloRenderer::new(device, RendererOptions::default()).unwrap();
app.insert_non_send_resource(vello_renderer);
// Setup communication between main world and render world, to send
// and receive the texture
let (s, r) = crossbeam_channel::unbounded();
app.insert_resource(MainWorldReceiver(r));
let render_app = app.sub_app_mut(RenderApp);
render_app.add_systems(bevy::render::ExtractSchedule, extract_texture_image);
render_app.insert_resource(RenderWorldSender(s));
// Add a render graph node to get the GPU texture
let mut graph = render_app.world_mut().resource_mut::<RenderGraph>();
graph.add_node(TextureGetterNode, TextureGetterNodeDriver);
graph.add_node_edge(bevy::render::graph::CameraDriverLabel, TextureGetterNode);
}
}
struct RenderTexture {
pub texture_view: wgpu::TextureView,
pub width: u32,
pub height: u32,
}
#[derive(Resource, Deref)]
struct MainWorldReceiver(Receiver<RenderTexture>);
#[derive(Resource, Deref)]
struct RenderWorldSender(Sender<RenderTexture>);
fn create_ui_texture(width: u32, height: u32) -> Image {
let mut image = Image::new_fill(
Extent3d {
width,
height,
depth_or_array_layers: 1,
},
TextureDimension::D2,
&[0u8; 4],
TextureFormat::Rgba8Unorm,
RenderAssetUsages::RENDER_WORLD,
);
image.texture_descriptor.usage = wgpu::TextureUsages::COPY_DST
| wgpu::TextureUsages::STORAGE_BINDING
| wgpu::TextureUsages::TEXTURE_BINDING;
image
}
#[derive(Debug, PartialEq, Eq, Clone, Hash, RenderLabel)]
struct TextureGetterNode;
#[derive(Default)]
struct TextureGetterNodeDriver;
impl render_graph::Node for TextureGetterNodeDriver {
fn update(&mut self, world: &mut World) {
// Get the GPU texture from the texture image, and send it to the main world
if let Some(sender) = world.get_resource::<RenderWorldSender>() {
if let Some(image) = world
.get_resource::<ExtractedTextureImage>()
.and_then(|e| e.0.as_ref())
{
if let Some(gpu_images) = world
.get_resource::<RenderAssets<GpuImage>>()
.and_then(|a| a.get(image))
{
let _ = sender.send(RenderTexture {
texture_view: (*gpu_images.texture_view).clone(),
width: gpu_images.size.width,
height: gpu_images.size.height,
});
if let Some(mut extracted_image) =
world.get_resource_mut::<ExtractedTextureImage>()
{
// Reset the image, so it is not sent again, unless it changes
extracted_image.0 = None;
}
}
}
}
}
fn run(
&self,
_graph: &mut RenderGraphContext,
_render_context: &mut RenderContext,
_world: &World,
) -> bevy::prelude::Result<(), NodeRunError> {
Ok(())
}
}
#[derive(Resource)]
pub struct TextureImage(Handle<Image>);
#[derive(Resource)]
pub struct ExtractedTextureImage(Option<Handle<Image>>);
fn extract_texture_image(
mut commands: Commands,
texture_image: Extract<Option<Res<TextureImage>>>,
mut last_texture_image: Local<Option<Handle<Image>>>,
) {
if let Some(texture_image) = texture_image.as_ref() {
if let Some(last_texture_image) = &*last_texture_image {
if last_texture_image == &texture_image.0 {
return;
}
}
commands.insert_resource(ExtractedTextureImage(Some(texture_image.0.clone())));
*last_texture_image = Some(texture_image.0.clone());
}
}
struct HeadElement {
name: String,
attributes: Vec<(String, String)>,
contents: Option<String>,
}
enum DioxusMessage {
Devserver(DevserverMsg),
CreateHeadElement(HeadElement),
ResourceLoad(blitz_dom::net::Resource),
}
#[derive(Resource, Deref)]
struct DioxusMessages(Receiver<DioxusMessage>);
#[derive(Component)]
pub struct DioxusUiQuad;
fn setup_ui(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
mut images: ResMut<Assets<Image>>,
mut dioxus_doc: NonSendMut<DioxusDocument>,
mut animation_epoch: ResMut<AnimationTime>,
windows: Query<&Window>,
) {
let window = windows
.iter()
.next()
.expect("Should have at least one window");
let width = window.physical_width();
let height = window.physical_height();
debug!("Initial window size: {}x{}", width, height);
// Set the initial viewport
animation_epoch.0 = Instant::now();
dioxus_doc.set_viewport(Viewport::new(width, height, SCALE_FACTOR, COLOR_SCHEME));
dioxus_doc.resolve(0.0);
// Create Bevy Image from the texture data
let image = create_ui_texture(width, height);
let handle = images.add(image);
// Create a quad to display the texture
commands.spawn((
Mesh2d(meshes.add(Rectangle::new(1.0, 1.0))),
MeshMaterial2d(materials.add(ColorMaterial {
texture: Some(handle.clone()),
..default()
})),
Transform::from_scale(Vec3::new(width as f32, height as f32, 0.0)),
DioxusUiQuad,
));
commands.spawn((
Camera2d,
Camera {
order: isize::MAX,
..default()
},
));
commands.insert_resource(TextureImage(handle));
}
#[allow(clippy::too_many_arguments)]
fn update_ui(
mut dioxus_doc: NonSendMut<DioxusDocument>,
dioxus_messages: Res<DioxusMessages>,
waker: NonSendMut<std::task::Waker>,
vello_renderer: Option<NonSendMut<VelloRenderer>>,
render_device: Res<RenderDevice>,
render_queue: Res<RenderQueue>,
receiver: Res<MainWorldReceiver>,
animation_epoch: Res<AnimationTime>,
mut cached_texture: Local<Option<RenderTexture>>,
) {
while let Ok(msg) = dioxus_messages.0.try_recv() {
match msg {
DioxusMessage::Devserver(devserver_msg) => match devserver_msg {
dioxus_devtools::DevserverMsg::HotReload(hotreload_message) => {
// Apply changes to vdom
dioxus_devtools::apply_changes(&dioxus_doc.vdom, &hotreload_message);
// Reload changed assets
for asset_path in &hotreload_message.assets {
if let Some(url) = asset_path.to_str() {
dioxus_doc.reload_resource_by_href(url);
}
}
}
dioxus_devtools::DevserverMsg::FullReloadStart => {}
_ => {}
},
DioxusMessage::CreateHeadElement(el) => {
dioxus_doc.create_head_element(&el.name, &el.attributes, &el.contents);
dioxus_doc.poll(Some(std::task::Context::from_waker(&waker)));
}
DioxusMessage::ResourceLoad(resource) => {
dioxus_doc.load_resource(resource);
}
};
}
while let Ok(texture) = receiver.try_recv() {
*cached_texture = Some(texture);
}
if let (Some(texture), Some(mut vello_renderer)) = ((*cached_texture).as_ref(), vello_renderer)
{
// Poll the vdom
dioxus_doc.poll(Some(std::task::Context::from_waker(&waker)));
// Refresh the document
let animation_time = animation_epoch.0.elapsed().as_secs_f64();
dioxus_doc.resolve(animation_time);
// Create a `vello::Scene` to paint into
let mut scene = Scene::new();
// Paint the document
paint_scene(
&mut VelloScenePainter::new(&mut scene),
&dioxus_doc,
SCALE_FACTOR as f64,
texture.width,
texture.height,
);
// Render the `vello::Scene` to the Texture using the `VelloRenderer`
vello_renderer
.render_to_texture(
render_device.wgpu_device(),
render_queue.into_inner(),
&scene,
&texture.texture_view,
&RenderParams {
base_color: AlphaColor::TRANSPARENT,
width: texture.width,
height: texture.height,
antialiasing_method: vello::AaConfig::Msaa16,
},
)
.expect("failed to render to texture");
}
}
fn handle_window_resize(
mut dioxus_doc: NonSendMut<DioxusDocument>,
mut resize_events: MessageReader<WindowResized>,
mut commands: Commands,
mut images: ResMut<Assets<Image>>,
mut materials: ResMut<Assets<ColorMaterial>>,
texture_image: Option<Res<TextureImage>>,
mut query: Query<(&mut Transform, &mut MeshMaterial2d<ColorMaterial>), With<DioxusUiQuad>>,
) {
for resize_event in resize_events.read() {
let width = resize_event.width as u32;
let height = resize_event.height as u32;
debug!("Window resized to: {}x{}", width, height);
// Update the dioxus viewport
dioxus_doc.set_viewport(Viewport::new(width, height, SCALE_FACTOR, COLOR_SCHEME));
// dioxus_doc.resolve();
// Create a new texture with the new size
let new_image = create_ui_texture(width, height);
let new_handle = images.add(new_image);
// Update the quad mesh to match the new size
if let Ok((mut trans, mut mat)) = query.single_mut() {
*trans = Transform::from_scale(Vec3::new(width as f32, height as f32, 0.0));
materials.get_mut(&mut mat.0).unwrap().texture = Some(new_handle.clone());
}
// Remove the old texture
if let Some(texture_image) = texture_image.as_ref() {
images.remove(&texture_image.0);
}
// Insert the new texture resource
commands.insert_resource(TextureImage(new_handle));
}
}
#[derive(Resource, Default)]
pub struct MouseState {
pub x: f32,
pub y: f32,
pub buttons: MouseEventButtons,
pub mods: Modifiers,
}
fn does_catch_events(dioxus_doc: &DioxusDocument, node_id: usize) -> bool {
if let Some(node) = dioxus_doc.get_node(node_id) {
let class = node.attr(blitz_dom::local_name!("class")).unwrap_or("");
if class
.split_whitespace()
.any(|word| word == CATCH_EVENTS_CLASS)
{
true
} else if let Some(parent) = node.parent {
does_catch_events(dioxus_doc, parent)
} else {
false
}
} else {
false
}
}
fn handle_mouse_events(
mut dioxus_doc: NonSendMut<DioxusDocument>,
mut cursor_moved: MessageReader<CursorMoved>,
mut mouse_button_input_events: ResMut<Messages<MouseButtonInput>>,
mut mouse_buttons: ResMut<ButtonInput<MouseButton>>,
mut last_mouse_state: Local<MouseState>,
) {
if cursor_moved.is_empty() && mouse_button_input_events.is_empty() {
return;
}
let mouse_state = &mut last_mouse_state;
for cursor_event in cursor_moved.read() {
mouse_state.x = cursor_event.position.x;
mouse_state.y = cursor_event.position.y;
dioxus_doc.handle_ui_event(UiEvent::MouseMove(BlitzMouseButtonEvent {
x: mouse_state.x,
y: mouse_state.y,
button: Default::default(),
buttons: mouse_state.buttons,
mods: mouse_state.mods,
}));
}
for event in mouse_button_input_events
.get_cursor()
.read(&mouse_button_input_events)
{
let button_blitz = match event.button {
MouseButton::Left => MouseEventButton::Main,
MouseButton::Right => MouseEventButton::Secondary,
MouseButton::Middle => MouseEventButton::Auxiliary,
MouseButton::Back => MouseEventButton::Fourth,
MouseButton::Forward => MouseEventButton::Fifth,
_ => continue,
};
let buttons_blitz = MouseEventButtons::from(button_blitz);
match event.state {
ButtonState::Pressed => {
mouse_state.buttons |= buttons_blitz;
dioxus_doc.handle_ui_event(UiEvent::MouseDown(BlitzMouseButtonEvent {
x: mouse_state.x,
y: mouse_state.y,
button: button_blitz,
buttons: mouse_state.buttons,
mods: mouse_state.mods,
}));
}
ButtonState::Released => {
mouse_state.buttons &= !buttons_blitz;
dioxus_doc.handle_ui_event(UiEvent::MouseUp(BlitzMouseButtonEvent {
x: mouse_state.x,
y: mouse_state.y,
button: button_blitz,
buttons: mouse_state.buttons,
mods: mouse_state.mods,
}));
}
}
}
let should_catch_events = dioxus_doc
.hit(mouse_state.x, mouse_state.y)
.map(|hit| does_catch_events(&dioxus_doc, hit.node_id))
.unwrap_or(false);
if should_catch_events {
mouse_button_input_events.clear();
mouse_buttons.reset_all();
}
// dioxus_doc.resolve();
}
fn handle_keyboard_events(
mut dioxus_doc: NonSendMut<DioxusDocument>,
mut keyboard_input_events: ResMut<Messages<KeyboardInput>>,
mut keys: ResMut<ButtonInput<BevyKeyCode>>,
mut last_mouse_state: Local<MouseState>,
) {
if keyboard_input_events.is_empty() {
return;
}
for event in keyboard_input_events
.get_cursor()
.read(&keyboard_input_events)
{
let modifier = match event.logical_key {
BevyKey::Alt => Some(Modifiers::ALT),
BevyKey::AltGraph => Some(Modifiers::ALT_GRAPH),
BevyKey::CapsLock => Some(Modifiers::CAPS_LOCK),
BevyKey::Control => Some(Modifiers::CONTROL),
BevyKey::Fn => Some(Modifiers::FN),
BevyKey::FnLock => Some(Modifiers::FN_LOCK),
BevyKey::NumLock => Some(Modifiers::NUM_LOCK),
BevyKey::ScrollLock => Some(Modifiers::SCROLL_LOCK),
BevyKey::Shift => Some(Modifiers::SHIFT),
BevyKey::Symbol => Some(Modifiers::SYMBOL),
BevyKey::SymbolLock => Some(Modifiers::SYMBOL_LOCK),
BevyKey::Meta => Some(Modifiers::META),
BevyKey::Hyper => Some(Modifiers::HYPER),
BevyKey::Super => Some(Modifiers::SUPER),
_ => None,
};
if let Some(modifier) = modifier {
match event.state {
ButtonState::Pressed => last_mouse_state.mods.insert(modifier),
ButtonState::Released => last_mouse_state.mods.remove(modifier),
};
}
let key_state = match event.state {
ButtonState::Pressed => KeyState::Pressed,
ButtonState::Released => KeyState::Released,
};
let blitz_key_event = BlitzKeyEvent {
key: bevy_key_to_blitz_key(&event.logical_key),
code: bevy_key_code_to_blitz_code(&event.key_code),
modifiers: last_mouse_state.mods,
location: Location::Standard,
is_auto_repeating: event.repeat,
is_composing: false,
state: key_state,
text: event.text.clone(),
};
match key_state {
KeyState::Pressed => {
dioxus_doc.handle_ui_event(UiEvent::KeyDown(blitz_key_event));
}
KeyState::Released => {
dioxus_doc.handle_ui_event(UiEvent::KeyUp(blitz_key_event));
}
}
}
let should_catch_events = dioxus_doc
.hit(last_mouse_state.x, last_mouse_state.y)
.map(|hit| does_catch_events(&dioxus_doc, hit.node_id))
.unwrap_or(false);
if should_catch_events {
keyboard_input_events.clear();
keys.reset_all();
}
// dioxus_doc.resolve();
}
pub struct DioxusDocumentProxy {
sender: Sender<DioxusMessage>,
}
impl DioxusDocumentProxy {
fn new(sender: Sender<DioxusMessage>) -> Self {
Self { sender }
}
}
impl dioxus::document::Document for DioxusDocumentProxy {
fn eval(&self, _js: String) -> dioxus::document::Eval {
dioxus::document::NoOpDocument.eval(_js)
}
fn create_head_element(
&self,
name: &str,
attributes: &[(&str, String)],
contents: Option<String>,
) {
self.sender
.send(DioxusMessage::CreateHeadElement(HeadElement {
name: name.to_string(),
attributes: attributes
.iter()
.map(|(name, value)| (name.to_string(), value.clone()))
.collect(),
contents,
}))
.unwrap();
}
fn set_title(&self, title: String) {
self.create_head_element("title", &[], Some(title));
}
fn create_meta(&self, props: dioxus::document::MetaProps) {
let attributes = props.attributes();
self.create_head_element("meta", &attributes, None);
}
fn create_script(&self, props: dioxus::document::ScriptProps) {
let attributes = props.attributes();
self.create_head_element("script", &attributes, props.script_contents().ok());
}
fn create_style(&self, props: dioxus::document::StyleProps) {
let attributes = props.attributes();
self.create_head_element("style", &attributes, props.style_contents().ok());
}
fn create_link(&self, props: dioxus::document::LinkProps) {
let attributes = props.attributes();
self.create_head_element("link", &attributes, None);
}
fn create_head_component(&self) -> bool {
true
}
}
struct BevyNetCallback {
sender: Sender<DioxusMessage>,
}
use blitz_dom::net::Resource as BlitzResource;
use blitz_traits::net::NetHandler;
impl NetCallback<BlitzResource> for BevyNetCallback {
fn call(&self, _doc_id: usize, result: core::result::Result<BlitzResource, Option<String>>) {
if let Ok(res) = result {
self.sender.send(DioxusMessage::ResourceLoad(res)).unwrap();
}
}
}
pub struct BevyNetProvider {
callback: Arc<dyn NetCallback<BlitzResource> + 'static>,
}
impl BevyNetProvider {
fn shared(sender: Sender<DioxusMessage>) -> Arc<dyn NetProvider<BlitzResource>> {
Arc::new(Self::new(sender)) as _
}
fn new(sender: Sender<DioxusMessage>) -> Self {
Self {
callback: Arc::new(BevyNetCallback { sender }) as _,
}
}
}
impl NetProvider<BlitzResource> for BevyNetProvider {
fn fetch(
&self,
doc_id: usize,
request: blitz_traits::net::Request,
handler: Box<dyn NetHandler<BlitzResource>>,
) {
match request.url.scheme() {
// Load Dioxus assets
"dioxus" => match dioxus_asset_resolver::native::serve_asset(request.url.path()) {
Ok(res) => handler.bytes(doc_id, res.into_body().into(), self.callback.clone()),
Err(_) => {
self.callback.call(
doc_id,
Err(Some(String::from("Error loading Dioxus asset"))),
);
}
},
// Decode data URIs
"data" => {
let Ok(data_url) = DataUrl::process(request.url.as_str()) else {
self.callback
.call(doc_id, Err(Some(String::from("Failed to parse data uri"))));
return;
};
let Ok(decoded) = data_url.decode_to_vec() else {
self.callback
.call(doc_id, Err(Some(String::from("Failed to decode data uri"))));
return;
};
let bytes = Bytes::from(decoded.0);
handler.bytes(doc_id, bytes, Arc::clone(&self.callback));
}
// TODO: support http requests
_ => {
self.callback
.call(doc_id, Err(Some(String::from("UnsupportedScheme"))));
}
}
}
}
fn bevy_key_to_blitz_key(key: &BevyKey) -> Key {
match key {
BevyKey::Character(c) => Key::Character(c.to_string()),
BevyKey::Unidentified(_) => Key::Unidentified,
BevyKey::Dead(_) => Key::Dead,
BevyKey::Alt => Key::Alt,
BevyKey::AltGraph => Key::AltGraph,
BevyKey::CapsLock => Key::CapsLock,
BevyKey::Control => Key::Control,
BevyKey::Fn => Key::Fn,
BevyKey::FnLock => Key::FnLock,
BevyKey::NumLock => Key::Meta,
BevyKey::ScrollLock => Key::NumLock,
BevyKey::Shift => Key::ScrollLock,
BevyKey::Symbol => Key::Shift,
BevyKey::SymbolLock => Key::Symbol,
BevyKey::Meta => Key::SymbolLock,
BevyKey::Hyper => Key::Hyper,
BevyKey::Super => Key::Super,
BevyKey::Enter => Key::Enter,
BevyKey::Tab => Key::Tab,
BevyKey::Space => Key::Character(" ".to_string()),
BevyKey::ArrowDown => Key::ArrowDown,
BevyKey::ArrowLeft => Key::ArrowLeft,
BevyKey::ArrowRight => Key::ArrowRight,
BevyKey::ArrowUp => Key::ArrowUp,
BevyKey::End => Key::End,
BevyKey::Home => Key::Home,
BevyKey::PageDown => Key::PageDown,
BevyKey::PageUp => Key::PageUp,
BevyKey::Backspace => Key::Backspace,
BevyKey::Clear => Key::Clear,
BevyKey::Copy => Key::Copy,
BevyKey::CrSel => Key::CrSel,
BevyKey::Cut => Key::Cut,
BevyKey::Delete => Key::Delete,
BevyKey::EraseEof => Key::EraseEof,
BevyKey::ExSel => Key::ExSel,
BevyKey::Insert => Key::Insert,
BevyKey::Paste => Key::Paste,
BevyKey::Redo => Key::Redo,
BevyKey::Undo => Key::Undo,
BevyKey::Accept => Key::Accept,
BevyKey::Again => Key::Again,
BevyKey::Attn => Key::Attn,
BevyKey::Cancel => Key::Cancel,
BevyKey::ContextMenu => Key::ContextMenu,
BevyKey::Escape => Key::Escape,
BevyKey::Execute => Key::Execute,
BevyKey::Find => Key::Find,
BevyKey::Help => Key::Help,
BevyKey::Pause => Key::Pause,
BevyKey::Play => Key::Play,
BevyKey::Props => Key::Props,
BevyKey::Select => Key::Select,
BevyKey::ZoomIn => Key::ZoomIn,
BevyKey::ZoomOut => Key::ZoomOut,
BevyKey::BrightnessDown => Key::BrightnessDown,
BevyKey::BrightnessUp => Key::BrightnessUp,
BevyKey::Eject => Key::Eject,
BevyKey::LogOff => Key::LogOff,
BevyKey::Power => Key::Power,
BevyKey::PowerOff => Key::PowerOff,
BevyKey::PrintScreen => Key::PrintScreen,
BevyKey::Hibernate => Key::Hibernate,
BevyKey::Standby => Key::Standby,
BevyKey::WakeUp => Key::WakeUp,
BevyKey::AllCandidates => Key::AllCandidates,
BevyKey::Alphanumeric => Key::Alphanumeric,
BevyKey::CodeInput => Key::CodeInput,
BevyKey::Compose => Key::Compose,
BevyKey::Convert => Key::Convert,
BevyKey::FinalMode => Key::FinalMode,
BevyKey::GroupFirst => Key::GroupFirst,
BevyKey::GroupLast => Key::GroupLast,
BevyKey::GroupNext => Key::GroupNext,
BevyKey::GroupPrevious => Key::GroupPrevious,
BevyKey::ModeChange => Key::ModeChange,
BevyKey::NextCandidate => Key::NextCandidate,
BevyKey::NonConvert => Key::NonConvert,
BevyKey::PreviousCandidate => Key::PreviousCandidate,
BevyKey::Process => Key::Process,
BevyKey::SingleCandidate => Key::SingleCandidate,
BevyKey::HangulMode => Key::HangulMode,
BevyKey::HanjaMode => Key::HanjaMode,
BevyKey::JunjaMode => Key::JunjaMode,
BevyKey::Eisu => Key::Eisu,
BevyKey::Hankaku => Key::Hankaku,
BevyKey::Hiragana => Key::Hiragana,
BevyKey::HiraganaKatakana => Key::HiraganaKatakana,
BevyKey::KanaMode => Key::KanaMode,
BevyKey::KanjiMode => Key::KanjiMode,
BevyKey::Katakana => Key::Katakana,
BevyKey::Romaji => Key::Romaji,
BevyKey::Zenkaku => Key::Zenkaku,
BevyKey::ZenkakuHankaku => Key::ZenkakuHankaku,
BevyKey::Soft1 => Key::Soft1,
BevyKey::Soft2 => Key::Soft2,
BevyKey::Soft3 => Key::Soft3,
BevyKey::Soft4 => Key::Soft4,
BevyKey::ChannelDown => Key::ChannelDown,
BevyKey::ChannelUp => Key::ChannelUp,
BevyKey::Close => Key::Close,
BevyKey::MailForward => Key::MailForward,
BevyKey::MailReply => Key::MailReply,
BevyKey::MailSend => Key::MailSend,
BevyKey::MediaClose => Key::MediaClose,
BevyKey::MediaFastForward => Key::MediaFastForward,
BevyKey::MediaPause => Key::MediaPause,
BevyKey::MediaPlay => Key::MediaPlay,
BevyKey::MediaPlayPause => Key::MediaPlayPause,
BevyKey::MediaRecord => Key::MediaRecord,
BevyKey::MediaRewind => Key::MediaRewind,
BevyKey::MediaStop => Key::MediaStop,
BevyKey::MediaTrackNext => Key::MediaTrackNext,
BevyKey::MediaTrackPrevious => Key::MediaTrackPrevious,
BevyKey::New => Key::New,
BevyKey::Open => Key::Open,
BevyKey::Print => Key::Print,
BevyKey::Save => Key::Save,
BevyKey::SpellCheck => Key::SpellCheck,
BevyKey::Key11 => Key::Key11,
BevyKey::Key12 => Key::Key12,
BevyKey::AudioBalanceLeft => Key::AudioBalanceLeft,
BevyKey::AudioBalanceRight => Key::AudioBalanceRight,
BevyKey::AudioBassBoostDown => Key::AudioBassBoostDown,
BevyKey::AudioBassBoostToggle => Key::AudioBassBoostToggle,
BevyKey::AudioBassBoostUp => Key::AudioBassBoostUp,
BevyKey::AudioFaderFront => Key::AudioFaderFront,
BevyKey::AudioFaderRear => Key::AudioFaderRear,
BevyKey::AudioSurroundModeNext => Key::AudioSurroundModeNext,
BevyKey::AudioTrebleDown => Key::AudioTrebleDown,
BevyKey::AudioTrebleUp => Key::AudioTrebleUp,
BevyKey::AudioVolumeDown => Key::AudioVolumeDown,
BevyKey::AudioVolumeUp => Key::AudioVolumeUp,
BevyKey::AudioVolumeMute => Key::AudioVolumeMute,
BevyKey::MicrophoneToggle => Key::MicrophoneToggle,
BevyKey::MicrophoneVolumeDown => Key::MicrophoneVolumeDown,
BevyKey::MicrophoneVolumeUp => Key::MicrophoneVolumeUp,
BevyKey::MicrophoneVolumeMute => Key::MicrophoneVolumeMute,
BevyKey::SpeechCorrectionList => Key::SpeechCorrectionList,
BevyKey::SpeechInputToggle => Key::SpeechInputToggle,
BevyKey::LaunchApplication1 => Key::LaunchApplication1,
BevyKey::LaunchApplication2 => Key::LaunchApplication2,
BevyKey::LaunchCalendar => Key::LaunchCalendar,
BevyKey::LaunchContacts => Key::LaunchContacts,
BevyKey::LaunchMail => Key::LaunchMail,
BevyKey::LaunchMediaPlayer => Key::LaunchMediaPlayer,
BevyKey::LaunchMusicPlayer => Key::LaunchMusicPlayer,
BevyKey::LaunchPhone => Key::LaunchPhone,
BevyKey::LaunchScreenSaver => Key::LaunchScreenSaver,
BevyKey::LaunchSpreadsheet => Key::LaunchSpreadsheet,
BevyKey::LaunchWebBrowser => Key::LaunchWebBrowser,
BevyKey::LaunchWebCam => Key::LaunchWebCam,
BevyKey::LaunchWordProcessor => Key::LaunchWordProcessor,
BevyKey::BrowserBack => Key::BrowserBack,
BevyKey::BrowserFavorites => Key::BrowserFavorites,
BevyKey::BrowserForward => Key::BrowserForward,
BevyKey::BrowserHome => Key::BrowserHome,
BevyKey::BrowserRefresh => Key::BrowserRefresh,
BevyKey::BrowserSearch => Key::BrowserSearch,
BevyKey::BrowserStop => Key::BrowserStop,
BevyKey::AppSwitch => Key::AppSwitch,
BevyKey::Call => Key::Call,
BevyKey::Camera => Key::Camera,
BevyKey::CameraFocus => Key::CameraFocus,
BevyKey::EndCall => Key::EndCall,
BevyKey::GoBack => Key::GoBack,
BevyKey::GoHome => Key::GoHome,
BevyKey::HeadsetHook => Key::HeadsetHook,
BevyKey::LastNumberRedial => Key::LastNumberRedial,
BevyKey::Notification => Key::Notification,
BevyKey::MannerMode => Key::MannerMode,
BevyKey::VoiceDial => Key::VoiceDial,
BevyKey::TV => Key::TV,
BevyKey::TV3DMode => Key::TV3DMode,
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/native-headless-in-bevy/src/ui.rs | examples/10-integrations/native-headless-in-bevy/src/ui.rs | use async_std::task::sleep;
use crossbeam_channel::{Receiver, Sender};
use dioxus::prelude::*;
use paste::paste;
macro_rules! define_ui_state {
(
$($field:ident : $type:ty = $default:expr),* $(,)?
) => { paste! {
#[allow(dead_code)]
#[derive(Clone, Copy)]
pub struct UiState {
$($field: Signal<$type>,)*
}
#[allow(dead_code)]
impl UiState {
fn default() -> Self {
Self {
$($field: Signal::new($default),)*
}
}
$(pub const [<DEFAULT_ $field:upper>]: $type = $default;)*
}
#[allow(dead_code)]
pub enum UIMessage {
$([<$field:camel>]($type),)*
}
}};
}
define_ui_state! {
cube_color: [f32; 4] = [0.0, 0.0, 1.0, 1.0],
cube_translation_speed: f32 = 2.0,
cube_rotation_speed: f32 = 1.0,
fps: f32 = 0.0,
}
#[derive(Clone)]
pub struct UIProps {
pub ui_sender: Sender<UIMessage>,
pub app_receiver: Receiver<UIMessage>,
}
pub fn ui(props: UIProps) -> Element {
let mut state = use_context_provider(UiState::default);
use_effect({
let ui_sender = props.ui_sender.clone();
move || {
println!("Color changed to {:?}", state.cube_color);
ui_sender
.send(UIMessage::CubeColor((state.cube_color)()))
.unwrap();
}
});
use_effect({
let ui_sender = props.ui_sender.clone();
move || {
println!("Rotation speed changed to {:?}", state.cube_rotation_speed);
ui_sender
.send(UIMessage::CubeRotationSpeed((state.cube_rotation_speed)()))
.unwrap();
}
});
use_effect({
let ui_sender = props.ui_sender.clone();
move || {
println!(
"Translation speed changed to {:?}",
state.cube_translation_speed
);
ui_sender
.send(UIMessage::CubeTranslationSpeed((state
.cube_translation_speed)(
)))
.unwrap();
}
});
use_future(move || {
let app_receiver = props.app_receiver.clone();
async move {
loop {
// Update UI every 1s in this demo.
sleep(std::time::Duration::from_millis(1000)).await;
let mut fps = Option::<f32>::None;
while let Ok(message) = app_receiver.try_recv() {
if let UIMessage::Fps(v) = message {
fps = Some(v)
}
}
if let Some(fps) = fps {
state.fps.set(fps);
}
}
}
});
let color = *state.cube_color.read();
let [r, g, b, a] = color.map(|c| (c * 255.0) as u8);
println!("rgba({r}, {g}, {b}, {a})");
rsx! {
document::Stylesheet { href: asset!("/src/ui.css") }
div {
id: "panel",
class: "catch-events",
div {
id: "title",
h1 { "Dioxus In Bevy Example" }
}
div {
id: "buttons",
button {
id: "button-red",
class: "color-button",
onclick: move |_| state.cube_color.set([1.0, 0.0, 0.0, 1.0]),
}
button {
id: "button-green",
class: "color-button",
onclick: move |_| state.cube_color.set([0.0, 1.0, 0.0, 1.0]),
}
button {
id: "button-blue",
class: "color-button",
onclick: move |_| state.cube_color.set([0.0, 0.0, 1.0, 1.0]),
}
}
div {
id: "translation-speed-control",
label { "Translation Speed:" }
input {
r#type: "number",
min: "0.0",
max: "10.0",
step: "0.1",
value: "{state.cube_translation_speed}",
oninput: move |event| {
if let Ok(speed) = event.value().parse::<f32>() {
state.cube_translation_speed.set(speed);
}
}
}
}
div {
id: "rotation-speed-control",
label { "Rotation Speed:" }
input {
r#type: "number",
min: "0.0",
max: "10.0",
step: "0.1",
value: "{state.cube_rotation_speed}",
oninput: move |event| {
if let Ok(speed) = event.value().parse::<f32>() {
state.cube_rotation_speed.set(speed);
}
}
}
}
div {
flex: "0 0 150px",
display: "grid",
align_items: "center",
justify_items: "center",
div {
class: "spin-box",
background: "rgba({r}, {g}, {b}, {a}",
}
}
div {
id: "footer",
p { "Bevy framerate: {state.fps}" }
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/native-headless-in-bevy/src/main.rs | examples/10-integrations/native-headless-in-bevy/src/main.rs | mod bevy_scene_plugin;
mod dioxus_in_bevy_plugin;
mod ui;
use crate::bevy_scene_plugin::BevyScenePlugin;
use crate::dioxus_in_bevy_plugin::DioxusInBevyPlugin;
use crate::ui::{ui, UIProps};
use bevy::prelude::*;
fn main() {
#[cfg(feature = "tracing")]
tracing_subscriber::fmt::init();
let (ui_sender, ui_receiver) = crossbeam_channel::unbounded();
let (app_sender, app_receiver) = crossbeam_channel::unbounded();
let props = UIProps {
ui_sender,
app_receiver,
};
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(DioxusInBevyPlugin::<UIProps> { ui, props })
.add_plugins(BevyScenePlugin {
app_sender,
ui_receiver,
})
.run();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/pwa/src/main.rs | examples/10-integrations/pwa/src/main.rs | use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! (
div { style: "text-align: center;",
h1 { "🌗 Dioxus 🚀" }
h3 { "Frontend that scales." }
p { "Build web, desktop, and mobile apps with Dioxus" }
}
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/wgpu-texture/src/main.rs | examples/10-integrations/wgpu-texture/src/main.rs | use color::{palette::css::WHITE, parse_color};
use color::{OpaqueColor, Srgb};
use demo_renderer::{DemoMessage, DemoPaintSource};
use dioxus::prelude::*;
use dioxus_native::use_wgpu;
use std::any::Any;
use wgpu::{Features, Limits};
use winit::dpi::LogicalSize;
use winit::window::WindowAttributes;
mod demo_renderer;
// CSS Styles
static STYLES: Asset = asset!("/src/styles.css");
// WGPU settings required by this example
const FEATURES: Features = Features::PUSH_CONSTANTS;
fn limits() -> Limits {
Limits {
max_push_constant_size: 16,
..Limits::default()
}
}
fn window_attributes() -> WindowAttributes {
// You can also use a `<title>` element to set the window title
// but this demonstrates the use of `WindowAttributes`
WindowAttributes::default()
.with_title("WGPU Example")
.with_inner_size(LogicalSize::new(800, 600))
}
type Color = OpaqueColor<Srgb>;
fn main() {
#[cfg(feature = "tracing")]
tracing_subscriber::fmt::init();
let config: Vec<Box<dyn Any>> = vec![
Box::new(FEATURES),
Box::new(limits()),
Box::new(window_attributes()),
];
dioxus_native::launch_cfg(app, Vec::new(), config);
}
fn app() -> Element {
let mut show_cube = use_signal(|| true);
let color_str = use_signal(|| String::from("red"));
let color = use_memo(move || {
parse_color(&color_str())
.map(|c| c.to_alpha_color())
.unwrap_or(WHITE)
.split()
.0
});
use_effect(move || println!("{:?}", color().components));
rsx!(
Stylesheet { href: STYLES }
div { id:"overlay",
h2 { "Control Panel" },
button {
onclick: move |_| show_cube.toggle(),
if show_cube() {
"Hide cube"
} else {
"Show cube"
}
}
br {}
ColorControl { label: "Color:", color_str },
p { "This overlay demonstrates that the custom WGPU content can be rendered beneath layers of HTML content" }
}
div { id:"underlay",
h2 { "Underlay" },
p { "This underlay demonstrates that the custom WGPU content can be rendered above layers and blended with the content underneath" }
}
header {
h1 { "Blitz WGPU Demo" }
}
if show_cube() {
SpinningCube { color }
}
)
}
#[component]
fn ColorControl(label: &'static str, color_str: WriteSignal<String>) -> Element {
rsx!(div {
class: "color-control",
{ label },
input {
value: color_str(),
oninput: move |evt| {
*color_str.write() = evt.value()
}
}
})
}
#[component]
fn SpinningCube(color: Memo<Color>) -> Element {
// Create custom paint source and register it with the renderer
let paint_source = DemoPaintSource::new();
let sender = paint_source.sender();
let paint_source_id = use_wgpu(move || paint_source);
use_effect(move || {
sender.send(DemoMessage::SetColor(color())).unwrap();
});
rsx!(
div { id:"canvas-container",
canvas {
id: "demo-canvas",
"src": paint_source_id
}
}
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/wgpu-texture/src/demo_renderer.rs | examples/10-integrations/wgpu-texture/src/demo_renderer.rs | // Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: MIT
use crate::Color;
use dioxus_native::{CustomPaintCtx, CustomPaintSource, DeviceHandle, TextureHandle};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::time::Instant;
use wgpu::{
CommandEncoderDescriptor, Device, Extent3d, FragmentState, LoadOp, MultisampleState,
Operations, PipelineLayoutDescriptor, PrimitiveState, PushConstantRange, Queue,
RenderPassColorAttachment, RenderPassDescriptor, RenderPipeline, RenderPipelineDescriptor,
ShaderModuleDescriptor, ShaderSource, ShaderStages, StoreOp, Texture, TextureDescriptor,
TextureDimension, TextureFormat, TextureUsages, TextureViewDescriptor, VertexState,
};
pub struct DemoPaintSource {
state: DemoRendererState,
start_time: std::time::Instant,
tx: Sender<DemoMessage>,
rx: Receiver<DemoMessage>,
color: Color,
}
impl CustomPaintSource for DemoPaintSource {
fn resume(&mut self, device_handle: &DeviceHandle) {
// Extract device and queue from device_handle
let device = &device_handle.device;
let queue = &device_handle.queue;
let active_state = ActiveDemoRenderer::new(device, queue);
self.state = DemoRendererState::Active(Box::new(active_state));
}
fn suspend(&mut self) {
self.state = DemoRendererState::Suspended;
}
fn render(
&mut self,
ctx: CustomPaintCtx<'_>,
width: u32,
height: u32,
_scale: f64,
) -> Option<TextureHandle> {
self.process_messages();
self.render(ctx, width, height)
}
}
pub enum DemoMessage {
// Color in RGB format
SetColor(Color),
}
enum DemoRendererState {
Active(Box<ActiveDemoRenderer>),
Suspended,
}
#[derive(Clone)]
struct TextureAndHandle {
texture: Texture,
handle: TextureHandle,
}
struct ActiveDemoRenderer {
device: Device,
queue: Queue,
pipeline: RenderPipeline,
displayed_texture: Option<TextureAndHandle>,
next_texture: Option<TextureAndHandle>,
}
impl DemoPaintSource {
pub fn new() -> Self {
let (tx, rx) = channel();
Self::with_channel(tx, rx)
}
pub fn with_channel(tx: Sender<DemoMessage>, rx: Receiver<DemoMessage>) -> Self {
Self {
state: DemoRendererState::Suspended,
start_time: std::time::Instant::now(),
tx,
rx,
color: Color::WHITE,
}
}
pub fn sender(&self) -> Sender<DemoMessage> {
self.tx.clone()
}
fn process_messages(&mut self) {
loop {
match self.rx.try_recv() {
Err(_) => return,
Ok(msg) => match msg {
DemoMessage::SetColor(color) => self.color = color,
},
}
}
}
fn render(
&mut self,
ctx: CustomPaintCtx<'_>,
width: u32,
height: u32,
) -> Option<TextureHandle> {
if width == 0 || height == 0 {
return None;
}
let DemoRendererState::Active(state) = &mut self.state else {
return None;
};
state.render(ctx, self.color.components, width, height, &self.start_time)
}
}
impl ActiveDemoRenderer {
pub(crate) fn new(device: &Device, queue: &Queue) -> Self {
let shader = device.create_shader_module(ShaderModuleDescriptor {
label: None,
source: ShaderSource::Wgsl(std::borrow::Cow::Borrowed(include_str!("shader.wgsl"))),
});
let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
push_constant_ranges: &[PushConstantRange {
stages: ShaderStages::FRAGMENT,
range: 0..16, // full size in bytes, aligned
}],
});
let pipeline = device.create_render_pipeline(&RenderPipelineDescriptor {
label: None,
layout: Some(&pipeline_layout),
vertex: VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(TextureFormat::Rgba8Unorm.into())],
}),
primitive: PrimitiveState::default(),
depth_stencil: None,
multisample: MultisampleState::default(),
multiview: None,
cache: None,
});
Self {
device: device.clone(),
queue: queue.clone(),
pipeline,
displayed_texture: None,
next_texture: None,
}
}
pub(crate) fn render(
&mut self,
mut ctx: CustomPaintCtx<'_>,
light: [f32; 3],
width: u32,
height: u32,
start_time: &Instant,
) -> Option<TextureHandle> {
// If "next texture" size doesn't match specified size then unregister and drop texture
if let Some(next) = &self.next_texture {
if next.texture.width() != width || next.texture.height() != height {
ctx.unregister_texture(self.next_texture.take().unwrap().handle);
}
}
// If there is no "next texture" then create one and register it.
let texture_and_handle = match &self.next_texture {
Some(next) => next,
None => {
let texture = create_texture(&self.device, width, height);
let handle = ctx.register_texture(texture.clone());
self.next_texture = Some(TextureAndHandle { texture, handle });
self.next_texture.as_ref().unwrap()
}
};
let next_texture = &texture_and_handle.texture;
let next_texture_handle = texture_and_handle.handle.clone();
let elapsed: f32 = start_time.elapsed().as_millis() as f32 / 500.;
let [light_red, light_green, light_blue] = light;
let push_constants = PushConstants {
light_color_and_time: [light_red, light_green, light_blue, elapsed],
};
let mut encoder = self
.device
.create_command_encoder(&CommandEncoderDescriptor { label: None });
{
let mut rpass = encoder.begin_render_pass(&RenderPassDescriptor {
label: None,
color_attachments: &[Some(RenderPassColorAttachment {
view: &next_texture.create_view(&TextureViewDescriptor::default()),
resolve_target: None,
ops: Operations {
load: LoadOp::Clear(wgpu::Color::GREEN),
store: StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
});
rpass.set_pipeline(&self.pipeline);
rpass.set_push_constants(
ShaderStages::FRAGMENT, // Stage (your constants are for fragment shader)
0, // Offset in bytes (start at 0)
bytemuck::bytes_of(&push_constants),
);
rpass.draw(0..3, 0..1);
}
self.queue.submit(Some(encoder.finish()));
std::mem::swap(&mut self.next_texture, &mut self.displayed_texture);
Some(next_texture_handle)
}
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct PushConstants {
light_color_and_time: [f32; 4],
}
fn create_texture(device: &Device, width: u32, height: u32) -> Texture {
device.create_texture(&TextureDescriptor {
label: None,
size: Extent3d {
width,
height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8Unorm,
usage: TextureUsages::RENDER_ATTACHMENT
| TextureUsages::TEXTURE_BINDING
| TextureUsages::COPY_SRC,
view_formats: &[],
})
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/native-headless/src/main.rs | examples/10-integrations/native-headless/src/main.rs | //! A "sketch" of how to integrate a Dioxus Native app to into a wider application
//! by rendering the UI to a texture and driving it with your own event loop
//!
//! (this example is not really intended to be run as-is, and requires you to fill
//! in the missing pieces)
use anyrender_vello::VelloScenePainter;
use blitz_dom::{Document as _, DocumentConfig};
use blitz_paint::paint_scene;
use blitz_traits::{
events::{BlitzMouseButtonEvent, MouseEventButton, MouseEventButtons, UiEvent},
shell::{ColorScheme, Viewport},
};
use dioxus::prelude::*;
use dioxus_native_dom::DioxusDocument;
use pollster::FutureExt as _;
use std::sync::Arc;
use std::task::Context;
use vello::{
peniko::color::AlphaColor, RenderParams, Renderer as VelloRenderer, RendererOptions, Scene,
};
use wgpu::TextureFormat;
use wgpu_context::WGPUContext;
// Constant width, height, scale factor and color schemefor example purposes
const SCALE_FACTOR: f32 = 1.0;
const WIDTH: u32 = 800;
const HEIGHT: u32 = 600;
const COLOR_SCHEME: ColorScheme = ColorScheme::Light;
// Example Dioxus app.
fn app() -> Element {
rsx! {
div { "Hello, world!" }
}
}
fn main() {
#[cfg(feature = "tracing")]
tracing_subscriber::fmt::init();
// =============
// INITIAL SETUP
// =============
let waker = create_waker(Box::new(|| {
// This should wake up and "poll" your event loop
}));
// Create the dioxus virtual dom and the dioxus-native document
// It is important to set the width, height, and scale factor on the document as these are used for layout.
let vdom = VirtualDom::new(app);
let mut dioxus_doc = DioxusDocument::new(
vdom,
DocumentConfig {
viewport: Some(Viewport::new(WIDTH, HEIGHT, SCALE_FACTOR, COLOR_SCHEME)),
..Default::default()
},
);
// Setup a WGPU Device and Queue
//
// There is nothing special about WGPUContext. It is just used to
// reduce the amount of boilerplate associated with setting up WGPU
let mut wgpu_context = WGPUContext::new();
let device_id = wgpu_context
.find_or_create_device(None)
.block_on()
.expect("Failed to create WGPU device");
let device_handle = &wgpu_context.device_pool[device_id];
let device = device_handle.device.clone();
let queue = device_handle.queue.clone();
// Create Vello renderer
// Note: creating a VelloRenderer is expensive, so it should be done once per Device.
let mut vello_renderer = VelloRenderer::new(&device, RendererOptions::default()).unwrap();
// =============
// CREATE TEXTURE (RECREATE ON RESIZE)
// =============
// Create texture and texture view
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: WIDTH,
height: HEIGHT,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING,
format: TextureFormat::Rgba8Unorm,
view_formats: &[],
});
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
// =============
// EACH FRAME
// =============
// Poll the vdom
dioxus_doc.poll(Some(Context::from_waker(&waker)));
// Create a `vello::Scene` to paint into
let mut scene = Scene::new();
// Paint the document using `blitz_paint::paint_scene`
//
// Note: the `paint_scene` will work with any implementation of `anyrender::PaintScene`
// so you could also write your own implementation if you want more control over rendering
// (i.e. to render a custom renderer instead of Vello)
paint_scene(
&mut VelloScenePainter::new(&mut scene),
&dioxus_doc,
SCALE_FACTOR as f64,
WIDTH,
HEIGHT,
);
// Render the `vello::Scene` to the Texture using the `VelloRenderer`
vello_renderer
.render_to_texture(
&device,
&queue,
&scene,
&texture_view,
&RenderParams {
base_color: AlphaColor::TRANSPARENT,
width: WIDTH,
height: HEIGHT,
antialiasing_method: vello::AaConfig::Msaa16,
},
)
.expect("failed to render to texture");
// `texture` will now contain the rendered Scene
// =============
// EVENT HANDLING
// =============
let event = UiEvent::MouseDown(BlitzMouseButtonEvent {
x: 30.0,
y: 40.0,
button: MouseEventButton::Main,
buttons: MouseEventButtons::Primary, // keep track of all pressed buttons
mods: Modifiers::empty(), // ctrl, alt, shift, etc
});
dioxus_doc.handle_ui_event(event);
// Trigger a poll via your event loop (or wait for next frame)
}
/// Create a waker that will call an arbitrary callback
pub fn create_waker(callback: Box<dyn Fn() + 'static + Send + Sync>) -> std::task::Waker {
struct DomHandle {
callback: Box<dyn Fn() + 'static + Send + Sync>,
}
impl futures_util::task::ArcWake for DomHandle {
fn wake_by_ref(arc_self: &Arc<Self>) {
(arc_self.callback)()
}
}
futures_util::task::waker(Arc::new(DomHandle { callback }))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/10-integrations/tailwind/src/main.rs | examples/10-integrations/tailwind/src/main.rs | use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let grey_background = true;
rsx! {
Stylesheet { href: asset!("/assets/tailwind.css") }
div {
header {
class: "text-gray-400 body-font",
// you can use optional attributes to optionally apply a tailwind class
class: if grey_background { "bg-gray-900" },
div { class: "container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center",
a { class: "flex title-font font-medium items-center text-white mb-4 md:mb-0",
StacksIcon {}
span { class: "ml-3 text-xl", "Hello Dioxus!" }
}
nav { class: "md:ml-auto flex flex-wrap items-center text-base justify-center",
a { class: "mr-5 hover:text-white", "First Link" }
a { class: "mr-5 hover:text-white", "Second Link" }
a { class: "mr-5 hover:text-white", "Third Link" }
a { class: "mr-5 hover:text-white", "Fourth Link" }
}
button { class: "inline-flex items-center bg-gray-800 border-0 py-1 px-3 focus:outline-hidden hover:bg-gray-700 rounded-sm text-base mt-4 md:mt-0",
"Button"
RightArrowIcon {}
}
}
}
section { class: "text-gray-400 bg-gray-900 body-font",
div { class: "container mx-auto flex px-5 py-24 md:flex-row flex-col items-center",
div { class: "lg:grow md:w-1/2 lg:pr-24 md:pr-16 flex flex-col md:items-start md:text-left mb-16 md:mb-0 items-center text-center",
h1 { class: "title-font sm:text-4xl text-3xl mb-4 font-medium text-white",
br { class: "hidden lg:inline-block" }
"Dioxus Sneak Peek"
}
p { class: "mb-8 leading-relaxed",
"Dioxus is a new UI framework that makes it easy and simple to write cross-platform apps using web
technologies! It is functional, fast, and portable. Dioxus can run on the web, on the desktop, and
on mobile and embedded platforms."
}
div { class: "flex justify-center",
button { class: "inline-flex text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-hidden hover:bg-indigo-600 rounded-sm text-lg",
"Learn more"
}
button { class: "ml-4 inline-flex text-gray-400 bg-gray-800 border-0 py-2 px-6 focus:outline-hidden hover:bg-gray-700 hover:text-white rounded-sm text-lg",
"Build an app"
}
}
}
div { class: "lg:max-w-lg lg:w-full md:w-1/2 w-5/6",
img {
class: "object-cover object-center rounded-sm",
src: "https://i.imgur.com/oK6BLtw.png",
referrerpolicy: "no-referrer",
alt: "hero",
}
}
}
}
}
}
}
#[component]
pub fn StacksIcon() -> Element {
rsx! {
svg {
fill: "none",
stroke: "currentColor",
stroke_linecap: "round",
stroke_linejoin: "round",
stroke_width: "2",
class: "w-10 h-10 text-white p-2 bg-indigo-500 rounded-full",
view_box: "0 0 24 24",
path { d: "M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" }
}
}
}
#[component]
pub fn RightArrowIcon() -> Element {
rsx! {
svg {
fill: "none",
stroke: "currentColor",
stroke_linecap: "round",
stroke_linejoin: "round",
stroke_width: "2",
class: "w-4 h-4 ml-1",
view_box: "0 0 24 24",
path { d: "M5 12h14M12 5l7 7-7 7" }
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/header_map.rs | examples/07-fullstack/header_map.rs | //! This example shows how you can extract a HeaderMap from requests to read custom headers.
//!
//! The extra arguments in the `#[get(...)]` macro are passed to the underlying axum handler,
//! and only visible on the server. This lets you run normal axum extractors like `HeaderMap`,
//! `TypedHeader`, `Query`, etc.
//!
//! Note that headers returned by the server are not always visible to the client due to CORS.
//! Headers like `Set-Cookie` are hidden by default, and need to be explicitly allowed
//! by the server using the `Access-Control-Expose-Headers` header (which dioxus-fullstack does not
//! currently expose directly).
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut headers = use_action(get_headers);
rsx! {
h1 { "Header Map Example" }
button { onclick: move |_| headers.call(), "Get Headers" }
if let Some(Ok(headers)) = headers.value() {
p { "Response from server:" }
pre { "{headers}" }
} else {
p { "No headers yet" }
}
}
}
#[get("/api/example", headers: dioxus::fullstack::HeaderMap)]
async fn get_headers() -> Result<String> {
Ok(format!("{:#?}", headers))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/multipart_form.rs | examples/07-fullstack/multipart_form.rs | //! This example showcases how to handle multipart form data uploads in Dioxus.
//!
//! Dioxus provides the `MultipartFormData` type to allow converting from the websys `FormData`
//! type directly into a streaming multipart form data handler.
use dioxus::{fullstack::MultipartFormData, prelude::*};
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// The `MultipartFormData` type can be used to handle multipart form data uploads.
// We can convert into it by using `.into()` on the `FormEvent`'s data, or by crafting
// a `MultipartFormData` instance manually.
let mut upload_as_multipart = use_action(move |event: FormEvent| upload(event.into()));
rsx! {
Stylesheet { href: asset!("/examples/assets/file_upload.css") }
img { src: asset!("/examples/assets/logo.png"), width: "200px" }
div {
h3 { "Upload as Multipart" }
p { "Use the built-in multipart form handling" }
form {
display: "flex",
flex_direction: "column",
gap: "8px",
onsubmit: move |evt| async move {
evt.prevent_default();
upload_as_multipart.call(evt).await;
},
label { r#for: "headshot", "Photos" }
input { r#type: "file", name: "headshot", multiple: true, accept: ".png,.jpg,.jpeg" }
label { r#for: "resume", "Resume" }
input { r#type: "file", name: "resume", multiple: false, accept: ".pdf" }
label { r#for: "name", "Name" }
input { r#type: "text", name: "name", placeholder: "Name" }
label { r#for: "age", "Age" }
input { r#type: "number", name: "age", placeholder: "Age" }
input { r#type: "submit", name: "submit", value: "Submit your resume" }
}
}
}
}
/// Upload a form as multipart form data.
///
/// MultipartFormData is typed over the form data structure, allowing us to extract
/// both files and other form fields in a type-safe manner.
///
/// On the server, we have access to axum's `Multipart` extractor
#[post("/api/upload-multipart")]
async fn upload(mut form: MultipartFormData) -> Result<()> {
while let Ok(Some(field)) = form.next_field().await {
let name = field.name().unwrap_or("<none>").to_string();
let file_name = field.file_name().unwrap_or("<none>").to_string();
let content_type = field.content_type().unwrap_or("<none>").to_string();
let size = field.bytes().await.unwrap().len();
info!(
"Field name: {:?}, filename: {:?}, content_type: {:?}, size: {:?}",
name, file_name, content_type, size
);
}
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/login_form.rs | examples/07-fullstack/login_form.rs | //! This example demonstrates how to use types like `Form`, `SetHeader`, and `TypedHeader`
//! to create a simple login form that sets a cookie in the browser and uses it for authentication
//! on a protected endpoint.
//!
//! For more information on handling forms in general, see the multipart_form example.
//!
//! The intent with this example is to show how to use the building blocks like `Form` and `SetHeader`
//! to roll a simple authentication system.
use dioxus::fullstack::{Form, SetCookie, SetHeader};
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
#[cfg(feature = "server")]
use {
dioxus::fullstack::{Cookie, TypedHeader},
std::sync::LazyLock,
uuid::Uuid,
};
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut fetch_login = use_action(login);
let mut fetch_sensitive = use_action(sensitive);
rsx! {
h1 { "Login Form Demo" }
button {
onclick: move |_| async move {
fetch_sensitive.call();
},
"Get Sensitive Data",
}
pre { "Response from locked API: {fetch_sensitive.value():?}"}
form {
onsubmit: move |evt: FormEvent| async move {
// Prevent the browser from navigating away.
evt.prevent_default();
// Extract the form values into our `LoginForm` struct. The `.parsed_values` method
// is provided by Dioxus and works with any form element that has `name` attributes.
let values: LoginForm = evt.parsed_values().unwrap();
// Call our server function with the form values wrapped in `Form`. The `SetHeader`
// response will set a cookie in the browser if the login is successful.
fetch_login.call(Form(values)).await;
// Now that we're logged in, we can call our sensitive endpoint.
fetch_sensitive.call().await;
},
input { r#type: "text", id: "username", name: "username" }
label { "Username" }
input { r#type: "password", id: "password", name: "password" }
label { "Password" }
button { "Login" }
}
}
}
#[derive(Deserialize, Serialize)]
pub struct LoginForm {
username: String,
password: String,
}
/// A static session ID for demonstration purposes. This forces all previous logins to be invalidated
/// when the server restarts.
#[cfg(feature = "server")]
static THIS_SESSION_ID: LazyLock<Uuid> = LazyLock::new(Uuid::new_v4);
/// In our `login` form, we'll return a `SetCookie` header if the login is successful.
///
/// This will set a cookie in the user's browser that can be used for subsequent authenticated requests.
/// The `SetHeader::new()` method takes anything that can be converted into a `HeaderValue`.
///
/// We can set multiple headers by returning a tuple of `SetHeader` types, or passing in a tuple
/// of headers to `SetHeader::new()`.
#[post("/api/login")]
async fn login(form: Form<LoginForm>) -> Result<SetHeader<SetCookie>> {
// Verify the username and password. In a real application, you'd check these against a database.
if form.0.username == "admin" && form.0.password == "password" {
return Ok(SetHeader::new(format!("auth-demo={};", &*THIS_SESSION_ID))?);
}
HttpError::unauthorized("Invalid username or password")?
}
/// We'll use the `TypedHeader` extractor on the server to get the cookie from the request.
#[get("/api/sensitive", header: TypedHeader<Cookie>)]
async fn sensitive() -> Result<String> {
// Extract the cookie from the request headers and use `.eq` to verify its value.
// The `or_unauthorized` works on boolean values, returning a 401 if the condition is false.
header
.get("auth-demo")
.or_unauthorized("Missing auth-demo cookie")?
.eq(THIS_SESSION_ID.to_string().as_str())
.or_unauthorized("Invalid auth-demo cookie")?;
Ok("Sensitive data".to_string())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/server_sent_events.rs | examples/07-fullstack/server_sent_events.rs | //! This example demonstrates server-sent events (SSE) using Dioxus Fullstack.
//!
//! Server-sent events allow the server to push updates to the client over a single HTTP connection.
//! This is useful for real-time updates, notifications, or any scenario where the server needs to
//! send data to the client without the client explicitly requesting it.
//!
//! SSE is a simpler alternative to WebSockets, not requiring a full-duplex, stateful connection with
//! the server. Instead, it uses a single long-lived HTTP connection to stream events from the server to the client.
//!
//! This means that SSE messages are stringly encoded, and thus binary data must be base64 encoded.
//! If you need to send binary data, consider using the `Streaming<T>` type instead, which lets
//! you send raw bytes over a streaming HTTP response with a custom encoding. You'd reach for SSE
//! when dealing with clients that might not support custom streaming protocols.
//!
//! Calling an SSE endpoint is as simple as calling any other server function. The return type of an
//! SSE endpoint is a `ServerEvents<T>` where `T` is the type of event you want to send to the client.
//!
//! On the client, the `ServerEvents<T>` type implements `Stream<Item = Result<T, ServerFnError>>`
//! so you can use it with async streams to get new events as they arrive.
//!
//! `T` must be serializable and deserializable, so anything that implements `Serialize` and `Deserialize`
//! can be used as an event type. Calls to `.recv()` will wait for the next event to arrive and
//! deserialize it into the correct type.
use dioxus::prelude::*;
use dioxus_fullstack::ServerEvents;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut events = use_signal(Vec::new);
use_future(move || async move {
// Call the SSE endpoint to get a stream of events
let mut stream = listen_for_changes().await?;
// And then poll it for new events, adding them to our signal
while let Some(Ok(event)) = stream.recv().await {
events.push(event);
}
dioxus::Ok(())
});
rsx! {
h1 { "Events from server: " }
for msg in events.read().iter().rev() {
pre { "{msg:?}" }
}
}
}
/// We can send anything that's serializable as a server event - strings, numbers, structs, enums, etc.
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
enum MyServerEvent {
Yay { message: String },
Nay { error: String },
}
/// Our SSE endpoint, when called, will return the ServerEvents handle which streams events to the client.
/// On the client, we can interact with this stream object to get new events as they arrive.
#[get("/api/sse")]
async fn listen_for_changes() -> Result<ServerEvents<MyServerEvent>> {
use std::time::Duration;
Ok(ServerEvents::new(|mut tx| async move {
let mut count = 1;
loop {
// Create our serializable message
let msg = if count % 5 == 0 {
MyServerEvent::Nay {
error: "An error occurred".into(),
}
} else {
MyServerEvent::Yay {
message: format!("Hello number {count}"),
}
};
// Send the message to the client. If it errors, the client has disconnected
if tx.send(msg).await.is_err() {
// client disconnected, do some cleanup
break;
}
count += 1;
// Poll some data source here, subscribe to changes, maybe call an LLM?
tokio::time::sleep(Duration::from_secs(1)).await;
}
}))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/websocket.rs | examples/07-fullstack/websocket.rs | //! This example showcases the built-in websocket functionality in Dioxus Fullstack.
//!
//! We can create a new websocket endpoint that takes the WebSocketOptions as a body and returns
//! a `Websocket` instance that the client uses to communicate with the server.
//!
//! The `Websocket` type is generic over the message types and the encoding used to serialize the messages.
//!
//! By default, we use `JsonEncoding`, but in this example, we use `CborEncoding` to demonstrate that
//! binary encodings also work.
//!
//! The `use_websocket` hook wraps the `Websocket` instance and provides a reactive interface to the
//! state of the connection, as well as methods to send and receive messages.
//!
//! Because the websocket is generic over the message types, calls to `.recv()` and `.send()` are
//! strongly typed, making it easy to send and receive messages without having to manually
//! serialize and deserialize them.
use dioxus::{fullstack::CborEncoding, prelude::*};
use dioxus_fullstack::{WebSocketOptions, Websocket, use_websocket};
use serde::{Deserialize, Serialize};
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Track the messages we've received from the server.
let mut messages = use_signal(std::vec::Vec::new);
// The `use_websocket` wraps the `WebSocket` connection and provides a reactive handle to easily
// send and receive messages and track the connection state.
//
// We can customize the websocket connection with the `WebSocketOptions` struct, allowing us to
// set things like custom headers, protocols, reconnection strategies, etc.
let mut socket = use_websocket(|| uppercase_ws("John Doe".into(), 30, WebSocketOptions::new()));
// Calling `.recv()` automatically waits for the connection to be established and deserializes
// messages as they arrive.
use_future(move || async move {
while let Ok(msg) = socket.recv().await {
messages.push(msg);
}
});
rsx! {
h1 { "WebSocket Example" }
p { "Type a message and see it echoed back in uppercase!" }
p { "Connection status: {socket.status():?}" }
input {
placeholder: "Type a message",
oninput: move |e| async move { _ = socket.send(ClientEvent::TextInput(e.value())).await; },
}
button { onclick: move |_| messages.clear(), "Clear messages" }
for message in messages.read().iter().rev() {
pre { "{message:?}" }
}
}
}
#[derive(Serialize, Deserialize, Debug)]
enum ClientEvent {
TextInput(String),
}
#[derive(Serialize, Deserialize, Debug)]
enum ServerEvent {
Uppercase(String),
}
#[get("/api/uppercase_ws?name&age")]
async fn uppercase_ws(
name: String,
age: i32,
options: WebSocketOptions,
) -> Result<Websocket<ClientEvent, ServerEvent, CborEncoding>> {
Ok(options.on_upgrade(move |mut socket| async move {
// send back a greeting message
_ = socket
.send(ServerEvent::Uppercase(format!(
"Fist message from server: Hello, {}! You are {} years old.",
name, age
)))
.await;
// Loop and echo back uppercase messages
while let Ok(ClientEvent::TextInput(next)) = socket.recv().await {
_ = socket.send(ServerEvent::Uppercase(next)).await;
}
}))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/streaming_file_upload.rs | examples/07-fullstack/streaming_file_upload.rs | //! This example showcases how to upload files from the client to the server.
//!
//! We can use the `FileStream` type to handle file uploads in a streaming fashion.
//! This allows us to handle large files without loading them entirely into memory.
//!
//! `FileStream` and `FileDownload` are built on multi-part form data and streams, which we
//! also showcase here.
use dioxus::{
fullstack::{ByteStream, FileStream},
prelude::*,
};
use dioxus_html::{FileData, HasFileData};
use futures::StreamExt;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Dioxus provides the `FileStream` type for efficiently uploading files in a streaming fashion.
// This approach automatically automatically sets relevant metadata such as headers like
// Content-Type, Content-Length, and Content-Disposition.
//
// The `FileStream` type can be created from a `FileData` instance using `.into()`.
// This approach is better suited for public-facing APIs where standard headers are expected.
//
// `FileStream` uses the platform's native file streaming capabilities when available,
// making it more efficient than manually streaming bytes.
let mut upload_as_file_upload = use_action(move |files: Vec<FileData>| async move {
for file in files {
upload_file_as_filestream(file.into()).await?;
}
dioxus::Ok(())
});
// We can upload files by directly using the `ByteStream` type. With this approach, we need to
// specify the file name and size as query parameters since its an opaque stream.
//
// The `FileData` type has a `byte_stream` method which returns a `Pin<Box<dyn Stream<Item = Bytes> + Send>>`
// that we can turn into a `ByteStream` with `.into()`.
//
// In WASM, this will buffer the entire file in memory, so it's not the most efficient way to upload files.
// This approach is best suited for data created by the user in the browser.
let mut upload_files_as_bytestream = use_action(move |files: Vec<FileData>| async move {
info!("Uploading {} files", files.len());
for file in files {
upload_as_bytestream(file.name(), file.size(), file.byte_stream().into()).await?;
}
dioxus::Ok(())
});
let mut download_file = use_action(move || async move {
let mut file = download_as_filestream().await?;
let mut bytes = vec![];
info!("Downloaded file: {:?}", file);
while let Some(Ok(chunk)) = file.next().await {
bytes.extend_from_slice(&chunk);
}
dioxus::Ok(String::from_utf8_lossy(&bytes).to_string())
});
rsx! {
Stylesheet { href: asset!("/examples/assets/file_upload.css") }
div {
max_width: "600px",
margin: "auto",
h1 { "File upload example" }
div {
h3 { "Upload as FileUpload" }
div {
class: "drop-zone",
ondragover: move |evt| evt.prevent_default(),
ondrop: move |evt| async move {
evt.prevent_default();
upload_as_file_upload.call(evt.files()).await;
},
"Drop files here"
}
pre { "{upload_as_file_upload.value():?}" }
}
div {
h3 { "Upload as ByteStream" }
div {
class: "drop-zone",
ondragover: move |evt| evt.prevent_default(),
ondrop: move |evt| async move {
evt.prevent_default();
upload_files_as_bytestream.call(evt.files()).await;
},
"Drop files here"
}
}
div {
h3 { "Download a file from the server" }
button { onclick: move |_| download_file.call(), "Download file" }
if let Some(Ok(content)) = &download_file.value() {
pre { "{content}" }
} else if let Some(Err(e)) = &download_file.value() {
pre { "Error downloading file: {e}" }
}
}
}
}
}
/// Upload a file using the `FileStream` type which automatically sets relevant metadata
/// as headers like Content-Type, Content-Length, and Content-Disposition.
#[post("/api/upload_as_file_stream")]
async fn upload_file_as_filestream(mut upload: FileStream) -> Result<u32> {
use futures::StreamExt;
use std::env::temp_dir;
use tokio::io::AsyncWriteExt;
info!("Received file upload: {:?}", upload);
// Create a temporary file to write the uploaded data to.
let upload_file = std::path::absolute(temp_dir().join(upload.file_name()))?;
// Reject paths that are outside the temp directory for security reasons.
if !upload_file.starts_with(temp_dir()) {
HttpError::bad_request("Invalid file path")?;
}
info!(
"Uploading bytes of {:?} file to {:?}",
upload.size(),
upload_file
);
// Open the file for writing.
tokio::fs::create_dir_all(upload_file.parent().unwrap()).await?;
let mut file = tokio::fs::File::create(&upload_file).await?;
let expected = upload.size();
// Stream the data from the request body to the file.
let mut uploaded: u64 = 0;
let mut errored = false;
while let Some(chunk) = upload.next().await {
match chunk {
Ok(bytes) => {
uploaded += bytes.len() as u64;
if file.write_all(&bytes).await.is_err() {
errored = true;
break;
}
// 1GB max file size or attempting to upload more than expected.
if uploaded > expected.unwrap_or(1024 * 1024 * 1024) {
errored = true;
break;
}
}
Err(_) => {
errored = true;
break;
}
}
}
// Clean up the file if there was an error during upload.
if errored {
_ = file.sync_data().await;
let _ = tokio::fs::remove_file(&upload_file).await;
HttpError::internal_server_error("Failed to upload file")?;
}
Ok(uploaded as u32)
}
/// Upload a file as a raw byte stream. This requires us to specify the file name and size
/// as query parameters since the `ByteStream` type is an opaque stream without metadata.
///
/// We could also use custom headers to pass metadata if we wanted to avoid query parameters.
#[post("/api/upload_as_bytestream?name&size")]
async fn upload_as_bytestream(name: String, size: u64, mut stream: ByteStream) -> Result<()> {
let mut collected = 0;
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
collected += chunk.len() as u64;
info!("Received {} bytes for file {}", chunk.len(), name);
if collected > size {
HttpError::bad_request("Received more data than expected")?;
}
}
Ok(())
}
/// Download a file from the server as a `FileStream`. This automatically sets relevant
/// headers like Content-Type, Content-Length, and Content-Disposition.
///
/// This endpoint is nice because 3rd-party clients can visit it directly and download the file!
/// Try visiting this endpoint directly in your browser.
#[get("/api/download_as_filestream")]
async fn download_as_filestream() -> Result<FileStream> {
Ok(FileStream::from_path(file!()).await?)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/redirect.rs | examples/07-fullstack/redirect.rs | //! This example shows how to use the axum `Redirect` type to redirect the client to a different URL.
//!
//! On the web, a redirect will not be handled directly by JS, but instead the browser will automatically
//! follow the redirect. This is useful for redirecting to different pages after a form submission.
//!
//! Note that redirects returned to the client won't navigate the SPA to a new page automatically.
//! For managing a session or auth with client side routing, you'll need to handle that in the SPA itself.
use dioxus::{fullstack::Redirect, prelude::*};
fn main() {
dioxus::launch(|| {
rsx! {
Router::<Route> {}
}
});
}
#[derive(Clone, PartialEq, Routable)]
enum Route {
#[route("/")]
Home,
#[route("/blog")]
Blog,
}
#[component]
fn Home() -> Element {
rsx! {
h1 { "Welcome home" }
form {
method: "post",
action: "/api/old-blog",
button { "Go to blog" }
}
}
}
#[component]
fn Blog() -> Element {
rsx! {
h1 { "Welcome to the blog!" }
}
}
#[post("/api/old-blog")]
async fn redirect_to_blog() -> Result<Redirect> {
Ok(Redirect::to("/blog"))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/middleware.rs | examples/07-fullstack/middleware.rs | //! This example shows how to use middleware in a fullstack Dioxus app.
//!
//! Dioxus supports two ways of middleware:
//! - Applying layers to the top-level axum router
//! - Apply `#[middleware]` attributes to individual handlers
use dioxus::prelude::*;
#[cfg(feature = "server")]
use {std::time::Duration, tower_http::timeout::TimeoutLayer};
fn main() {
#[cfg(not(feature = "server"))]
dioxus::launch(app);
#[cfg(feature = "server")]
dioxus::serve(|| async move {
use axum::{extract::Request, middleware::Next};
use dioxus::server::axum;
Ok(dioxus::server::router(app)
// we can apply a layer to the entire router using axum's `.layer` method
.layer(axum::middleware::from_fn(
|request: Request, next: Next| async move {
println!("Request: {} {}", request.method(), request.uri().path());
let res = next.run(request).await;
println!("Response: {}", res.status());
res
},
)))
});
}
fn app() -> Element {
let mut per_route = use_action(per_route_middleware);
rsx! {
h1 { "Fullstack Middleware Example" }
button { onclick: move |_| per_route.call(), "Fetch Data" }
pre { "{per_route.value():#?}" }
}
}
// We can use the `#[middleware]` attribute to apply middleware to individual handlers.
//
// Here, we're applying a timeout to the `per_route_middleware` handler, which will return a 504
// if the handler takes longer than 3 seconds to complete.
//
// To add multiple middleware layers, simply stack multiple `#[middleware]` attributes.
#[get("/api/count")]
#[middleware(TimeoutLayer::with_status_code(408.try_into().unwrap(), Duration::from_secs(3)))]
async fn per_route_middleware() -> Result<String> {
tokio::time::sleep(Duration::from_secs(5)).await;
Ok("Hello, world!".to_string())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/full_request_access.rs | examples/07-fullstack/full_request_access.rs | //! This example shows how to get access to the full axum request in a handler.
//!
//! The extra arguments in the `post` macro are passed to the handler function, but not exposed
//! to the client. This means we can still call the endpoint from the client, but have full access
//! to the request on the server.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut file_id = use_action(full_request);
rsx! {
div { "Access to full axum request" }
button { onclick: move |_| file_id.call(), "Upload file" }
}
}
/// Example of accessing the full axum request in a handler
///
/// The `request: axum_core::extract::Request` argument is placed in the handler function, but not
/// exposed to the client.
#[post("/api/full_request_access", request: axum_core::extract::Request)]
async fn full_request() -> Result<()> {
let headers = request.headers();
if headers.contains_key("x-api-key") {
println!("API key found");
} else {
println!("No API key found");
}
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/through_reqwest.rs | examples/07-fullstack/through_reqwest.rs | //! This example demonstrates that dioxus server functions can be be called directly as a Rust
//! function or via an HTTP request using reqwest.
//!
//! Dioxus server functions generated a REST endpoint that can be called using any HTTP client.
//! By default, they also support different serialization formats like JSON and CBOR. Try changing
//! your `accept` header to see the different formats.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut user_from_server_fn = use_action(get_user);
let mut user_from_reqwest = use_action(move |id: i32| async move {
let port = dioxus::cli_config::server_port().unwrap_or(8080);
reqwest::get(&format!("http://localhost:{}/api/user/{}", port, id))
.await?
.json::<User>()
.await
});
rsx! {
button { onclick: move |_| user_from_server_fn.call(123), "Fetch Data" }
button { onclick: move |_| user_from_reqwest.call(456), "Fetch From Endpoint" }
div { display: "flex", flex_direction: "column",
pre { "User from server: {user_from_server_fn.value():?}", }
pre { "User from server: {user_from_reqwest.value():?}", }
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct User {
id: String,
name: String,
}
#[get("/api/user/{id}")]
async fn get_user(id: i32) -> Result<User> {
Ok(User {
id: id.to_string(),
name: "John Doe".into(),
})
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/custom_axum_serve.rs | examples/07-fullstack/custom_axum_serve.rs | //! This example demonstrates how to use `dioxus::serve` with a custom Axum router.
//!
//! By default, `dioxus::launch` takes over the main thread and runs the Dioxus application.
//! However, if you want to integrate Dioxus into an existing web server or use a custom router,
//! you can use `dioxus::serve` to create a server that serves your Dioxus application alongside
//! other routes.
//!
//! `dioxus::serve` sets up an async runtime, logging, hot-reloading, crash handling, and more.
//! You can then use the `.serve_dioxus_application` method on your router to serve the Dioxus app.
//!
//! `dioxus::serve` is most useful for customizing the server setup, such as adding middleware,
//! custom routes, or integrating with existing axum backend code.
//!
//! Note that `dioxus::serve` is accepts a Router from `axum`. Dioxus will use the IP and PORT
//! environment variables to determine where to bind the server. To customize the port, use environment
//! variables or a `.env` file.
//!
//! On other platforms (like desktop or mobile), you'll want to use `dioxus::launch` instead and then
//! handle async loading of data through hooks like `use_future` or `use_resource` and give the user
//! a loading state while data is being fetched.
use dioxus::prelude::*;
fn main() {
// On the client we just launch the app as normal.
#[cfg(not(feature = "server"))]
dioxus::launch(app);
// On the server, we can use `dioxus::serve` and `.serve_dioxus_application` to serve our app with routing.
// The `dioxus::server::router` function creates a new axum Router with the necessary routes to serve the Dioxus app.
#[cfg(feature = "server")]
dioxus::serve(|| async move {
use dioxus::server::axum::routing::{get, post};
Ok(dioxus::server::router(app)
.route("/submit", post(|| async { "Form submitted!" }))
.route("/about", get(|| async { "About us" }))
.route("/contact", get(|| async { "Contact us" })))
});
}
fn app() -> Element {
rsx! {
div { "Hello from Dioxus!" }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/dog_app_self_hosted.rs | examples/07-fullstack/dog_app_self_hosted.rs | //! This example showcases a fullstack variant of the "dog app" demo, but with the loader and actions
//! self-hosted instead of using the Dog API.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
// Fetch the list of breeds from the Dog API, using the `?` syntax to suspend or throw errors
let breed_list = use_loader(list_breeds)?;
// Whenever this action is called, it will re-run the future and return the result.
let mut breed = use_action(get_random_breed_image);
rsx! {
h1 { "Doggo selector" }
div { width: "400px",
for cur_breed in breed_list.read().iter().take(20).cloned() {
button { onclick: move |_| { breed.call(cur_breed.clone()); }, "{cur_breed}" }
}
}
div {
match breed.value() {
None => rsx! { div { "Click the button to fetch a dog!" } },
Some(Err(_e)) => rsx! { div { "Failed to fetch a dog, please try again." } },
Some(Ok(res)) => rsx! { img { max_width: "500px", max_height: "500px", src: "{res}" } },
}
}
}
}
#[get("/api/breeds/list/all")]
async fn list_breeds() -> Result<Vec<String>> {
Ok(vec!["bulldog".into(), "labrador".into(), "poodle".into()])
}
#[get("/api/breed/{breed}/images/random")]
async fn get_random_breed_image(breed: String) -> Result<String> {
match breed.as_str() {
"bulldog" => Ok("https://images.dog.ceo/breeds/buhund-norwegian/hakon3.jpg".into()),
"labrador" => Ok("https://images.dog.ceo/breeds/labrador/n02099712_2501.jpg".into()),
"poodle" => Ok("https://images.dog.ceo/breeds/poodle-standard/n02113799_5973.jpg".into()),
_ => HttpError::not_found("Breed not found")?,
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/fullstack_hello_world.rs | examples/07-fullstack/fullstack_hello_world.rs | //! A simple example using Dioxus Fullstack to call a server action.
//!
//! the `get`, `post`, `put`, `delete`, etc macros are used to define server actions that can be
//! called from the client. The action can take arguments and return a value, and the client
//! will automatically serialize and deserialize the data.
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<String> {
Ok(format!("Hello {}, you are {} years old!", name, age))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/query_params.rs | examples/07-fullstack/query_params.rs | //! An example showcasing query parameters in Dioxus Fullstack server functions.
//!
//! The query parameter syntax mostly follows axum, but with a few extra conveniences.
//! - can rename parameters in the function signature with `?age=age_in_years` where `age_in_years` is Rust variable name
//! - can absorb all query params with `?{object}` directly into a struct implementing `Deserialize`
use dioxus::prelude::*;
fn main() {
dioxus::launch(|| {
let mut message = use_action(get_message);
let mut message_rebind = use_action(get_message_rebind);
let mut message_all = use_action(get_message_all);
rsx! {
h1 { "Server says: "}
div {
button { onclick: move |_| message.call(22), "Single" }
pre { "{message:?}"}
}
div {
button { onclick: move |_| message_rebind.call(25), "Rebind" }
pre { "{message_rebind:?}"}
}
div {
button { onclick: move |_| message_all.call(Params { age: 30, name: "world".into() }), "Bind all" }
pre { "{message_all:?}"}
}
}
});
}
#[get("/api/message/?age")]
async fn get_message(age: i32) -> Result<String> {
Ok(format!("You are {} years old!", age))
}
#[get("/api/rebind/?age=age_in_years")]
async fn get_message_rebind(age_in_years: i32) -> Result<String> {
Ok(format!("You are {} years old!", age_in_years))
}
#[derive(serde::Deserialize, serde::Serialize, Debug)]
struct Params {
age: i32,
name: String,
}
#[get("/api/all/?{query}")]
async fn get_message_all(query: Params) -> Result<String> {
Ok(format!(
"Hello {}, you are {} years old!",
query.name, query.age
))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/server_functions.rs | examples/07-fullstack/server_functions.rs | //! This example is a simple showcase of Dioxus Server Functions.
//!
//! The other examples in this folder showcase advanced features of server functions like custom
//! data types, error handling, websockets, and more.
//!
//! This example is meant to just be a simple starting point to show how server functions work.
//!
//! ## Server Functions
//!
//! In Dioxus, Server Functions are `axum` backend endpoints that can be called directly from the client
//! as if you were simply calling a local Rust function. You can do anything with a server function
//! that an Axum handler can do like extracting path, query, headers, and body parameters.
//!
//! ## Server Function Arguments
//!
//! Unlike Axum handlers, the arguments of the server functions have some special magic enabled by
//! the accompanying `#[get]`/`#[post]` attributes. This magic enables you to choose between
//! arguments that are purely serializable (i.e. `String`, `i32`, `Vec<T>`, etc) as the JSON body of
//!
//! the request *or* arguments that implement Axum's `FromRequest` trait. This magic enables simple
//! RPC functions but also complex extractors for things like auth, sessions, cookies, and more.
//!
//! ## Server Function Return Types
//!
//! The return type of the server function is also somewhat magical. Unlike Axum handlers, all server
//! functions must return a `Result` type, giving the client an opportunity to handle errors properly.
//!
//! The `Ok` type can be anything that implements `Serialize + DeserializeOwned` so it can be sent
//! to the client as JSON, or it can be anything that implements `IntoResponse` just like an Axum handler.
//!
//! ## Error Types
//!
//! The `Err` type of the server function return type is also somewhat special. The `Err` type can be:
//! - `anyhow::Error` (the `dioxus_core::Err` type alias) for untyped errors with rich context. Note
//! that these errors will always downcast to `ServerFnError` on the client, losing the original
//! error stack and type.
//! - `ServerFnError` for typed errors with a status code and optional message.
//! - `StatusCode` for returning raw HTTP status codes.
//! - `HttpError` for returning HTTP status codes with custom messages.
//! - Any custom errors that implement `From<ServerFnError>` and are `Serialize`/`Deserialize`
//!
//! The only way to set the HTTP status code of the response is to use one of the above error types,
//! or to implement a custom `IntoResponse` type that sets the status code manually.
//!
//! The `anyhow::Error` type is the best choice for rapid development, but is somewhat limited when
//! handling specific error cases on the client since all errors are downcast to `ServerFnError`.
//!
//! ## Calling Server Functions from the Client
//!
//! Server functions can be called from the client by simply importing the function and calling it
//! like a normal Rust function. Unlike regular axum handlers, Dioxus server functions have a few
//! non-obvious restrictions.
//!
//! Most importantly, the arguments to the server function must implement either `Deserialize` *or*
//! `IntoRequest`. The `IntoRequest` trait is a Dioxus abstraction that represents the "inverse" of the
//! Axum `FromRequest` trait. Anything that is sent to the server from the client must be both extractable
//! with `FromRequest` on the server *and* constructible with `IntoRequest` on the client.
//!
//! Types like `WebsocketOptions` implement `IntoRequest` and pass along things like upgrade headers
//! to the server so that the server can properly upgrade the connection.
//!
//! When receiving data from the server, the return type must implement `Deserialize` *or* `FromResponse`.
//! The `FromResponse` trait is the inverse of Axum's `IntoResponse` trait, and is implemented
//! for types like `Websocket` where the raw HTTP response is needed to complete the construction
//! of the type.
//!
//! ## Server-only Extractors
//!
//! Because the arguments of the server function define the structure of the public API, some extractors
//! might not make sense to expose directly, nor would they be possible to construct on the client.
//! For example, on the web, you typically don't work directly with cookies since the browser handles
//! them for you. In these cases, the client would omit the `Cookie` header entirely, and we would need
//! "hoist" our extractor into a "server-only extractor".
//!
//! Server-only extractors are function arguments placed after the path in the `#[get]`/`#[post]` attribute.
//! These arguments are extracted on the server, but not passed in from the client. This lets the
//! server function remain callable from the client, while still allowing full access to axum's
//! extractors.
//!
//! ```
//! #[post("/api/authenticate", auth: AuthCookie)]
//! async fn authenticate() -> Result<User> { /* ... */ }
//! ```
//!
//! ## Automatic Registration
//!
//! Unlike axum handlers, server functions do not need to be manually registered with a router.
//! By default, *all* server functions in your app will be automatically registered with the
//! server when you call `dioxus::launch` or create a router manually with `dioxus::server::router()`.
//!
//! However, not all server functions are automatically registered by default. Server functions that
//! take a `State<T>` extractor cannot be automatically added to the router since the dioxus router
//! type does not know how to construct the `T` type.
//!
//! These server functions will be registered once the `ServerState<T>` layer is added to the app with
//! `router = router.layer(ServerState::new(your_state))`.
//!
//! ## Middleware
//!
//! Middleware can be added to server functions using the `#[middleware(MiddlewareType)]` attribute.
//! Middleware will be applied in the order they are specified, and will be applied before any
//! server-only extractors.
//!
//! To add router-level middleware, you can customize the axum `Router` using layers and extensions
//! as you would in a normal axum app.
//!
//! ## Anonymous Server Functions
//!
//! The `#[server]` attribute can be used without a path to create an anonymous server function.
//! These functions are still exposed as HTTP endpoints, but their names are procedurally generated
//! from the module path, function name, and a hash of the function signature. This makes it hard to
//! call these functions with `curl` or `postman`, but save you the trouble of coming up with unique
//! names for simple functions that are only called from your Dioxus app.
//!
//! If you're shipping desktop/mobile apps, we don't recommend using anonymous server functions
//! since the function names could change between builds and thus make older versions of your app
//! incompatible with newer versions of your server.
//!
//! ## Cross-platform Clients
//!
//! Server functions can be called from any platform (web, desktop mobile, etc) and use the best
//! underlying `fetch` implementation available.
//!
//! ## More examples
//!
//! With Dioxus Fullstack 0.7, pretty much anything you can do with an Axum handler, you can do with
//! a server function. More advanced examples can be found in this folder showcasing custom data types,
//! error handling, websockets, and more.
use axum_core::response::IntoResponse;
use dioxus::prelude::*;
use dioxus_fullstack::FromResponse;
use dioxus_fullstack::http::StatusCode;
use serde::{Deserialize, Serialize};
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut echo_action = use_action(echo);
let mut chat_action = use_action(chat);
let mut dog_data = use_action(get_data);
let mut custom_data = use_action(get_custom_data);
let mut anonymous_action = use_action(anonymous);
let mut custom_anonymous_action = use_action(custom_anonymous);
let mut custom_response_action = use_action(get_custom_response);
rsx! {
h1 { "Server Functions Example" }
div {
display: "flex",
flex_direction: "column",
gap: "8px",
button { onclick: move |_| echo_action.call("Hello from client".into()), "Echo: Hello" }
button { onclick: move |_| chat_action.call(42u32, Some(7u32)), "Chat (user 42, room 7)" }
button { onclick: move |_| dog_data.call(), "Get dog data" }
button { onclick: move |_| custom_data.call(), "Get custom data" }
button { onclick: move |_| anonymous_action.call(), "Call anonymous" }
button { onclick: move |_| custom_anonymous_action.call(), "Call custom anonymous" }
button { onclick: move |_| custom_response_action.call(), "Get custom response" }
button {
onclick: move |_| {
echo_action.reset();
chat_action.reset();
dog_data.reset();
custom_data.reset();
anonymous_action.reset();
custom_anonymous_action.reset();
custom_response_action.reset();
},
"Clear results"
}
pre { "Echo result: {echo_action.value():#?}" }
pre { "Chat result: {chat_action.value():#?}" }
pre { "Dog data: {dog_data.value():#?}" }
pre { "Custom data: {custom_data.value():#?}" }
pre { "Anonymous: {anonymous_action.value():#?}" }
pre { "Custom anonymous: {custom_anonymous_action.value():#?}" }
pre { "Custom response: {custom_response_action.value():#?}" }
}
}
}
/// A plain server function at a `POST` endpoint that takes a string and returns it.
/// Here, we use the `Result` return type which is an alias to `Result<T, anyhow::Error>`.
#[post("/api/echo")]
async fn echo(body: String) -> Result<String> {
Ok(body)
}
/// A Server function that takes path and query parameters, as well as a server-only extractor.
#[post("/api/{user_id}/chat?room_id", headers: dioxus_fullstack::HeaderMap)]
async fn chat(user_id: u32, room_id: Option<u32>) -> Result<String> {
Ok(format!(
"User ID: {}, Room ID: {} - Headers: {:#?}",
user_id,
room_id.map_or("None".to_string(), |id| id.to_string()),
headers
))
}
/// A plain server function at a `GET` endpoint that returns some JSON data. Because `DogData` is
/// `Serialize` and `Deserialize`, it can be sent to the client as JSON automatically.
///
/// You can `curl` this endpoint and it will return a 200 status code with a JSON body:
///
/// ```json
/// {
/// "name": "Fido",
/// "age": 4
/// }
/// ```
#[get("/api/dog")]
async fn get_data() -> Result<DogData> {
Ok(DogData {
name: "Fido".to_string(),
age: 4,
})
}
#[derive(Serialize, Deserialize, Debug)]
struct DogData {
name: String,
age: u8,
}
/// A server function that returns a custom struct as JSON.
#[get("/api/custom")]
async fn get_custom_data() -> Result<CustomData> {
Ok(CustomData {
message: "Hello from the server!".to_string(),
})
}
#[derive(Debug)]
struct CustomData {
message: String,
}
impl IntoResponse for CustomData {
fn into_response(self) -> axum_core::response::Response {
axum_core::response::Response::builder()
.status(StatusCode::ACCEPTED)
.body(serde_json::to_string(&self.message).unwrap().into())
.unwrap()
}
}
impl FromResponse for CustomData {
async fn from_response(res: dioxus_fullstack::ClientResponse) -> Result<Self, ServerFnError> {
let message = res.json::<String>().await?;
Ok(CustomData { message })
}
}
/// A server function that returns an axum type directly.
///
/// When make these endpoints, we need to use the `axum::response::Response` type and then call `into_response`
/// on the return value to convert it into a response.
#[get("/api/custom_response")]
async fn get_custom_response() -> Result<axum_core::response::Response> {
Ok(axum_core::response::Response::builder()
.status(StatusCode::CREATED)
.body("Created!".to_string())
.unwrap()
.into_response())
}
/// An anonymous server function - the url path is generated from the module path and function name.
///
/// This will end up as `/api/anonymous_<hash>` where `<hash>` is a hash of the function signature.
#[server]
async fn anonymous() -> Result<String> {
Ok("Hello from an anonymous server function!".to_string())
}
/// An anonymous server function with a custom prefix and a fixed endpoint name.
///
/// This is less preferred over the `#[get]`/`#[post]` syntax but is still functional for backwards
/// compatibility. Previously, only the `#[server]` attribute was available, but as of Dioxus 0.7,
/// the `#[get]`/`#[post]` attributes are preferred for new code.
///
/// You can also use server-only extractors here as well, provided they come after the configuration.
#[server(prefix = "/api/custom", endpoint = "my_anonymous", headers: dioxus_fullstack::HeaderMap)]
async fn custom_anonymous() -> Result<String> {
Ok(format!(
"Hello from a custom anonymous server function! -> {:#?}",
headers
))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/streaming.rs | examples/07-fullstack/streaming.rs | //! This example shows how to use the `Streaming<T, E>` type to send streaming responses from the
//! server to the client (and the client to the server!).
//!
//! The `Streaming<T, E>` type automatically coordinates sending and receiving streaming data over HTTP.
//! The `T` type parameter is the type of data being sent, and the `E` type parameter is the encoding
//! used to serialize and deserialize the data.
//!
//! Dioxus Fullstack provides several built-in encodings:
//! - JsonEncoding: the default, uses JSON for serialization
//! - CborEncoding: uses CBOR for binary serialization
//! - PostcardEncoding: uses Postcard for binary serialization
//! - MsgPackEncoding: uses MessagePack for binary serialization
//! - RkyvEncoding: uses Rkyv for zero-copy binary serialization
//!
//! The default encoding is `JsonEncoding`, which works well for most use cases and can be used by
//! most clients. If you need a more efficient binary encoding, consider using one of the
//! binary encodings.
use bytes::Bytes;
use dioxus::{
fullstack::{JsonEncoding, Streaming, TextStream},
prelude::*,
};
fn main() {
dioxus::launch(app)
}
fn app() -> Element {
let mut text_responses = use_signal(String::new);
let mut json_responses = use_signal(Vec::new);
let mut start_text_stream = use_action(move || async move {
text_responses.clear();
let mut stream = text_stream(Some(100)).await?;
while let Some(Ok(text)) = stream.next().await {
text_responses.push_str(&text);
text_responses.push('\n');
}
dioxus::Ok(())
});
let mut start_json_stream = use_action(move || async move {
json_responses.clear();
let mut stream = json_stream().await?;
while let Some(Ok(dog)) = stream.next().await {
json_responses.push(dog);
}
dioxus::Ok(())
});
rsx! {
div {
button { onclick: move |_| start_text_stream.call(), "Start text stream" }
button { onclick: move |_| start_text_stream.cancel(), "Stop text stream" }
pre { "{text_responses}" }
}
div {
button { onclick: move |_| start_json_stream.call(), "Start JSON stream" }
button { onclick: move |_| start_json_stream.cancel(), "Stop JSON stream" }
for dog in json_responses.read().iter() {
pre { "{dog:?}" }
}
}
}
}
/// The `TextStream` type is an alias for `Streaming<String>` with a text/plain encoding.
///
/// The `TextStream::new()` method takes anything that implements `Stream<Item = String>`, so
/// we can use a channel to send strings from a background task.
#[get("/api/test_stream?start")]
async fn text_stream(start: Option<i32>) -> Result<TextStream> {
let (tx, rx) = futures::channel::mpsc::unbounded();
tokio::spawn(async move {
let mut count = start.unwrap_or(0);
loop {
let message = format!("Hello, world! {}", count);
if tx.unbounded_send(message).is_err() {
break;
}
count += 1;
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
}
});
Ok(Streaming::new(rx))
}
#[derive(serde::Serialize, serde::Deserialize, Debug)]
struct Dog {
name: String,
age: u8,
}
/// A custom `Streaming<T, E>` endpoint that streams JSON-encoded `Dog` structs to the client.
///
/// Dioxus provides the `JsonEncoding` type which can be used to encode and decode JSON data.
#[get("/api/json_stream")]
async fn json_stream() -> Result<Streaming<Dog, JsonEncoding>> {
let (tx, rx) = futures::channel::mpsc::unbounded();
tokio::spawn(async move {
let mut count = 0;
loop {
let dog = Dog {
name: format!("Dog {}", count),
age: (count % 10) as u8,
};
if tx.unbounded_send(dog).is_err() {
// If the channel is closed, stop sending chunks
break;
}
count += 1;
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
}
});
Ok(Streaming::new(rx))
}
/// An example of streaming raw bytes to the client using `Streaming<Bytes>`.
/// This is useful for sending binary data, such as images, files, or zero-copy data.
#[get("/api/byte_stream")]
async fn byte_stream() -> Result<Streaming<Bytes>> {
let (tx, rx) = futures::channel::mpsc::unbounded();
tokio::spawn(async move {
let mut count = 0;
loop {
let bytes = vec![count; 10];
if tx.unbounded_send(bytes.into()).is_err() {
break;
}
count = (count + 1) % 255;
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
}
});
Ok(Streaming::new(rx))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/custom_error_page.rs | examples/07-fullstack/custom_error_page.rs | //! To render custom error pages, you can create a layout component that captures errors from routes
//! with an `ErrorBoundary` and display different content based on the error type.
//!
//! While capturing the error, we set the appropriate HTTP status code using `FullstackContext::commit_error_status`.
//! The router will then use this status code when doing server-side rendering (SSR).
//!
//! Any errors not captured by an error boundary will be handled by dioxus-ssr itself, which will render
//! a generic error page instead.
use dioxus::prelude::*;
use dioxus_fullstack::{FullstackContext, StatusCode};
fn main() {
dioxus::launch(|| {
rsx! {
Router::<Route> {}
}
});
}
#[derive(Routable, PartialEq, Clone, Debug)]
enum Route {
#[layout(ErrorLayout)]
#[route("/")]
Home,
#[route("/blog/:id")]
Blog { id: u32 },
}
#[component]
fn Home() -> Element {
rsx! {
div { "Welcome to the home page!" }
div { display: "flex", flex_direction: "column",
Link { to: Route::Blog { id: 1 }, "Go to blog post 1" }
Link { to: Route::Blog { id: 2 }, "Go to blog post 2" }
Link { to: Route::Blog { id: 3 }, "Go to blog post 3 (error)" }
Link { to: Route::Blog { id: 4 }, "Go to blog post 4 (not found)" }
}
}
}
#[component]
fn Blog(id: u32) -> Element {
match id {
1 => rsx! { div { "Blog post 1" } },
2 => rsx! { div { "Blog post 2" } },
3 => dioxus_core::bail!("An error occurred while loading the blog post!"),
_ => HttpError::not_found("Blog post not found")?,
}
}
/// In our `ErrorLayout` component, we wrap the `Outlet` in an `ErrorBoundary`. This lets us attempt
/// to downcast the error to an `HttpError` and set the appropriate status code.
///
/// The `commit_error_status` function will attempt to downcast the error to an `HttpError` and
/// set the status code accordingly. Note that you can commit any status code you want with `commit_http_status`.
///
/// The router will automatically set the HTTP status code when doing SSR.
#[component]
fn ErrorLayout() -> Element {
rsx! {
ErrorBoundary {
handle_error: move |err: ErrorContext| {
let http_error = FullstackContext::commit_error_status(err.error().unwrap());
match http_error.status {
StatusCode::NOT_FOUND => rsx! { div { "404 - Page not found" } },
StatusCode::UNAUTHORIZED => rsx! { div { "401 - Unauthorized" } },
StatusCode::INTERNAL_SERVER_ERROR => rsx! { div { "500 - Internal Server Error" } },
_ => rsx! { div { "An unknown error occurred" } },
}
},
Outlet::<Route> {}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/server_state.rs | examples/07-fullstack/server_state.rs | //! This example shows how to use global state to maintain state between server functions.
use std::rc::Rc;
use axum_core::extract::{FromRef, FromRequest};
use dioxus::{
fullstack::{FullstackContext, extract::State},
prelude::*,
};
use reqwest::header::HeaderMap;
#[cfg(feature = "server")]
use {
dioxus::fullstack::Lazy,
dioxus::fullstack::axum,
futures::lock::Mutex,
sqlx::{Executor, Row},
std::sync::LazyLock,
};
/*
Option 1:
For simple, synchronous, thread-safe data, we can use statics with atomic types or mutexes.
The `LazyLock` type from the standard library is a great choice for simple, synchronous data
*/
#[cfg(feature = "server")]
static MESSAGES: LazyLock<Mutex<Vec<String>>> = LazyLock::new(|| Mutex::new(Vec::new()));
#[post("/api/messages")]
async fn add_message() -> Result<()> {
MESSAGES.lock().await.push("New message".to_string());
Ok(())
}
#[get("/api/messages")]
async fn read_messages() -> Result<Vec<String>> {
Ok(MESSAGES.lock().await.clone())
}
/*
Option 2:
For complex async data, we can use the `Lazy` type from Dioxus Fullstack. The `Lazy` type provides
an interface like `once_cell::Lazy` but supports async initialization. When reading the value from
a `Lazy<T>`, the value will be initialized synchronously, blocking the current task until the value is ready.
Alternatively, you can create a `Lazy<T>` with `Lazy::lazy` and then initialize it later with
`Lazy::initialize`.
*/
#[cfg(feature = "server")]
static DATABASE: Lazy<sqlx::SqlitePool> = Lazy::new(|| async move {
use sqlx::sqlite::SqlitePoolOptions;
dioxus::Ok(
SqlitePoolOptions::new()
.max_connections(5)
.connect_with("sqlite::memory:".parse().unwrap())
.await?,
)
});
/// When using the `Lazy<T>` type, it implements `Deref<Target = T>`, so you can use it like a normal reference.
#[get("/api/users")]
async fn get_users() -> Result<Vec<String>> {
let users = DATABASE
.fetch_all(sqlx::query("SELECT name FROM users"))
.await?
.iter()
.map(|row| row.get::<String, _>("name"))
.collect::<Vec<_>>();
Ok(users)
}
/*
Option 3:
For data that needs to be provided per-request, we can use axum's `Extension` type to provide
data to our app. This is useful for things like request-scoped data or data that needs to be
initialized per-requestz
*/
#[cfg(feature = "server")]
type BroadcastExtension = axum::Extension<tokio::sync::broadcast::Sender<String>>;
#[post("/api/broadcast", ext: BroadcastExtension)]
async fn broadcast_message() -> Result<()> {
let rt = Rc::new("asdasd".to_string());
ext.send("New broadcast message".to_string())?;
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
println!("rt: {}", rt);
Ok(())
}
/*
Option 4:
You can use Axum's `State` extractor to provide custom application state to your server functions.
All ServerFunctions pull in `FullstackContext`, so you need to implement `FromRef<FullstackContext>` for your
custom state type. To add your state to your app, you can use `.register_server_functions()` on a router
for a given state type, which will automatically add your state into the `FullstackContext` used by your server functions.
There are two details to note here:
- You need to implement `FromRef<FullstackContext>` for your custom state type.
- Custom extractors need to implement `FromRequest<S>` where `S` is the state type that implements `FromRef<FullstackContext>`.
*/
#[derive(Clone)]
struct MyAppState {
abc: i32,
}
impl FromRef<FullstackContext> for MyAppState {
fn from_ref(state: &FullstackContext) -> Self {
state.extension::<MyAppState>().unwrap()
}
}
struct CustomExtractor {
abc: i32,
headermap: HeaderMap,
}
impl<S> FromRequest<S> for CustomExtractor
where
MyAppState: FromRef<S>,
S: Send + Sync,
{
type Rejection = ();
async fn from_request(
_req: axum::extract::Request,
state: &S,
) -> std::result::Result<Self, Self::Rejection> {
let state = MyAppState::from_ref(state);
Ok(CustomExtractor {
abc: state.abc,
headermap: HeaderMap::new(),
})
}
}
#[post("/api/stateful", state: State<MyAppState>, ex: CustomExtractor)]
async fn app_state() -> Result<()> {
println!("abc: {}", state.abc);
println!("state abc: {:?}", ex.abc);
println!("headermap: {:?}", ex.headermap);
Ok(())
}
fn main() {
#[cfg(not(feature = "server"))]
dioxus::launch(app);
// When using `Lazy` items, or axum `Extension`s, we need to initialize them in `dioxus::serve`
// before launching our app.
#[cfg(feature = "server")]
dioxus::serve(|| async move {
use dioxus::server::axum::Extension;
// For axum `Extension`s, we can use the `layer` method to add them to our router.
let router = dioxus::server::router(app)
.layer(Extension(tokio::sync::broadcast::channel::<String>(16).0));
// To use our custom app state with `State<MyAppState>`, we need to register it
// as an extension since our `FromRef<FullstackContext>` implementation relies on it.
let router = router.layer(Extension(MyAppState { abc: 42 }));
Ok(router)
});
}
fn app() -> Element {
let mut users = use_action(get_users);
let mut messages = use_action(read_messages);
let mut broadcast = use_action(broadcast_message);
let mut add = use_action(add_message);
rsx! {
div {
button { onclick: move |_| users.call(), "Get Users" }
pre { "{users.value():?}" }
button { onclick: move |_| messages.call(), "Get Messages" }
pre { "{messages.value():?}" }
button { onclick: move |_| broadcast.call(), "Broadcast Message" }
pre { "{broadcast.value():?}" }
button { onclick: move |_| add.call(), "Add Message" }
pre { "{add.value():?}" }
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/handling_errors.rs | examples/07-fullstack/handling_errors.rs | //! An example of handling errors from server functions.
//!
//! This example showcases a few important error handling patterns when using Dioxus Fullstack.
//!
//! Run with:
//!
//! ```sh
//! dx serve --web
//! ```
//!
//! What this example shows:
//! - You can return `anyhow::Result<T>` (i.e. `Result<T>` without an `E`) for
//! untyped errors with rich context (converted to HTTP 500 responses by default).
//! - You can return `Result<T, E>` where `E` is one of:
//! - `HttpError` (convenience for returning HTTP status codes)
//! - `StatusCode` (return raw status codes)
//! - a custom error type that implements `From<ServerFnError>` or
//! is `Serialize`/`Deserialize` so it can be sent to the client.
//! - This file demonstrates external API errors, custom typed errors, explicit
//! HTTP errors, and basic success cases. The UI uses `use_action` to call
//! server functions and shows loading/result states simply.
//!
//! Try running requests against the endpoints directly with `curl` or `postman` to see the actual HTTP responses!
use dioxus::fullstack::{AsStatusCode, Json, StatusCode};
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
fn main() {
dioxus::launch(|| {
let mut dog_data = use_action(get_dog_data);
let mut dog_data_err = use_action(get_dog_data_err);
let mut ip_data = use_action(get_ip_data);
let mut custom_data = use_action(move || {
get_custom_encoding(Json(serde_json::json!({
"example": "data",
"number": 123,
"array": [1, 2, 3],
})))
});
let mut error_data = use_action(get_throws_error);
let mut typed_error_data = use_action(get_throws_typed_error);
let mut throws_ok_data = use_action(get_throws_ok);
let mut http_error_data = use_action(throws_http_error);
let mut http_error_context_data = use_action(throws_http_error_context);
rsx! {
button { onclick: move |_| { dog_data.call(); }, "Fetch dog data" }
button { onclick: move |_| { ip_data.call(); }, "Fetch IP data" }
button { onclick: move |_| { custom_data.call(); }, "Fetch custom encoded data" }
button { onclick: move |_| { error_data.call(); }, "Fetch error data" }
button { onclick: move |_| { typed_error_data.call(); }, "Fetch typed error data" }
button { onclick: move |_| { dog_data_err.call(); }, "Fetch dog error data" }
button { onclick: move |_| { throws_ok_data.call(); }, "Fetch throws ok data" }
button { onclick: move |_| { http_error_data.call(); }, "Fetch HTTP 400" }
button { onclick: move |_| { http_error_context_data.call(); }, "Fetch HTTP 400 (context)" }
button {
onclick: move |_| {
ip_data.reset();
dog_data.reset();
custom_data.reset();
error_data.reset();
typed_error_data.reset();
dog_data_err.reset();
throws_ok_data.reset();
http_error_data.reset();
http_error_context_data.reset();
},
"Clear data"
}
div { display: "flex", flex_direction: "column", gap: "8px",
pre { "Dog data: {dog_data.value():#?}" }
pre { "IP data: {ip_data.value():#?}" }
pre { "Custom encoded data: {custom_data.value():#?}" }
pre { "Error data: {error_data.value():#?}" }
pre { "Typed error data: {typed_error_data.value():#?}" }
pre { "HTTP 400 data: {http_error_data.value():#?}" }
pre { "HTTP 400 (context) data: {http_error_context_data.value():#?}" }
pre { "Dog error data: {dog_data_err.value():#?}" }
pre { "Throws ok data: {throws_ok_data.value():#?}" }
}
}
});
}
/// Simple POST endpoint used to show a successful server function that returns `StatusCode`.
#[post("/api/data")]
async fn post_server_data(data: String) -> Result<(), StatusCode> {
println!("Server received: {}", data);
Ok(())
}
/// Fetches IP info from an external service. Demonstrates propagation of external errors.
#[get("/api/ip-data")]
async fn get_ip_data() -> Result<serde_json::Value> {
Ok(reqwest::get("https://httpbin.org/ip").await?.json().await?)
}
/// Fetches a random dog image (successful external API example).
#[get("/api/dog-data")]
async fn get_dog_data() -> Result<serde_json::Value> {
Ok(reqwest::get("https://dog.ceo/api/breeds/image/random")
.await?
.json()
.await?)
}
/// Calls the Dog API with an invalid breed to trigger an external API error (e.g. 404).
#[get("/api/dog-data-err")]
async fn get_dog_data_err() -> Result<serde_json::Value> {
Ok(
reqwest::get("https://dog.ceo/api/breed/NOT_A_REAL_DOG/images")
.await?
.json()
.await?,
)
}
/// Accepts JSON and returns a custom-encoded JSON response.
#[post("/api/custom-encoding")]
async fn get_custom_encoding(takes: Json<serde_json::Value>) -> Result<serde_json::Value> {
Ok(serde_json::json!({
"message": "This response was encoded with a custom encoder!",
"success": true,
"you sent": takes.0,
}))
}
/// Returns an untyped `anyhow` error with context (results in HTTP 500).
#[get("/api/untyped-error")]
async fn get_throws_error() -> Result<()> {
Err(None.context("This is an example error using anyhow::Error")?)
}
/// Demonstrates returning an explicit HTTP error (400 Bad Request) using `HttpError`.
#[get("/api/throws-http-error")]
async fn throws_http_error() -> Result<()> {
HttpError::bad_request("Bad request example")?;
Ok(())
}
/// Convenience example: handles an Option and returns HTTP 400 with a message if None.
#[get("/api/throws-http-error-context")]
async fn throws_http_error_context() -> Result<String> {
let res = None.or_bad_request("Value was None")?;
Ok(res)
}
/// A simple server function that always succeeds.
#[get("/api/throws-ok")]
async fn get_throws_ok() -> Result<()> {
Ok(())
}
#[derive(thiserror::Error, Debug, Serialize, Deserialize)]
enum MyCustomError {
#[error("bad request")]
BadRequest { custom_name: String },
#[error("not found")]
NotFound,
#[error("internal server error: {0}")]
ServerFnError(#[from] ServerFnError),
}
impl AsStatusCode for MyCustomError {
fn as_status_code(&self) -> StatusCode {
match self {
MyCustomError::BadRequest { .. } => StatusCode::BAD_REQUEST,
MyCustomError::NotFound => StatusCode::NOT_FOUND,
MyCustomError::ServerFnError(e) => e.as_status_code(),
}
}
}
/// Returns a custom typed error (serializable) so clients can handle specific cases.
///
/// Our custom error must implement `AsStatusCode` so it can properly set the outgoing HTTP status code.
#[get("/api/typed-error")]
async fn get_throws_typed_error() -> Result<(), MyCustomError> {
Err(MyCustomError::BadRequest {
custom_name: "Invalid input".into(),
})
}
/// Simple POST endpoint used to show a successful server function that returns `StatusCode`.
#[post("/api/data")]
async fn get_throws_serverfn_error() -> Result<(), ServerFnError> {
Err(ServerFnError::ServerError {
message: "Unauthorized access".to_string(),
code: StatusCode::UNAUTHORIZED.as_u16(),
details: None,
})
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/auth/src/auth.rs | examples/07-fullstack/auth/src/auth.rs | //! The code here is pulled from the `axum-session-auth` crate examples, requiring little to no
//! modification to work with dioxus fullstack.
use async_trait::async_trait;
use axum_session_auth::*;
use axum_session_sqlx::SessionSqlitePool;
use serde::{Deserialize, Serialize};
use sqlx::sqlite::SqlitePool;
use std::collections::HashSet;
pub(crate) type Session = axum_session_auth::AuthSession<User, i64, SessionSqlitePool, SqlitePool>;
pub(crate) type AuthLayer =
axum_session_auth::AuthSessionLayer<User, i64, SessionSqlitePool, SqlitePool>;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct User {
pub id: i32,
pub anonymous: bool,
pub username: String,
pub permissions: HashSet<String>,
}
#[derive(sqlx::FromRow, Clone)]
pub(crate) struct SqlPermissionTokens {
pub token: String,
}
#[async_trait]
impl Authentication<User, i64, SqlitePool> for User {
async fn load_user(userid: i64, pool: Option<&SqlitePool>) -> Result<User, anyhow::Error> {
let db = pool.unwrap();
#[derive(sqlx::FromRow, Clone)]
struct SqlUser {
id: i32,
anonymous: bool,
username: String,
}
let sqluser = sqlx::query_as::<_, SqlUser>("SELECT * FROM users WHERE id = $1")
.bind(userid)
.fetch_one(db)
.await
.unwrap();
//lets just get all the tokens the user can use, we will only use the full permissions if modifying them.
let sql_user_perms = sqlx::query_as::<_, SqlPermissionTokens>(
"SELECT token FROM user_permissions WHERE user_id = $1;",
)
.bind(userid)
.fetch_all(db)
.await
.unwrap();
Ok(User {
id: sqluser.id,
anonymous: sqluser.anonymous,
username: sqluser.username,
permissions: sql_user_perms.into_iter().map(|x| x.token).collect(),
})
}
fn is_authenticated(&self) -> bool {
!self.anonymous
}
fn is_active(&self) -> bool {
!self.anonymous
}
fn is_anonymous(&self) -> bool {
self.anonymous
}
}
#[async_trait]
impl HasPermission<SqlitePool> for User {
async fn has(&self, perm: &str, _pool: &Option<&SqlitePool>) -> bool {
self.permissions.contains(perm)
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/auth/src/main.rs | examples/07-fullstack/auth/src/main.rs | //! This example showcases how to use the `axum-session-auth` crate with Dioxus fullstack.
//! We add the `auth::Session` extractor to our server functions to get access to the current user session.
//!
//! To initialize the axum router, we use `dioxus::serve` to spawn a custom axum server that creates
//! our database, session store, and authentication layer.
//!
//! The `.serve_dioxus_application` method is used to mount our Dioxus app as a fallback service to
//! handle HTML rendering and static assets.
//!
//! We easily share the "permissions" between the server and client by using a `HashSet<String>`
//! which is serialized to/from JSON automatically by the server function system.
use std::collections::HashSet;
use dioxus::prelude::*;
#[cfg(feature = "server")]
mod auth;
fn main() {
// On the client, we simply launch the app as normal, taking over the main thread
#[cfg(not(feature = "server"))]
dioxus::launch(app);
// On the server, we can use `dioxus::serve` to create a server that serves our app.
//
// The `serve` function takes a closure that returns a `Future` which resolves to an `axum::Router`.
//
// We return a `Router` such that dioxus sets up logging, hot-reloading, devtools, and wires up the
// IP and PORT environment variables to our server.
#[cfg(feature = "server")]
dioxus::serve(|| async {
use crate::auth::*;
use axum_session::{SessionConfig, SessionLayer, SessionStore};
use axum_session_auth::AuthConfig;
use axum_session_sqlx::SessionSqlitePool;
use sqlx::{sqlite::SqlitePoolOptions, Executor};
// Create an in-memory SQLite database and set up our tables
let db = SqlitePoolOptions::new()
.max_connections(20)
.connect_with("sqlite::memory:".parse()?)
.await?;
// Create the tables (sessions, users)
db.execute(r#"CREATE TABLE IF NOT EXISTS users ( "id" INTEGER PRIMARY KEY, "anonymous" BOOLEAN NOT NULL, "username" VARCHAR(256) NOT NULL )"#,)
.await?;
db.execute(r#"CREATE TABLE IF NOT EXISTS user_permissions ( "user_id" INTEGER NOT NULL, "token" VARCHAR(256) NOT NULL)"#,)
.await?;
// Insert in some test data for two users (one anonymous, one normal)
db.execute(r#"INSERT INTO users (id, anonymous, username) SELECT 1, true, 'Guest' ON CONFLICT(id) DO UPDATE SET anonymous = EXCLUDED.anonymous, username = EXCLUDED.username"#,)
.await?;
db.execute(r#"INSERT INTO users (id, anonymous, username) SELECT 2, false, 'Test' ON CONFLICT(id) DO UPDATE SET anonymous = EXCLUDED.anonymous, username = EXCLUDED.username"#,)
.await?;
// Make sure our test user has the ability to view categories
db.execute(r#"INSERT INTO user_permissions (user_id, token) SELECT 2, 'Category::View'"#)
.await?;
// Create an axum router that dioxus will attach the app to
Ok(dioxus::server::router(app)
.layer(
AuthLayer::new(Some(db.clone()))
.with_config(AuthConfig::<i64>::default().with_anonymous_user_id(Some(1))),
)
.layer(SessionLayer::new(
SessionStore::<SessionSqlitePool>::new(
Some(db.into()),
SessionConfig::default().with_table_name("test_table"),
)
.await?,
)))
});
}
/// The UI for our app - is just a few buttons to call our server functions and display the results.
fn app() -> Element {
let mut login = use_action(login);
let mut user_name = use_action(get_user_name);
let mut permissions = use_action(get_permissions);
let mut logout = use_action(logout);
let fetch_new = move |_| async move {
user_name.call().await;
permissions.call().await;
};
rsx! {
div {
button {
onclick: move |_| async move {
login.call().await;
},
"Login Test User"
}
button {
onclick: move |_| async move {
logout.call().await;
},
"Logout"
}
button {
onclick: fetch_new,
"Fetch User Info"
}
pre { "Logged in: {login.value():?}" }
pre { "User name: {user_name.value():?}" }
pre { "Permissions: {permissions.value():?}" }
}
}
}
/// We use the `auth::Session` extractor to get access to the current user session.
/// This lets us modify the user session, log in/out, and access the current user.
#[post("/api/user/login", auth: auth::Session)]
pub async fn login() -> Result<()> {
auth.login_user(2);
Ok(())
}
/// Just like `login`, but this time we log out the user.
#[post("/api/user/logout", auth: auth::Session)]
pub async fn logout() -> Result<()> {
auth.logout_user();
Ok(())
}
/// We can access the current user via `auth.current_user`.
/// We can have both anonymous user (id 1) and a logged in user (id 2).
///
/// Logged-in users will have more permissions which we can modify.
#[post("/api/user/name", auth: auth::Session)]
pub async fn get_user_name() -> Result<String> {
Ok(auth.current_user.unwrap().username)
}
/// Get the current user's permissions, guarding the endpoint with the `Auth` validator.
/// If this returns false, we use the `or_unauthorized` extension to return a 401 error.
#[get("/api/user/permissions", auth: auth::Session)]
pub async fn get_permissions() -> Result<HashSet<String>> {
use crate::auth::User;
use axum_session_auth::{Auth, Rights};
let user = auth.current_user.unwrap();
Auth::<User, i64, sqlx::SqlitePool>::build([axum::http::Method::GET], false)
.requires(Rights::any([
Rights::permission("Category::View"),
Rights::permission("Admin::View"),
]))
.validate(&user, &axum::http::Method::GET, None)
.await
.or_unauthorized("You do not have permission to view categories")?;
Ok(user.permissions)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/desktop/src/main.rs | examples/07-fullstack/desktop/src/main.rs | #![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
// Make sure to set the url of the server where server functions are hosted - they aren't always at localhost
#[cfg(not(feature = "server"))]
dioxus::fullstack::set_server_url("http://127.0.0.1:8080");
dioxus::launch(app);
}
pub fn app() -> Element {
let mut count = use_signal(|| 0);
let mut text = use_signal(|| "...".to_string());
rsx! {
h1 { "High-Five counter: {count}" }
button { onclick: move |_| count += 1, "Up high!" }
button { onclick: move |_| count -= 1, "Down low!" }
button {
onclick: move |_| async move {
let data = get_server_data().await?;
println!("Client received: {}", data);
text.set(data.clone());
post_server_data(data).await?;
Ok(())
},
"Run a server function"
}
"Server said: {text}"
}
}
#[post("/api/data")]
async fn post_server_data(data: String) -> ServerFnResult {
println!("Server received: {}", data);
Ok(())
}
#[get("/api/data")]
async fn get_server_data() -> ServerFnResult<String> {
Ok("Hello from the server!".to_string())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/hello-world/src/main.rs | examples/07-fullstack/hello-world/src/main.rs | //! A simple hello world example for Dioxus fullstack
//!
//! Run with:
//!
//! ```sh
//! dx serve --web
//! ```
//!
//! This example demonstrates a simple Dioxus fullstack application with a client-side counter
//! and a server function that returns a greeting message.
//!
//! The `use_action` hook makes it easy to call async work (like server functions) from the client side
//! and handle loading and error states.
use dioxus::prelude::*;
use dioxus_fullstack::get;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut count = use_signal(|| 0);
let mut message = use_action(get_greeting);
rsx! {
div { style: "padding: 2rem; font-family: Arial, sans-serif;",
h1 { "Hello, Dioxus Fullstack!" }
// Client-side counter - you can use any client functionality in your app!
div { style: "margin: 1rem 0;",
h2 { "Client Counter: {count}" }
button { onclick: move |_| count += 1, "Increment" }
button { onclick: move |_| count -= 1, "Decrement" }
}
// We can handle the action result and display loading state
div { style: "margin: 1rem 0;",
h2 { "Server Greeting" }
button { onclick: move |_| message.call("World".to_string(), 30), "Get Server Greeting" }
if message.pending() {
p { "Loading..." }
}
p { "{message:#?}" }
}
}
}
}
/// A simple server function that returns a greeting
///
/// Our server function takes a name as a path and query parameters as inputs and returns a greeting message.
#[get("/api/greeting/{name}/{age}")]
async fn get_greeting(name: String, age: i32) -> Result<String> {
Ok(format!(
"Hello from the server, {}! You are {} years old. 🚀",
name, age
))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/ssr-only/src/main.rs | examples/07-fullstack/ssr-only/src/main.rs | //! This example showcases how to use Fullstack in a server-side rendering only context.
//!
//! This means we have no client-side bundle at all, and *everything* is rendered on the server.
//! You can still use signals, resources, etc, but they won't be reactive on the client.
//!
//! This is useful for static site generation, or if you want to use Dioxus Fullstack as a server-side
//! framework without the `rsx! {}` markup.
//!
//! To run this example, simply run `cargo run --package ssr-only` and navigate to `http://localhost:8080`.
use dioxus::prelude::*;
fn main() {
dioxus::launch(|| rsx! { Router::<Route> { } });
}
#[derive(Routable, Clone, Debug, PartialEq)]
enum Route {
#[route("/")]
Home,
#[route("/post/:id")]
Post { id: u32 },
}
#[component]
fn Home() -> Element {
rsx! {
h1 { "home" }
ul {
li { a { href: "/post/1", "Post 1" } }
li { a { href: "/post/2", "Post 2" } }
li { a { href: "/post/3", "Post 3 (404)" } }
}
}
}
#[component]
fn Post(id: ReadSignal<u32>) -> Element {
// You can return `HttpError` to return a specific HTTP status code and message.
// `404 Not Found` will cause the server to return a 404 status code.
//
// `use_loader` will suspend the server-side rendering until the future resolves.
let post_data = use_loader(move || get_post(id()))?;
rsx! {
h1 { "Post {id}" }
p { "{post_data}" }
}
}
#[get("/api/post/{id}")]
async fn get_post(id: u32) -> Result<String, HttpError> {
match id {
1 => Ok("first post".to_string()),
2 => Ok("second post".to_string()),
_ => HttpError::not_found("Post not found")?,
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/07-fullstack/router/src/main.rs | examples/07-fullstack/router/src/main.rs | //! Run with:
//!
//! ```sh
//! dx serve --platform web
//! ```
use dioxus::prelude::*;
fn main() {
dioxus::LaunchBuilder::new()
.with_cfg(server_only!(ServeConfig::builder().incremental(
dioxus::server::IncrementalRendererConfig::default()
.invalidate_after(std::time::Duration::from_secs(120)),
)))
.launch(app);
}
fn app() -> Element {
rsx! { Router::<Route> {} }
}
#[derive(Clone, Routable, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
enum Route {
#[route("/")]
Home {},
#[route("/blog/:id/")]
Blog { id: i32 },
}
#[component]
fn Blog(id: i32) -> Element {
rsx! {
Link { to: Route::Home {}, "Go to counter" }
table {
tbody {
for _ in 0..id {
tr {
for _ in 0..id {
td { "hello world!" }
}
}
}
}
}
}
}
#[component]
fn Home() -> Element {
let mut count = use_signal(|| 0);
let mut text = use_signal(|| "...".to_string());
rsx! {
Link { to: Route::Blog { id: count() }, "Go to blog" }
div {
h1 { "High-Five counter: {count}" }
button { onclick: move |_| count += 1, "Up high!" }
button { onclick: move |_| count -= 1, "Down low!" }
button {
onclick: move |_| async move {
let data = get_server_data().await?;
println!("Client received: {}", data);
text.set(data.clone());
post_server_data(data).await?;
Ok(())
},
"Run server function!"
}
"Server said: {text}"
}
}
}
#[post("/api/data")]
async fn post_server_data(data: String) -> ServerFnResult {
println!("Server received: {}", data);
Ok(())
}
#[get("/api/data")]
async fn get_server_data() -> ServerFnResult<String> {
Ok("Hello from the server!".to_string())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/02-building-ui/nested_listeners.rs | examples/02-building-ui/nested_listeners.rs | //! Nested Listeners
//!
//! This example showcases how to control event bubbling from child to parents.
//!
//! Both web and desktop support bubbling and bubble cancellation.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
div {
onclick: move |_| println!("clicked! top"),
"- div"
button {
onclick: move |_| println!("clicked! bottom propagate"),
"Propagate"
}
button {
onclick: move |evt| {
println!("clicked! bottom no bubbling");
evt.stop_propagation();
},
"Dont propagate"
}
button {
"Does not handle clicks - only propagate"
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/02-building-ui/svg.rs | examples/02-building-ui/svg.rs | //! Thanks to @japsu and their project https://github.com/japsu/jatsi for the example!
//!
//! This example shows how to create a simple dice rolling app using SVG and Dioxus.
//! The `svg` element and its children have a custom namespace, and are attached using different methods than regular
//! HTML elements. Any element can specify a custom namespace by using the `namespace` meta attribute.
//!
//! If you `go-to-definition` on the `svg` element, you'll see its custom namespace.
use dioxus::prelude::*;
use rand::{Rng, rng};
fn main() {
dioxus::launch(|| {
rsx! {
div { user_select: "none", webkit_user_select: "none", margin_left: "10%", margin_right: "10%",
h1 { "Click die to generate a new value" }
div { cursor: "pointer", height: "100%", width: "100%", Dice {} }
}
}
});
}
#[component]
fn Dice() -> Element {
const Y: bool = true;
const N: bool = false;
const DOTS: [(i64, i64); 7] = [(-1, -1), (-1, -0), (-1, 1), (1, -1), (1, 0), (1, 1), (0, 0)];
const DOTS_FOR_VALUE: [[bool; 7]; 6] = [
[N, N, N, N, N, N, Y],
[N, N, Y, Y, N, N, N],
[N, N, Y, Y, N, N, Y],
[Y, N, Y, Y, N, Y, N],
[Y, N, Y, Y, N, Y, Y],
[Y, Y, Y, Y, Y, Y, N],
];
let mut value = use_signal(|| 5);
let active_dots = use_memo(move || &DOTS_FOR_VALUE[(value() - 1) as usize]);
rsx! {
svg {
view_box: "-1000 -1000 2000 2000",
onclick: move |event| {
event.prevent_default();
value.set(rng().random_range(1..=6))
},
rect { x: -1000, y: -1000, width: 2000, height: 2000, rx: 200, fill: "#aaa" }
for ((x, y), _) in DOTS.iter().zip(active_dots.read().iter()).filter(|(_, active)| **active) {
circle {
cx: *x * 600,
cy: *y * 600,
r: 200,
fill: "#333"
}
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/02-building-ui/disabled.rs | examples/02-building-ui/disabled.rs | //! A simple demonstration of how to set attributes on buttons to disable them.
//!
//! This example also showcases the shorthand syntax for attributes, and how signals themselves implement IntoAttribute
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut disabled = use_signal(|| false);
rsx! {
div { text_align: "center", margin: "20px", display: "flex", flex_direction: "column", align_items: "center",
button {
onclick: move |_| disabled.toggle(),
"click to "
if disabled() { "enable" } else { "disable" }
" the lower button"
}
button { disabled, "lower button" }
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/05-using-async/suspense.rs | examples/05-using-async/suspense.rs | //! Suspense in Dioxus
//!
//! Suspense allows components to bubble up loading states to parent components, simplifying data fetching.
use dioxus::prelude::*;
fn main() {
dioxus::launch(app)
}
fn app() -> Element {
rsx! {
div {
h1 { "Dogs are very important" }
p {
"The dog or domestic dog (Canis familiaris[4][5] or Canis lupus familiaris[5])"
"is a domesticated descendant of the wolf which is characterized by an upturning tail."
"The dog derived from an ancient, extinct wolf,[6][7] and the modern grey wolf is the"
"dog's nearest living relative.[8] The dog was the first species to be domesticated,[9][8]"
"by hunter–gatherers over 15,000 years ago,[7] before the development of agriculture.[1]"
}
h3 { "Illustrious Dog Photo" }
ErrorBoundary { handle_error: |_| rsx! { p { "Error loading doggos" } },
SuspenseBoundary { fallback: move |_| rsx! { "Loading doggos..." },
Doggo {}
}
}
}
}
}
#[component]
fn Doggo() -> Element {
// `use_loader` returns a Result<Loader<T>, Loading>. Loading can either be "Pending" or "Failed".
// When we use the `?` operator, the pending/error state will be thrown to the nearest Suspense or Error boundary.
//
// During SSR, `use_loader` will serialize the contents of the fetch, and during hydration, the client will
// use the pre-fetched data instead of re-fetching to render.
let mut dog = use_loader(move || async move {
#[derive(serde::Deserialize, serde::Serialize, PartialEq)]
struct DogApi {
message: String,
}
reqwest::get("https://dog.ceo/api/breeds/image/random/")
.await?
.json::<DogApi>()
.await
})?;
rsx! {
button { onclick: move |_| dog.restart(), "Click to fetch another doggo" }
div {
img {
max_width: "500px",
max_height: "500px",
src: "{dog.read().message}"
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/05-using-async/backgrounded_futures.rs | examples/05-using-async/backgrounded_futures.rs | //! Backgrounded futures example
//!
//! This showcases how use_future, use_memo, and use_effect will stop running if the component returns early.
//! Generally you should avoid using early returns around hooks since most hooks are not properly designed to
//! handle early returns. However, use_future *does* pause the future when the component returns early, and so
//! hooks that build on top of it like use_memo and use_effect will also pause.
//!
//! This example is more of a demonstration of the behavior than a practical use case, but it's still interesting to see.
use async_std::task::sleep;
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut show_child = use_signal(|| true);
let mut count = use_signal(|| 0);
let child = use_memo(move || {
rsx! {
Child { count }
}
});
rsx! {
// Some toggle/controls to show the child or increment the count
button { onclick: move |_| show_child.toggle(), "Toggle child" }
button { onclick: move |_| count += 1, "Increment count" }
if show_child() {
{child()}
}
}
}
#[component]
fn Child(count: WriteSignal<i32>) -> Element {
let mut early_return = use_signal(|| false);
let early = rsx! {
button { onclick: move |_| early_return.toggle(), "Toggle {early_return} early return" }
};
if early_return() {
return early;
}
use_future(move || async move {
loop {
sleep(std::time::Duration::from_millis(100)).await;
println!("Child")
}
});
use_effect(move || println!("Child count: {}", count()));
rsx! {
div {
"Child component"
{early}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/05-using-async/future.rs | examples/05-using-async/future.rs | //! A simple example that shows how to use the use_future hook to run a background task.
//!
//! use_future won't return a value, analogous to use_effect.
//! If you want to return a value from a future, use use_resource instead.
use async_std::task::sleep;
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut count = use_signal(|| 0);
// use_future is a non-reactive hook that simply runs a future in the background.
// You can use the UseFuture handle to pause, resume, restart, or cancel the future.
use_future(move || async move {
loop {
sleep(std::time::Duration::from_millis(200)).await;
count += 1;
}
});
// use_effect is a reactive hook that runs a future when signals captured by its reactive context
// are modified. This is similar to use_effect in React and is useful for running side effects
// that depend on the state of your component.
//
// Generally, we recommend performing async work in event as a reaction to a user event.
use_effect(move || {
spawn(async move {
sleep(std::time::Duration::from_secs(5)).await;
count.set(100);
});
});
// You can run futures directly from event handlers as well. Note that if the event handler is
// fired multiple times, the future will be spawned multiple times.
rsx! {
h1 { "Current count: {count}" }
button {
onclick: move |_| async move {
sleep(std::time::Duration::from_millis(200)).await;
count.set(0);
},
"Slowly reset the count"
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/05-using-async/streams.rs | examples/05-using-async/streams.rs | //! Handle async streams using use_future and awaiting the next value.
use async_std::task::sleep;
use dioxus::prelude::*;
use futures_util::{Stream, StreamExt, future, stream};
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut count = use_signal(|| 10);
use_future(move || async move {
// Create the stream.
// This could be a network request, a file read, or any other async operation.
let mut stream = some_stream();
// Await the next value from the stream.
while let Some(second) = stream.next().await {
count.set(second);
}
});
rsx! {
h1 { "High-Five counter: {count}" }
}
}
fn some_stream() -> std::pin::Pin<Box<dyn Stream<Item = i32>>> {
Box::pin(
stream::once(future::ready(0)).chain(stream::iter(1..).then(|second| async move {
sleep(std::time::Duration::from_secs(1)).await;
second
})),
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/examples/05-using-async/clock.rs | examples/05-using-async/clock.rs | //! A simple little clock that updates the time every few milliseconds.
use async_std::task::sleep;
use dioxus::prelude::*;
use web_time::Instant;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
let mut millis = use_signal(|| 0);
use_future(move || async move {
// Save our initial time
let start = Instant::now();
loop {
sleep(std::time::Duration::from_millis(27)).await;
// Update the time, using a more precise approach of getting the duration since we started the timer
millis.set(start.elapsed().as_millis() as i64);
}
});
// Format the time as a string
// This is rather cheap so it's fine to leave it in the render function
let time = format!(
"{:02}:{:02}:{:03}",
millis() / 1000 / 60 % 60,
millis() / 1000 % 60,
millis() % 1000
);
rsx! {
document::Stylesheet { href: asset!("/examples/assets/clock.css") }
div { id: "app",
div { id: "title", "Carpe diem 🎉" }
div { id: "clock-display", "{time}" }
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/const-serialize-macro/src/lib.rs | packages/const-serialize-macro/src/lib.rs | use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse_macro_input, DeriveInput, LitInt, Path};
use syn::{parse_quote, Generics, WhereClause, WherePredicate};
fn add_bounds(where_clause: &mut Option<WhereClause>, generics: &Generics, krate: &Path) {
let bounds = generics.params.iter().filter_map(|param| match param {
syn::GenericParam::Type(ty) => {
Some::<WherePredicate>(parse_quote! { #ty: #krate::SerializeConst, })
}
syn::GenericParam::Lifetime(_) => None,
syn::GenericParam::Const(_) => None,
});
if let Some(clause) = where_clause {
clause.predicates.extend(bounds);
} else {
*where_clause = Some(parse_quote! { where #(#bounds)* });
}
}
/// Derive the const serialize trait for a struct
#[proc_macro_derive(SerializeConst, attributes(const_serialize))]
pub fn derive_parse(raw_input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(raw_input as DeriveInput);
let krate = input.attrs.iter().find_map(|attr| {
attr.path()
.is_ident("const_serialize")
.then(|| {
let mut path = None;
if let Err(err) = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("crate") {
let ident: Path = meta.value()?.parse()?;
path = Some(ident);
}
Ok(())
}) {
return Some(Err(err));
}
path.map(Ok)
})
.flatten()
});
let krate = match krate {
Some(Ok(path)) => path,
Some(Err(err)) => return err.into_compile_error().into(),
None => parse_quote! { const_serialize },
};
match input.data {
syn::Data::Struct(data) => match data.fields {
syn::Fields::Unnamed(_) | syn::Fields::Named(_) => {
let ty = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let mut where_clause = where_clause.cloned();
add_bounds(&mut where_clause, &input.generics, &krate);
let field_names = data.fields.iter().enumerate().map(|(i, field)| {
field
.ident
.as_ref()
.map(|ident| ident.to_token_stream())
.unwrap_or_else(|| {
LitInt::new(&i.to_string(), proc_macro2::Span::call_site())
.into_token_stream()
})
});
let field_types = data.fields.iter().map(|field| &field.ty);
quote! {
unsafe impl #impl_generics #krate::SerializeConst for #ty #ty_generics #where_clause {
const MEMORY_LAYOUT: #krate::Layout = #krate::Layout::Struct(#krate::StructLayout::new(
std::mem::size_of::<Self>(),
&[#(
#krate::StructFieldLayout::new(
stringify!(#field_names),
std::mem::offset_of!(#ty, #field_names),
<#field_types as #krate::SerializeConst>::MEMORY_LAYOUT,
),
)*],
));
}
}.into()
}
syn::Fields::Unit => {
let ty = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let mut where_clause = where_clause.cloned();
add_bounds(&mut where_clause, &input.generics, &krate);
quote! {
unsafe impl #impl_generics #krate::SerializeConst for #ty #ty_generics #where_clause {
const MEMORY_LAYOUT: #krate::Layout = #krate::Layout::Struct(#krate::StructLayout::new(
std::mem::size_of::<Self>(),
&[],
));
}
}.into()
}
},
syn::Data::Enum(data) => match data.variants.len() {
0 => syn::Error::new(input.ident.span(), "Enums must have at least one variant")
.to_compile_error()
.into(),
1.. => {
let mut repr_c = false;
let mut discriminant_size = None;
for attr in &input.attrs {
if attr.path().is_ident("repr") {
if let Err(err) = attr.parse_nested_meta(|meta| {
// #[repr(C)]
if meta.path.is_ident("C") {
repr_c = true;
return Ok(());
}
// #[repr(u8)]
if meta.path.is_ident("u8") {
discriminant_size = Some(1);
return Ok(());
}
// #[repr(u16)]
if meta.path.is_ident("u16") {
discriminant_size = Some(2);
return Ok(());
}
// #[repr(u32)]
if meta.path.is_ident("u32") {
discriminant_size = Some(3);
return Ok(());
}
// #[repr(u64)]
if meta.path.is_ident("u64") {
discriminant_size = Some(4);
return Ok(());
}
Err(meta.error("unrecognized repr"))
}) {
return err.to_compile_error().into();
}
}
}
let variants_have_fields = data
.variants
.iter()
.any(|variant| !variant.fields.is_empty());
if !repr_c && variants_have_fields {
return syn::Error::new(input.ident.span(), "Enums must be repr(C, u*)")
.to_compile_error()
.into();
}
if discriminant_size.is_none() {
return syn::Error::new(input.ident.span(), "Enums must be repr(u*)")
.to_compile_error()
.into();
}
let ty = &input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let mut where_clause = where_clause.cloned();
add_bounds(&mut where_clause, &input.generics, &krate);
let mut last_discriminant = None;
let variants = data.variants.iter().map(|variant| {
let discriminant = variant
.discriminant
.as_ref()
.map(|(_, discriminant)| discriminant.to_token_stream())
.unwrap_or_else(|| match &last_discriminant {
Some(discriminant) => quote! { #discriminant + 1 },
None => {
quote! { 0 }
}
});
last_discriminant = Some(discriminant.clone());
let variant_name = &variant.ident;
let field_names = variant.fields.iter().enumerate().map(|(i, field)| {
field
.ident
.clone()
.unwrap_or_else(|| quote::format_ident!("__field_{}", i))
});
let field_types = variant.fields.iter().map(|field| &field.ty);
let generics = &input.generics;
quote! {
{
#[allow(unused)]
#[derive(#krate::SerializeConst)]
#[const_serialize(crate = #krate)]
#[repr(C)]
struct VariantStruct #generics {
#(
#field_names: #field_types,
)*
}
#krate::EnumVariant::new(
stringify!(#variant_name),
#discriminant as u32,
match <VariantStruct #generics as #krate::SerializeConst>::MEMORY_LAYOUT {
#krate::Layout::Struct(layout) => layout,
_ => panic!("VariantStruct::MEMORY_LAYOUT must be a struct"),
},
::std::mem::align_of::<VariantStruct>(),
)
}
}
});
quote! {
unsafe impl #impl_generics #krate::SerializeConst for #ty #ty_generics #where_clause {
const MEMORY_LAYOUT: #krate::Layout = #krate::Layout::Enum(#krate::EnumLayout::new(
::std::mem::size_of::<Self>(),
#krate::PrimitiveLayout::new(
#discriminant_size as usize,
),
{
const DATA: &'static [#krate::EnumVariant] = &[
#(
#variants,
)*
];
DATA
},
));
}
}.into()
}
},
_ => syn::Error::new(input.ident.span(), "Only structs and enums are supported")
.to_compile_error()
.into(),
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-macro/src/lib.rs | packages/fullstack-macro/src/lib.rs | // TODO: Create README, uncomment this: #![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
use core::panic;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::ToTokens;
use quote::{format_ident, quote};
use std::collections::HashMap;
use syn::{
braced, bracketed,
parse::ParseStream,
punctuated::Punctuated,
token::{Comma, Slash},
Error, ExprTuple, FnArg, Meta, PathArguments, PathSegment, Token, Type, TypePath,
};
use syn::{parse::Parse, parse_quote, Ident, ItemFn, LitStr, Path};
use syn::{spanned::Spanned, LitBool, LitInt, Pat, PatType};
use syn::{
token::{Brace, Star},
Attribute, Expr, ExprClosure, Lit, Result,
};
/// ## Usage
///
/// ```rust,ignore
/// # use dioxus::prelude::*;
/// # #[derive(serde::Deserialize, serde::Serialize)]
/// # struct BlogPost;
/// # async fn load_posts(category: &str) -> Result<Vec<BlogPost>> { unimplemented!() }
///
/// #[server]
/// async fn blog_posts(category: String) -> Result<Vec<BlogPost>> {
/// let posts = load_posts(&category).await?;
/// // maybe do some other work
/// Ok(posts)
/// }
/// ```
///
/// ## Named Arguments
///
/// You can use any combination of the following named arguments:
/// - `endpoint`: a prefix at which the server function handler will be mounted (defaults to `/api`).
/// Example: `endpoint = "/my_api/my_serverfn"`.
/// - `input`: the encoding for the arguments, defaults to `Json<T>`
/// - You may customize the encoding of the arguments by specifying a different type for `input`.
/// - Any axum `IntoRequest` extractor can be used here, and dioxus provides
/// - `Json<T>`: The default axum `Json` extractor that decodes JSON-encoded request bodies.
/// - `Cbor<T>`: A custom axum `Cbor` extractor that decodes CBOR-encoded request bodies.
/// - `MessagePack<T>`: A custom axum `MessagePack` extractor that decodes MessagePack-encoded request bodies.
/// - `output`: the encoding for the response (defaults to `Json`).
/// - The `output` argument specifies how the server should encode the response data.
/// - Acceptable values include:
/// - `Json`: A response encoded as JSON (default). This is ideal for most web applications.
/// - `Cbor`: A response encoded in the CBOR format for efficient, binary-encoded data.
/// - `client`: a custom `Client` implementation that will be used for this server function. This allows
/// customization of the client-side behavior if needed.
///
/// ## Advanced Usage of `input` and `output` Fields
///
/// The `input` and `output` fields allow you to customize how arguments and responses are encoded and decoded.
/// These fields impose specific trait bounds on the types you use. Here are detailed examples for different scenarios:
///
/// ## Adding layers to server functions
///
/// Layers allow you to transform the request and response of a server function. You can use layers
/// to add authentication, logging, or other functionality to your server functions. Server functions integrate
/// with the tower ecosystem, so you can use any layer that is compatible with tower.
///
/// Common layers include:
/// - [`tower_http::trace::TraceLayer`](https://docs.rs/tower-http/latest/tower_http/trace/struct.TraceLayer.html) for tracing requests and responses
/// - [`tower_http::compression::CompressionLayer`](https://docs.rs/tower-http/latest/tower_http/compression/struct.CompressionLayer.html) for compressing large responses
/// - [`tower_http::cors::CorsLayer`](https://docs.rs/tower-http/latest/tower_http/cors/struct.CorsLayer.html) for adding CORS headers to responses
/// - [`tower_http::timeout::TimeoutLayer`](https://docs.rs/tower-http/latest/tower_http/timeout/struct.TimeoutLayer.html) for adding timeouts to requests
/// - [`tower_sessions::service::SessionManagerLayer`](https://docs.rs/tower-sessions/0.13.0/tower_sessions/service/struct.SessionManagerLayer.html) for adding session management to requests
///
/// You can add a tower [`Layer`](https://docs.rs/tower/latest/tower/trait.Layer.html) to your server function with the middleware attribute:
///
/// ```rust,ignore
/// # use dioxus::prelude::*;
/// #[server]
/// // The TraceLayer will log all requests to the console
/// #[middleware(tower_http::timeout::TimeoutLayer::new(std::time::Duration::from_secs(5)))]
/// pub async fn my_wacky_server_fn(input: Vec<String>) -> ServerFnResult<usize> {
/// unimplemented!()
/// }
/// ```
#[proc_macro_attribute]
pub fn server(attr: proc_macro::TokenStream, mut item: TokenStream) -> TokenStream {
// Parse the attribute list using the old server_fn arg parser.
let args = match syn::parse::<ServerFnArgs>(attr) {
Ok(args) => args,
Err(err) => {
let err: TokenStream = err.to_compile_error().into();
item.extend(err);
return item;
}
};
let method = Method::Post(Ident::new("POST", proc_macro2::Span::call_site()));
let prefix = args
.prefix
.unwrap_or_else(|| LitStr::new("/api", Span::call_site()));
let route: Route = Route {
method: None,
path_params: vec![],
query_params: vec![],
route_lit: args.fn_path,
oapi_options: None,
server_args: args.server_args,
prefix: Some(prefix),
_input_encoding: args.input,
_output_encoding: args.output,
};
match route_impl_with_route(route, item.clone(), Some(method)) {
Ok(mut tokens) => {
// Let's add some deprecated warnings to the various fields from `args` if the user is using them...
// We don't generate structs anymore, don't use various protocols, etc
if let Some(name) = args.struct_name {
tokens.extend(quote! {
const _: () = {
#[deprecated(note = "Dioxus server functions no longer generate a struct for the server function. The function itself is used directly.")]
struct #name;
fn ___assert_deprecated() {
let _ = #name;
}
()
};
});
}
//
tokens.into()
}
// Retain the original function item and append the error to it. Better for autocomplete.
Err(err) => {
let err: TokenStream = err.to_compile_error().into();
item.extend(err);
item
}
}
}
#[proc_macro_attribute]
pub fn get(args: proc_macro::TokenStream, body: TokenStream) -> TokenStream {
wrapped_route_impl(args, body, Some(Method::new_from_string("GET")))
}
#[proc_macro_attribute]
pub fn post(args: proc_macro::TokenStream, body: TokenStream) -> TokenStream {
wrapped_route_impl(args, body, Some(Method::new_from_string("POST")))
}
#[proc_macro_attribute]
pub fn put(args: proc_macro::TokenStream, body: TokenStream) -> TokenStream {
wrapped_route_impl(args, body, Some(Method::new_from_string("PUT")))
}
#[proc_macro_attribute]
pub fn delete(args: proc_macro::TokenStream, body: TokenStream) -> TokenStream {
wrapped_route_impl(args, body, Some(Method::new_from_string("DELETE")))
}
#[proc_macro_attribute]
pub fn patch(args: proc_macro::TokenStream, body: TokenStream) -> TokenStream {
wrapped_route_impl(args, body, Some(Method::new_from_string("PATCH")))
}
fn wrapped_route_impl(
attr: TokenStream,
mut item: TokenStream,
method: Option<Method>,
) -> TokenStream {
match route_impl(attr, item.clone(), method) {
Ok(tokens) => tokens.into(),
Err(err) => {
let err: TokenStream = err.to_compile_error().into();
item.extend(err);
item
}
}
}
fn route_impl(
attr: TokenStream,
item: TokenStream,
method_from_macro: Option<Method>,
) -> syn::Result<TokenStream2> {
let route = syn::parse::<Route>(attr)?;
route_impl_with_route(route, item, method_from_macro)
}
fn route_impl_with_route(
route: Route,
item: TokenStream,
method_from_macro: Option<Method>,
) -> syn::Result<TokenStream2> {
// Parse the route and function
let mut function = syn::parse::<ItemFn>(item)?;
// Collect the middleware initializers
let middleware_layers = function
.attrs
.iter()
.filter(|attr| attr.path().is_ident("middleware"))
.map(|f| match &f.meta {
Meta::List(meta_list) => Ok({
let tokens = &meta_list.tokens;
quote! { .layer(#tokens) }
}),
_ => Err(Error::new(
f.span(),
"Expected middleware attribute to be a list, e.g. #[middleware(MyLayer::new())]",
)),
})
.collect::<Result<Vec<_>>>()?;
// don't re-emit the middleware attribute on the inner
function
.attrs
.retain(|attr| !attr.path().is_ident("middleware"));
// Attach `#[allow(unused_mut)]` to all original inputs to avoid warnings
let outer_inputs = function
.sig
.inputs
.iter()
.enumerate()
.map(|(i, arg)| match arg {
FnArg::Receiver(_receiver) => panic!("Self type is not supported"),
FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
Pat::Ident(_) => {
quote! { #[allow(unused_mut)] #pat_type }
}
_ => {
let ident = format_ident!("___Arg{}", i);
let ty = &pat_type.ty;
quote! { #[allow(unused_mut)] #ident: #ty }
}
},
})
.collect::<Punctuated<_, Token![,]>>();
// .collect::<Punctuated<_, Token![,]>>();
let route = CompiledRoute::from_route(route, &function, false, method_from_macro)?;
let query_params_struct = route.query_params_struct(false);
let method_ident = &route.method;
let body_json_args = route.remaining_pattypes_named(&function.sig.inputs);
let body_json_names = body_json_args
.iter()
.map(|(i, pat_type)| match &*pat_type.pat {
Pat::Ident(ref pat_ident) => pat_ident.ident.clone(),
_ => format_ident!("___Arg{}", i),
})
.collect::<Vec<_>>();
let body_json_types = body_json_args
.iter()
.map(|pat_type| &pat_type.1.ty)
.collect::<Vec<_>>();
let route_docs = route.to_doc_comments();
// Get the variables we need for code generation
let fn_on_server_name = &function.sig.ident;
let vis = &function.vis;
let (impl_generics, ty_generics, where_clause) = &function.sig.generics.split_for_impl();
let ty_generics = ty_generics.as_turbofish();
let fn_docs = function
.attrs
.iter()
.filter(|attr| attr.path().is_ident("doc"));
let __axum = quote! { dioxus_server::axum };
let output_type = match &function.sig.output {
syn::ReturnType::Default => parse_quote! { () },
syn::ReturnType::Type(_, ty) => (*ty).clone(),
};
let query_param_names = route
.query_params
.iter()
.filter(|c| !c.catch_all)
.map(|param| ¶m.binding);
let path_param_args = route.path_params.iter().map(|(_slash, param)| match param {
PathParam::Capture(_lit, _brace_1, ident, _ty, _brace_2) => {
Some(quote! { #ident = #ident, })
}
PathParam::WildCard(_lit, _brace_1, _star, ident, _ty, _brace_2) => {
Some(quote! { #ident = #ident, })
}
PathParam::Static(_lit) => None,
});
let out_ty = match output_type.as_ref() {
Type::Tuple(tuple) if tuple.elems.is_empty() => parse_quote! { () },
_ => output_type.clone(),
};
let mut function_on_server = function.clone();
function_on_server
.sig
.inputs
.extend(route.server_args.clone());
let server_names = route
.server_args
.iter()
.enumerate()
.map(|(i, pat_type)| match pat_type {
FnArg::Typed(_pat_type) => format_ident!("___sarg___{}", i),
FnArg::Receiver(_) => panic!("Self type is not supported"),
})
.collect::<Vec<_>>();
let server_types = route
.server_args
.iter()
.map(|pat_type| match pat_type {
FnArg::Receiver(_) => parse_quote! { () },
FnArg::Typed(pat_type) => (*pat_type.ty).clone(),
})
.collect::<Vec<_>>();
let body_struct_impl = {
let tys = body_json_types
.iter()
.enumerate()
.map(|(idx, _)| format_ident!("__Ty{}", idx));
let names = body_json_names.iter().enumerate().map(|(idx, name)| {
let ty_name = format_ident!("__Ty{}", idx);
quote! { #name: #ty_name }
});
quote! {
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(crate = "serde")]
struct ___Body_Serialize___< #(#tys,)* > {
#(#names,)*
}
}
};
// This unpacks the body struct into the individual variables that get scoped
let unpack_closure = {
let unpack_args = body_json_names.iter().map(|name| quote! { data.#name });
quote! {
|data| { ( #(#unpack_args,)* ) }
}
};
let as_axum_path = route.to_axum_path_string();
let query_endpoint = if let Some(full_url) = route.url_without_queries_for_format() {
quote! { format!(#full_url, #( #path_param_args)*) }
} else {
quote! { __ENDPOINT_PATH.to_string() }
};
let endpoint_path = {
let prefix = route
.prefix
.as_ref()
.cloned()
.unwrap_or_else(|| LitStr::new("", Span::call_site()));
let route_lit = if let Some(lit) = as_axum_path {
quote! { #lit }
} else {
let name =
route.route_lit.as_ref().cloned().unwrap_or_else(|| {
LitStr::new(&fn_on_server_name.to_string(), Span::call_site())
});
quote! {
concat!(
"/",
#name
)
}
};
let hash = match route.prefix.as_ref() {
// Implicit route lit, we need to hash the function signature to avoid collisions
Some(_) if route.route_lit.is_none() => {
// let enable_hash = option_env!("DISABLE_SERVER_FN_HASH").is_none();
let key_env_var = match option_env!("SERVER_FN_OVERRIDE_KEY") {
Some(_) => "SERVER_FN_OVERRIDE_KEY",
None => "CARGO_MANIFEST_DIR",
};
quote! {
dioxus_fullstack::xxhash_rust::const_xxh64::xxh64(
concat!(env!(#key_env_var), ":", module_path!()).as_bytes(),
0
)
}
}
// Explicit route lit, no need to hash
_ => quote! { "" },
};
quote! {
dioxus_fullstack::const_format::concatcp!(#prefix, #route_lit, #hash)
}
};
let extracted_idents = route.extracted_idents();
let query_tokens = if route.query_is_catchall() {
let query = route
.query_params
.iter()
.find(|param| param.catch_all)
.unwrap();
let input = &function.sig.inputs[query.arg_idx];
let name = match input {
FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
Pat::Ident(ref pat_ident) => pat_ident.ident.clone(),
_ => format_ident!("___Arg{}", query.arg_idx),
},
FnArg::Receiver(_receiver) => panic!(),
};
quote! {
#name
}
} else {
quote! {
__QueryParams__ { #(#query_param_names,)* }
}
};
let extracted_as_server_headers = route.extracted_as_server_headers(query_tokens.clone());
Ok(quote! {
#(#fn_docs)*
#route_docs
#[deny(
unexpected_cfgs,
reason = "
==========================================================================================
Using Dioxus Server Functions requires a `server` feature flag in your `Cargo.toml`.
Please add the following to your `Cargo.toml`:
```toml
[features]
server = [\"dioxus/server\"]
```
To enable better Rust-Analyzer support, you can make `server` a default feature:
```toml
[features]
default = [\"web\", \"server\"]
web = [\"dioxus/web\"]
server = [\"dioxus/server\"]
```
==========================================================================================
"
)]
#vis async fn #fn_on_server_name #impl_generics( #outer_inputs ) -> #out_ty #where_clause {
use dioxus_fullstack::serde as serde;
use dioxus_fullstack::{
// concrete types
ServerFnEncoder, ServerFnDecoder, FullstackContext,
// "magic" traits for encoding/decoding on the client
ExtractRequest, EncodeRequest, RequestDecodeResult, RequestDecodeErr,
// "magic" traits for encoding/decoding on the server
MakeAxumResponse, MakeAxumError,
};
#query_params_struct
#body_struct_impl
const __ENDPOINT_PATH: &str = #endpoint_path;
{
_ = dioxus_fullstack::assert_is_result::<#out_ty>();
let verify_token = (&&&&&&&&&&&&&&ServerFnEncoder::<___Body_Serialize___<#(#body_json_types,)*>, (#(#body_json_types,)*)>::new())
.verify_can_serialize();
dioxus_fullstack::assert_can_encode(verify_token);
let decode_token = (&&&&&ServerFnDecoder::<#out_ty>::new())
.verify_can_deserialize();
dioxus_fullstack::assert_can_decode(decode_token);
};
// On the client, we make the request to the server
// We want to support extremely flexible error types and return types, making this more complex than it should
#[allow(clippy::unused_unit)]
#[cfg(not(feature = "server"))]
{
let client = dioxus_fullstack::ClientRequest::new(
dioxus_fullstack::http::Method::#method_ident,
#query_endpoint,
&#query_tokens,
);
let response = (&&&&&&&&&&&&&&ServerFnEncoder::<___Body_Serialize___<#(#body_json_types,)*>, (#(#body_json_types,)*)>::new())
.fetch_client(client, ___Body_Serialize___ { #(#body_json_names,)* }, #unpack_closure)
.await;
let decoded = (&&&&&ServerFnDecoder::<#out_ty>::new())
.decode_client_response(response)
.await;
let result = (&&&&&ServerFnDecoder::<#out_ty>::new())
.decode_client_err(decoded)
.await;
return result;
}
// On the server, we expand the tokens and submit the function to inventory
#[cfg(feature = "server")] {
#function_on_server
#[allow(clippy::unused_unit)]
fn __inner__function__ #impl_generics(
___state: #__axum::extract::State<FullstackContext>,
___request: #__axum::extract::Request,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = #__axum::response::Response>>> #where_clause {
Box::pin(async move {
match (&&&&&&&&&&&&&&ServerFnEncoder::<___Body_Serialize___<#(#body_json_types,)*>, (#(#body_json_types,)*)>::new()).extract_axum(___state.0, ___request, #unpack_closure).await {
Ok(((#(#body_json_names,)* ), (#(#extracted_as_server_headers,)* #(#server_names,)*) )) => {
// Call the user function
let res = #fn_on_server_name #ty_generics(#(#extracted_idents,)* #(#body_json_names,)* #(#server_names,)*).await;
// Encode the response Into a `Result<T, E>`
let encoded = (&&&&&&ServerFnDecoder::<#out_ty>::new()).make_axum_response(res);
// And then encode `Result<T, E>` into `Response`
(&&&&&ServerFnDecoder::<#out_ty>::new()).make_axum_error(encoded)
},
Err(res) => res,
}
})
}
dioxus_server::inventory::submit! {
dioxus_server::ServerFunction::new(
dioxus_server::http::Method::#method_ident,
__ENDPOINT_PATH,
|| {
dioxus_server::ServerFunction::make_handler(dioxus_server::http::Method::#method_ident, __inner__function__ #ty_generics)
#(#middleware_layers)*
}
)
}
// Extract the server arguments from the context if needed.
let (#(#server_names,)*) = dioxus_fullstack::FullstackContext::extract::<(#(#server_types,)*), _>().await?;
// Call the function directly
return #fn_on_server_name #ty_generics(
#(#extracted_idents,)*
#(#body_json_names,)*
#(#server_names,)*
).await;
}
#[allow(unreachable_code)]
{
unreachable!()
}
}
})
}
struct CompiledRoute {
method: Method,
#[allow(clippy::type_complexity)]
path_params: Vec<(Slash, PathParam)>,
query_params: Vec<QueryParam>,
route_lit: Option<LitStr>,
prefix: Option<LitStr>,
oapi_options: Option<OapiOptions>,
server_args: Punctuated<FnArg, Comma>,
}
struct QueryParam {
arg_idx: usize,
name: String,
binding: Ident,
catch_all: bool,
ty: Box<Type>,
}
impl CompiledRoute {
fn to_axum_path_string(&self) -> Option<String> {
if self.prefix.is_some() {
return None;
}
let mut path = String::new();
for (_slash, param) in &self.path_params {
path.push('/');
match param {
PathParam::Capture(lit, _brace_1, _, _, _brace_2) => {
path.push('{');
path.push_str(&lit.value());
path.push('}');
}
PathParam::WildCard(lit, _brace_1, _, _, _, _brace_2) => {
path.push('{');
path.push('*');
path.push_str(&lit.value());
path.push('}');
}
PathParam::Static(lit) => path.push_str(&lit.value()),
}
}
Some(path)
}
/// Removes the arguments in `route` from `args`, and merges them in the output.
pub fn from_route(
mut route: Route,
function: &ItemFn,
with_aide: bool,
method_from_macro: Option<Method>,
) -> syn::Result<Self> {
if !with_aide && route.oapi_options.is_some() {
return Err(syn::Error::new(
Span::call_site(),
"Use `api_route` instead of `route` to use OpenAPI options",
));
} else if with_aide && route.oapi_options.is_none() {
route.oapi_options = Some(OapiOptions {
summary: None,
description: None,
id: None,
hidden: None,
tags: None,
security: None,
responses: None,
transform: None,
});
}
let sig = &function.sig;
let mut arg_map = sig
.inputs
.iter()
.enumerate()
.filter_map(|(i, item)| match item {
syn::FnArg::Receiver(_) => None,
syn::FnArg::Typed(pat_type) => Some((i, pat_type)),
})
.filter_map(|(i, pat_type)| match &*pat_type.pat {
syn::Pat::Ident(ident) => Some((ident.ident.clone(), (pat_type.ty.clone(), i))),
_ => None,
})
.collect::<HashMap<_, _>>();
for (_slash, path_param) in &mut route.path_params {
match path_param {
PathParam::Capture(_lit, _, ident, ty, _) => {
let (new_ident, new_ty) = arg_map.remove_entry(ident).ok_or_else(|| {
syn::Error::new(
ident.span(),
format!("path parameter `{}` not found in function arguments", ident),
)
})?;
*ident = new_ident;
*ty = new_ty.0;
}
PathParam::WildCard(_lit, _, _star, ident, ty, _) => {
let (new_ident, new_ty) = arg_map.remove_entry(ident).ok_or_else(|| {
syn::Error::new(
ident.span(),
format!("path parameter `{}` not found in function arguments", ident),
)
})?;
*ident = new_ident;
*ty = new_ty.0;
}
PathParam::Static(_lit) => {}
}
}
let mut query_params = Vec::new();
for param in route.query_params {
let (ident, ty) = arg_map.remove_entry(¶m.binding).ok_or_else(|| {
syn::Error::new(
param.binding.span(),
format!(
"query parameter `{}` not found in function arguments",
param.binding
),
)
})?;
query_params.push(QueryParam {
binding: ident,
name: param.name,
catch_all: param.catch_all,
ty: ty.0,
arg_idx: ty.1,
});
}
// Disallow multiple query params if one is a catch-all
if query_params.iter().any(|param| param.catch_all) && query_params.len() > 1 {
return Err(syn::Error::new(
Span::call_site(),
"Cannot have multiple query parameters when one is a catch-all",
));
}
if let Some(options) = route.oapi_options.as_mut() {
options.merge_with_fn(function)
}
let method = match (method_from_macro, route.method) {
(Some(method), None) => method,
(None, Some(method)) => method,
(Some(_), Some(_)) => {
return Err(syn::Error::new(
Span::call_site(),
"HTTP method specified both in macro and in attribute",
))
}
(None, None) => {
return Err(syn::Error::new(
Span::call_site(),
"HTTP method not specified in macro or in attribute",
))
}
};
Ok(Self {
method,
route_lit: route.route_lit,
path_params: route.path_params,
query_params,
oapi_options: route.oapi_options,
prefix: route.prefix,
server_args: route.server_args,
})
}
pub fn query_is_catchall(&self) -> bool {
self.query_params.iter().any(|param| param.catch_all)
}
pub fn extracted_as_server_headers(&self, query_tokens: TokenStream2) -> Vec<Pat> {
let mut out = vec![];
// Add the path extractor
out.push({
let path_iter = self
.path_params
.iter()
.filter_map(|(_slash, path_param)| path_param.capture());
let idents = path_iter.clone().map(|item| item.0);
parse_quote! {
dioxus_server::axum::extract::Path((#(#idents,)*))
}
});
out.push(parse_quote!(
dioxus_fullstack::payloads::Query(#query_tokens)
));
out
}
pub fn query_params_struct(&self, with_aide: bool) -> TokenStream2 {
let fields = self.query_params.iter().map(|item| {
let name = &item.name;
let binding = &item.binding;
let ty = &item.ty;
if item.catch_all {
quote! {}
} else if item.binding != item.name {
quote! {
#[serde(rename = #name)]
#binding: #ty,
}
} else {
quote! { #binding: #ty, }
}
});
let derive = match with_aide {
true => quote! {
#[derive(serde::Deserialize, serde::Serialize, ::schemars::JsonSchema)]
#[serde(crate = "serde")]
},
false => quote! {
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(crate = "serde")]
},
};
quote! {
#derive
struct __QueryParams__ {
#(#fields)*
}
}
}
pub fn extracted_idents(&self) -> Vec<Ident> {
let mut idents = Vec::new();
for (_slash, path_param) in &self.path_params {
if let Some((ident, _ty)) = path_param.capture() {
idents.push(ident.clone());
}
}
for param in &self.query_params {
idents.push(param.binding.clone());
}
idents
}
fn remaining_pattypes_named(&self, args: &Punctuated<FnArg, Comma>) -> Vec<(usize, PatType)> {
args.iter()
.enumerate()
.filter_map(|(i, item)| {
if let FnArg::Typed(pat_type) = item {
if let syn::Pat::Ident(pat_ident) = &*pat_type.pat {
if self.path_params.iter().any(|(_slash, path_param)| {
if let Some((path_ident, _ty)) = path_param.capture() {
path_ident == &pat_ident.ident
} else {
false
}
}) || self
.query_params
.iter()
.any(|query| query.binding == pat_ident.ident)
{
return None;
}
}
Some((i, pat_type.clone()))
} else {
unimplemented!("Self type is not supported")
}
})
.collect()
}
pub(crate) fn to_doc_comments(&self) -> TokenStream2 {
let mut doc = format!(
"# Handler information
- Method: `{}`
- Path: `{}`",
self.method.to_axum_method_name(),
self.route_lit
.as_ref()
.map(|lit| lit.value())
.unwrap_or_else(|| "<auto>".into()),
);
if let Some(options) = &self.oapi_options {
let summary = options
.summary
.as_ref()
.map(|(_, summary)| format!("\"{}\"", summary.value()))
.unwrap_or("None".to_string());
let description = options
.description
.as_ref()
.map(|(_, description)| format!("\"{}\"", description.value()))
.unwrap_or("None".to_string());
let id = options
.id
.as_ref()
.map(|(_, id)| format!("\"{}\"", id.value()))
.unwrap_or("None".to_string());
let hidden = options
.hidden
.as_ref()
.map(|(_, hidden)| hidden.value().to_string())
.unwrap_or("None".to_string());
let tags = options
.tags
.as_ref()
.map(|(_, tags)| tags.to_string())
.unwrap_or("[]".to_string());
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.