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/packages/signals/examples/split_subscriptions.rs
packages/signals/examples/split_subscriptions.rs
#![allow(non_snake_case)] use dioxus::prelude::*; use dioxus_signals::Signal; fn main() { dioxus::launch(app); } #[derive(Clone, Copy, Default)] struct ApplicationData { first_data: Signal<i32>, second_data: Signal<i32>, many_signals: Signal<Vec<Signal<i32>>>, } fn app() -> Element { use_context_provider(ApplicationData::default); rsx! { div { ReadsFirst {} } div { ReadsSecond {} } div { ReadsManySignals {} } } } #[component] fn ReadsFirst() -> Element { println!("running first"); let mut data = use_context::<ApplicationData>(); rsx! { button { onclick: move |_| { *data.first_data.write() += 1; }, "Increase" } button { onclick: move |_| { *data.first_data.write() -= 1; }, "Decrease" } button { onclick: move |_| { *data.first_data.write() = 0; }, "Reset" } "{data.first_data}" } } #[component] fn ReadsSecond() -> Element { println!("running second"); let mut data = use_context::<ApplicationData>(); rsx! { button { onclick: move |_| data.second_data += 1, "Increase" } button { onclick: move |_| data.second_data -= 1, "Decrease" } button { onclick: move |_| data.second_data.set(0), "Reset" } "{data.second_data}" } } #[component] fn ReadsManySignals() -> Element { println!("running many signals"); let mut data = use_context::<ApplicationData>(); rsx! { button { onclick: move |_| data.many_signals.write().push(Signal::new(0)), "Create" } button { onclick: move |_| { data.many_signals.write().pop(); }, "Destroy" } button { onclick: move |_| { if let Some(mut first) = data.many_signals.read().first().cloned() { first += 1; } }, "Increase First Item" } for signal in data.many_signals.iter() { Child { count: *signal } } } } #[component] fn Child(mut count: Signal<i32>) -> Element { println!("running child"); rsx! { div { "Child: {count}" button { onclick: move |_| count += 1, "Increase" } button { onclick: move |_| count -= 1, "Decrease" } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/examples/map_signal.rs
packages/signals/examples/map_signal.rs
#![allow(non_snake_case)] use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut vec = use_signal(|| vec![0]); rsx! { button { onclick: move |_| { let mut write = vec.write(); let len = write.len() as i32; write.push(len); }, "Create" } button { onclick: move |_| { vec.write().pop(); }, "Destroy" } for i in 0..vec.len() { Child { count: vec.map_mut(move |v| &v[i], move |v| &mut v[i]) } } } } #[component] fn Child(count: WriteSignal<i32>) -> Element { rsx! { div { "{count}" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/examples/send.rs
packages/signals/examples/send.rs
use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut signal = use_signal_sync(|| 0); use_hook(|| { std::thread::spawn(move || loop { std::thread::sleep(std::time::Duration::from_secs(1)); signal += 1; }); }); rsx! { button { onclick: move |_| signal += 1, "Increase" } "{signal}" } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/examples/send_store.rs
packages/signals/examples/send_store.rs
use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut store = use_hook(|| Store::new_maybe_sync(0u32)); rsx! { button { onclick: move |_| store += 1, "Increase" } "{store}" Child { store } } } #[component] fn Child(store: WriteStore<u32, SyncStorage>) -> Element { // A `WriteStore<T, SyncStorage>` can be sent to another thread! // Make sure to clean up your threads when the component unmounts. use_hook(|| { std::thread::spawn(move || loop { std::thread::sleep(std::time::Duration::from_secs(1)); store += 1; if store() >= 10 { break; } }); }); rsx! {} }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/examples/dependencies.rs
packages/signals/examples/dependencies.rs
use dioxus::prelude::*; fn main() { dioxus::launch(app); } fn app() -> Element { let mut signal = use_signal(|| 0); use_future(move || async move { loop { tokio::time::sleep(std::time::Duration::from_secs(1)).await; signal += 1; } }); rsx! { "Parent count: {signal}" Child { non_reactive_prop: signal() } } } #[component] fn Child(non_reactive_prop: i32) -> Element { let mut signal = use_signal(|| 0); // You can manually specify the dependencies with `use_reactive` for values that are not reactive like props let computed = use_memo(use_reactive!( |(non_reactive_prop,)| non_reactive_prop + signal() )); use_effect(use_reactive!(|(non_reactive_prop,)| println!( "{}", non_reactive_prop + signal() ))); let fut = use_resource(use_reactive!(|(non_reactive_prop,)| async move { tokio::time::sleep(std::time::Duration::from_secs(1)).await; non_reactive_prop + signal() })); rsx! { button { onclick: move |_| signal += 1, "Child count: {signal}" } "Sum: {computed}" "{fut():?}" } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/examples/selector.rs
packages/signals/examples/selector.rs
use dioxus::prelude::*; fn main() { dioxus::launch(app) } fn app() -> Element { let mut signal = use_signal(|| 0); let doubled = use_memo(move || signal * 2); rsx! { button { onclick: move |_| signal += 1, "Increase" } Child { signal: doubled } } } #[component] fn Child(signal: ReadSignal<usize>) -> Element { rsx! { "{signal}" } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/examples/context.rs
packages/signals/examples/context.rs
#![allow(non_snake_case)] use dioxus::prelude::*; fn main() { dioxus::launch(app) } // Because signal is never read in this component, this component will not rerun when the signal changes fn app() -> Element { use_context_provider(|| Signal::new(0)); rsx! { Child {} } } // This component does read from the signal, so when the signal changes it will rerun #[component] fn Child() -> Element { let signal: Signal<i32> = use_context(); rsx! { "{signal}" } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/examples/read_only_degrade.rs
packages/signals/examples/read_only_degrade.rs
//! Signals can degrade into a Read variant automatically //! This is done thanks to a conversion by the #[component] macro 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!" } Child { count, "hiiii" } } } #[component] fn Child(count: ReadSignal<i32>, children: Element) -> Element { rsx! { div { "Count: {count}" } {children} } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/errors.rs
packages/fullstack-core/src/errors.rs
//! Contains a hydration compatible error boundary context. use crate::serialize_context; use dioxus_core::{spawn_isomorphic, CapturedError, ErrorContext, ReactiveContext}; use futures_util::StreamExt; /// Initializes an error boundary context that is compatible with hydration. pub fn init_error_boundary() -> ErrorContext { let initial_error = serialize_context().create_entry::<Option<CapturedError>>(); let (rx_context, mut rx) = ReactiveContext::new(); let errors = ErrorContext::new(None); if let Ok(Some(err)) = initial_error.get() { errors.insert_error(err); } rx_context.run_in(|| { errors.error(); }); spawn_isomorphic({ let errors = errors.clone(); async move { if rx.next().await.is_some() { rx_context.run_in(|| { initial_error.insert(&errors.error(), std::panic::Location::caller()) }); } } }); errors }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/httperror.rs
packages/fullstack-core/src/httperror.rs
use axum_core::response::IntoResponse; use http::StatusCode; use std::fmt; /// An error type that wraps an HTTP status code and optional message. #[derive(Debug, Clone, PartialEq)] pub struct HttpError { pub status: StatusCode, pub message: Option<String>, } impl HttpError { pub fn new<M: Into<String>>(status: StatusCode, message: M) -> Self { HttpError { status, message: Some(message.into()), } } pub fn err<T>(status: StatusCode, message: impl Into<String>) -> Result<T, Self> { Err(HttpError::new(status, message)) } // --- 4xx Client Errors --- pub fn bad_request<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::BAD_REQUEST, message) } pub fn unauthorized<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::UNAUTHORIZED, message) } pub fn payment_required<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::PAYMENT_REQUIRED, message) } pub fn forbidden<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::FORBIDDEN, message) } pub fn not_found<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::NOT_FOUND, message) } pub fn method_not_allowed<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::METHOD_NOT_ALLOWED, message) } pub fn not_acceptable<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::NOT_ACCEPTABLE, message) } pub fn proxy_auth_required<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::PROXY_AUTHENTICATION_REQUIRED, message) } pub fn request_timeout<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::REQUEST_TIMEOUT, message) } pub fn conflict<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::CONFLICT, message) } pub fn gone<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::GONE, message) } pub fn length_required<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::LENGTH_REQUIRED, message) } pub fn precondition_failed<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::PRECONDITION_FAILED, message) } pub fn payload_too_large<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::PAYLOAD_TOO_LARGE, message) } pub fn uri_too_long<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::URI_TOO_LONG, message) } pub fn unsupported_media_type<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::UNSUPPORTED_MEDIA_TYPE, message) } pub fn im_a_teapot<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::IM_A_TEAPOT, message) } pub fn too_many_requests<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::TOO_MANY_REQUESTS, message) } // --- 5xx Server Errors --- pub fn internal_server_error<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::INTERNAL_SERVER_ERROR, message) } pub fn not_implemented<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::NOT_IMPLEMENTED, message) } pub fn bad_gateway<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::BAD_GATEWAY, message) } pub fn service_unavailable<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::SERVICE_UNAVAILABLE, message) } pub fn gateway_timeout<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::GATEWAY_TIMEOUT, message) } pub fn http_version_not_supported<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::HTTP_VERSION_NOT_SUPPORTED, message) } // --- 2xx/3xx (rare, but for completeness) --- pub fn ok<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::OK, message) } pub fn created<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::CREATED, message) } pub fn accepted<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::ACCEPTED, message) } pub fn moved_permanently<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::MOVED_PERMANENTLY, message) } pub fn found<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::FOUND, message) } pub fn see_other<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::SEE_OTHER, message) } pub fn not_modified<T>(message: impl Into<String>) -> Result<T, Self> { Self::err(StatusCode::NOT_MODIFIED, message) } } impl fmt::Display for HttpError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.message { Some(msg) => write!(f, "{}: {}", self.status, msg), None => write!(f, "{}", self.status), } } } impl std::error::Error for HttpError {} /// Trait to convert errors into HttpError with a given status code. pub trait OrHttpError<T, M>: Sized { fn or_http_error(self, status: StatusCode, message: impl Into<String>) -> Result<T, HttpError>; // --- Most common user-facing status codes --- fn or_bad_request(self, message: impl Into<String>) -> Result<T, HttpError> { self.or_http_error(StatusCode::BAD_REQUEST, message) } fn or_unauthorized(self, message: impl Into<String>) -> Result<T, HttpError> { self.or_http_error(StatusCode::UNAUTHORIZED, message) } fn or_forbidden(self, message: impl Into<String>) -> Result<T, HttpError> { self.or_http_error(StatusCode::FORBIDDEN, message) } fn or_not_found(self, message: impl Into<String>) -> Result<T, HttpError> { self.or_http_error(StatusCode::NOT_FOUND, message) } fn or_internal_server_error(self, message: impl Into<String>) -> Result<T, HttpError> { self.or_http_error(StatusCode::INTERNAL_SERVER_ERROR, message) } } impl<T, E> OrHttpError<T, ()> for Result<T, E> where E: std::error::Error + Send + Sync + 'static, { fn or_http_error(self, status: StatusCode, message: impl Into<String>) -> Result<T, HttpError> { self.map_err(|_| HttpError { status, message: Some(message.into()), }) } } impl<T> OrHttpError<T, ()> for Option<T> { fn or_http_error(self, status: StatusCode, message: impl Into<String>) -> Result<T, HttpError> { self.ok_or_else(|| HttpError { status, message: Some(message.into()), }) } } impl OrHttpError<(), ()> for bool { fn or_http_error( self, status: StatusCode, message: impl Into<String>, ) -> Result<(), HttpError> { if self { Ok(()) } else { Err(HttpError { status, message: Some(message.into()), }) } } } pub struct AnyhowMarker; impl<T> OrHttpError<T, AnyhowMarker> for Result<T, anyhow::Error> { fn or_http_error(self, status: StatusCode, message: impl Into<String>) -> Result<T, HttpError> { self.map_err(|_| HttpError { status, message: Some(message.into()), }) } } impl IntoResponse for HttpError { fn into_response(self) -> axum_core::response::Response { let body = match &self.message { Some(msg) => msg.clone(), None => self .status .canonical_reason() .unwrap_or("Unknown error") .to_string(), }; (self.status, body).into_response() } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/lib.rs
packages/fullstack-core/src/lib.rs
// #![warn(missing_docs)] #![doc = include_str!("../README.md")] pub mod document; pub mod history; mod errors; mod loader; mod server_cached; mod server_future; mod streaming; mod transport; pub use crate::errors::*; pub use crate::loader::*; pub use crate::server_cached::*; pub use crate::server_future::*; pub use crate::streaming::*; pub use crate::transport::*; /// Error types and utilities. #[macro_use] pub mod error; pub use error::*; pub mod httperror; pub use httperror::*;
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/server_cached.rs
packages/fullstack-core/src/server_cached.rs
use crate::{transport::SerializeContextEntry, Transportable}; use dioxus_core::use_hook; /// This allows you to send data from the server to the client *during hydration*. /// - When compiled as server, the closure is ran and the resulting data is serialized on the server and sent to the client. /// - When compiled as web client, the data is deserialized from the server if already available, otherwise runs on the client. Data is usually only available if this hook exists in a component during hydration. /// - When otherwise compiled, the closure is run directly with no serialization. /// /// The order this function is run on the client needs to be the same order initially run on the server. /// /// If Dioxus fullstack cannot find the data on the client, it will run the closure again to get the data. /// /// # Example /// ```rust /// use dioxus::prelude::*; /// /// fn app() -> Element { /// let state1 = use_server_cached(|| { /// 1234 /// }); /// /// unimplemented!() /// } /// ``` #[track_caller] pub fn use_server_cached<O, M>(server_fn: impl Fn() -> O) -> O where O: Transportable<M> + Clone, M: 'static, { let location = std::panic::Location::caller(); use_hook(|| server_cached(server_fn, location)) } pub(crate) fn server_cached<O, M>( value: impl FnOnce() -> O, #[allow(unused)] location: &'static std::panic::Location<'static>, ) -> O where O: Transportable<M> + Clone, M: 'static, { let serialize = crate::transport::serialize_context(); #[allow(unused)] let entry: SerializeContextEntry<O> = serialize.create_entry(); #[cfg(feature = "server")] { let data = value(); entry.insert(&data, location); data } #[cfg(all(not(feature = "server"), feature = "web"))] { match entry.get() { Ok(value) => value, Err(_) => value(), } } #[cfg(not(any(feature = "server", feature = "web")))] { value() } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/document.rs
packages/fullstack-core/src/document.rs
//! On the client, we use the [`FullstackWebDocument`] implementation to render the head for any elements that were not rendered on the server. use dioxus_document::*; fn head_element_written_on_server() -> bool { crate::transport::head_element_hydration_entry() .get() .ok() .unwrap_or_default() } /// A document provider for fullstack web clients #[derive(Clone)] pub struct FullstackWebDocument<D> { document: D, } impl<D> From<D> for FullstackWebDocument<D> { fn from(document: D) -> Self { Self { document } } } impl<D: Document> Document for FullstackWebDocument<D> { fn eval(&self, js: String) -> Eval { self.document.eval(js) } /// Set the title of the document fn set_title(&self, title: String) { self.document.set_title(title); } /// Create a new meta tag in the head fn create_meta(&self, props: MetaProps) { self.document.create_meta(props); } /// Create a new script tag in the head fn create_script(&self, props: ScriptProps) { self.document.create_script(props); } /// Create a new style tag in the head fn create_style(&self, props: StyleProps) { self.document.create_style(props); } /// Create a new link tag in the head fn create_link(&self, props: LinkProps) { self.document.create_link(props); } fn create_head_component(&self) -> bool { !head_element_written_on_server() } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/error.rs
packages/fullstack-core/src/error.rs
use axum_core::response::IntoResponse; use futures_util::TryStreamExt; use http::StatusCode; use serde::{Deserialize, Serialize}; use std::fmt::Debug; use crate::HttpError; /// A default result type for server functions, which can either be successful or contain an error. The [`ServerFnResult`] type /// is a convenient alias for a `Result` type that uses [`ServerFnError`] as the error type. /// /// # Example /// ```rust /// use dioxus::prelude::*; /// /// #[server] /// async fn parse_number(number: String) -> Result<f32> { /// let parsed_number: f32 = number.parse()?; /// Ok(parsed_number) /// } /// ``` pub type ServerFnResult<T = ()> = std::result::Result<T, ServerFnError>; /// The error type for the server function system. This enum encompasses all possible errors that can occur /// during the registration, invocation, and processing of server functions. #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum ServerFnError { /// Occurs when there is an error while actually running the function on the server. /// /// The `details` field can optionally contain additional structured information about the error. /// When passing typed errors from the server to the client, the `details` field contains the serialized /// representation of the error. #[error("error running server function: {message} (details: {details:#?})")] ServerError { /// A human-readable message describing the error. message: String, /// HTTP status code associated with the error. code: u16, #[serde(skip_serializing_if = "Option::is_none")] details: Option<serde_json::Value>, }, /// Occurs on the client if there is a network error while trying to run function on server. #[error("error reaching server to call server function: {0} ")] Request(RequestError), /// Occurs on the client if there is an error while trying to read the response body as a stream. #[error("error reading response body stream: {0}")] StreamError(String), /// Error while trying to register the server function (only occurs in case of poisoned RwLock). #[error("error while trying to register the server function: {0}")] Registration(String), /// Occurs on the client if trying to use an unsupported `HTTP` method when building a request. #[error("error trying to build `HTTP` method request: {0}")] UnsupportedRequestMethod(String), /// Occurs when there is an error while actually running the middleware on the server. #[error("error running middleware: {0}")] MiddlewareError(String), /// Occurs on the client if there is an error deserializing the server's response. #[error("error deserializing server function results: {0}")] Deserialization(String), /// Occurs on the client if there is an error serializing the server function arguments. #[error("error serializing server function arguments: {0}")] Serialization(String), /// Occurs on the server if there is an error deserializing one of the arguments that's been sent. #[error("error deserializing server function arguments: {0}")] Args(String), /// Occurs on the server if there's a missing argument. #[error("missing argument {0}")] MissingArg(String), /// Occurs on the server if there is an error creating an HTTP response. #[error("error creating response {0}")] Response(String), } impl ServerFnError { /// Create a new server error (status code 500) with a message. pub fn new(f: impl ToString) -> Self { ServerFnError::ServerError { message: f.to_string(), details: None, code: 500, } } /// Create a new server error (status code 500) with a message and details. pub async fn from_axum_response(resp: axum_core::response::Response) -> Self { let status = resp.status(); let message = resp .into_body() .into_data_stream() .try_fold(Vec::new(), |mut acc, chunk| async move { acc.extend_from_slice(&chunk); Ok(acc) }) .await .ok() .and_then(|bytes| String::from_utf8(bytes).ok()) .unwrap_or_else(|| status.canonical_reason().unwrap_or("").to_string()); ServerFnError::ServerError { message, code: status.as_u16(), details: None, } } } impl From<anyhow::Error> for ServerFnError { fn from(value: anyhow::Error) -> Self { ServerFnError::ServerError { message: value.to_string(), details: None, code: 500, } } } impl From<serde_json::Error> for ServerFnError { fn from(value: serde_json::Error) -> Self { ServerFnError::Deserialization(value.to_string()) } } impl From<ServerFnError> for http::StatusCode { fn from(value: ServerFnError) -> Self { match value { ServerFnError::ServerError { code, .. } => { http::StatusCode::from_u16(code).unwrap_or(http::StatusCode::INTERNAL_SERVER_ERROR) } ServerFnError::Request(err) => match err { RequestError::Status(_, code) => http::StatusCode::from_u16(code) .unwrap_or(http::StatusCode::INTERNAL_SERVER_ERROR), _ => http::StatusCode::INTERNAL_SERVER_ERROR, }, ServerFnError::StreamError(_) | ServerFnError::Registration(_) | ServerFnError::UnsupportedRequestMethod(_) | ServerFnError::MiddlewareError(_) | ServerFnError::Deserialization(_) | ServerFnError::Serialization(_) | ServerFnError::Args(_) | ServerFnError::MissingArg(_) | ServerFnError::Response(_) => http::StatusCode::INTERNAL_SERVER_ERROR, } } } impl From<RequestError> for ServerFnError { fn from(value: RequestError) -> Self { ServerFnError::Request(value) } } impl From<ServerFnError> for HttpError { fn from(value: ServerFnError) -> Self { let status = StatusCode::from_u16(match &value { ServerFnError::ServerError { code, .. } => *code, _ => 500, }) .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); HttpError { status, message: Some(value.to_string()), } } } impl From<HttpError> for ServerFnError { fn from(value: HttpError) -> Self { ServerFnError::ServerError { message: value.message.unwrap_or_else(|| { value .status .canonical_reason() .unwrap_or("Unknown error") .to_string() }), code: value.status.as_u16(), details: None, } } } impl IntoResponse for ServerFnError { fn into_response(self) -> axum_core::response::Response { match self { Self::ServerError { message, code, details, } => { let status = StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); let body = if let Some(details) = details { serde_json::json!({ "error": message, "details": details, }) } else { serde_json::json!({ "error": message, }) }; let body = axum_core::body::Body::from( serde_json::to_string(&body) .unwrap_or_else(|_| "{\"error\":\"Internal Server Error\"}".to_string()), ); axum_core::response::Response::builder() .status(status) .header("Content-Type", "application/json") .body(body) .unwrap_or_else(|_| { axum_core::response::Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .body(axum_core::body::Body::from( "{\"error\":\"Internal Server Error\"}", )) .unwrap() }) } _ => { let status: StatusCode = self.clone().into(); let body = axum_core::body::Body::from( serde_json::json!({ "error": self.to_string(), }) .to_string(), ); axum_core::response::Response::builder() .status(status) .header("Content-Type", "application/json") .body(body) .unwrap_or_else(|_| { axum_core::response::Response::builder() .status(StatusCode::INTERNAL_SERVER_ERROR) .body(axum_core::body::Body::from( "{\"error\":\"Internal Server Error\"}", )) .unwrap() }) } } } } /// An error type representing issues that can occur while making requests. /// /// This is made to paper over the reqwest::Error type which we don't want to export here and /// is limited in many ways. #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum RequestError { /// An error occurred when building the request. #[error("error building request: {0}")] Builder(String), /// An error occurred when serializing the request body. #[error("error serializing request body: {0}")] Serialization(String), /// An error occurred when following a redirect. #[error("error following redirect: {0}")] Redirect(String), /// An error occurred when receiving a non-2xx status code. #[error("error receiving status code: {0} ({1})")] Status(String, u16), /// An error occurred when a request times out. #[error("error timing out: {0}")] Timeout(String), /// An error occurred when sending a request. #[error("error sending request: {0}")] Request(String), /// An error occurred when upgrading a connection. #[error("error upgrading connection: {0}")] Connect(String), /// An error occurred when there is a request or response body error. #[error("request or response body error: {0}")] Body(String), /// An error occurred when decoding the response body. #[error("error decoding response body: {0}")] Decode(String), } impl RequestError { pub fn status(&self) -> Option<StatusCode> { match self { RequestError::Status(_, code) => Some(StatusCode::from_u16(*code).ok()?), _ => None, } } pub fn status_code(&self) -> Option<u16> { match self { RequestError::Status(_, code) => Some(*code), _ => None, } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/history.rs
packages/fullstack-core/src/history.rs
//! A history provider for fullstack apps that is compatible with hydration. use std::{cell::RefCell, rc::Rc}; use crate::transport::{is_hydrating, SerializeContextEntry}; use dioxus_core::{provide_context, queue_effect, schedule_update, try_consume_context}; use dioxus_history::{history, provide_history_context, History}; // If we are currently in a scope and this is the first run then queue a rerender // for after hydration fn match_hydration<O>( during_hydration: impl FnOnce() -> O, after_hydration: impl FnOnce() -> O, ) -> O { if is_hydrating() { let update = schedule_update(); queue_effect(move || update()); during_hydration() } else { after_hydration() } } #[derive(Debug, Clone, PartialEq)] pub(crate) struct ResolvedRouteContext { route: String, } pub(crate) fn finalize_route() { // This may run in tests without the full hydration context set up, if it does, then just // return without modifying the context let Some(entry) = try_consume_context::<RouteEntry>() else { return; }; let Some(entry) = entry.entry.borrow_mut().take() else { // If it was already taken, then just return. This can happen if commit_initial_chunk is called twice return; }; if cfg!(feature = "server") { let history = history(); let route = history.current_route(); entry.insert(&route, std::panic::Location::caller()); provide_context(ResolvedRouteContext { route }); } else if cfg!(feature = "web") { let route = entry .get() .expect("Failed to get initial route from hydration context"); provide_context(ResolvedRouteContext { route }); } } /// Provide the fullstack history context. This interacts with the hydration context so it must /// be called in the same order on the client and server after the hydration context is created pub fn provide_fullstack_history_context<H: History + 'static>(history: H) { let entry = crate::transport::serialize_context().create_entry(); provide_context(RouteEntry { entry: Rc::new(RefCell::new(Some(entry.clone()))), }); provide_history_context(Rc::new(FullstackHistory::new(history))); } #[derive(Clone)] struct RouteEntry { entry: Rc<RefCell<Option<SerializeContextEntry<String>>>>, } /// A history provider for fullstack apps that is compatible with hydration. #[derive(Clone)] struct FullstackHistory<H> { history: H, } impl<H> FullstackHistory<H> { /// Create a new `FullstackHistory` with the given history. pub fn new(history: H) -> Self { Self { history } } /// Get the initial route of the history. fn initial_route(&self) -> String where H: History, { // If the route hydration entry is set, use that instead of the histories current route // for better hydration behavior. The client may be rendering from a ssg route that was // rendered at a different url if let Some(entry) = try_consume_context::<RouteEntry>() { let entry = entry.entry.borrow(); if let Some(entry) = &*entry { if let Ok(initial_route) = entry.get() { return initial_route; } } } self.history.current_route() } } impl<H: History> History for FullstackHistory<H> { fn current_prefix(&self) -> Option<String> { self.history.current_prefix() } fn can_go_back(&self) -> bool { match_hydration(|| false, || self.history.can_go_back()) } fn can_go_forward(&self) -> bool { match_hydration(|| false, || self.history.can_go_forward()) } fn external(&self, url: String) -> bool { self.history.external(url) } fn updater(&self, callback: std::sync::Arc<dyn Fn() + Send + Sync>) { self.history.updater(callback) } fn include_prevent_default(&self) -> bool { self.history.include_prevent_default() } fn current_route(&self) -> String { match_hydration(|| self.initial_route(), || self.history.current_route()) } fn go_back(&self) { self.history.go_back(); } fn go_forward(&self) { self.history.go_forward(); } fn push(&self, route: String) { self.history.push(route); } fn replace(&self, path: String) { self.history.replace(path); } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/server_future.rs
packages/fullstack-core/src/server_future.rs
use crate::Transportable; use dioxus_core::{suspend, use_hook, RenderError}; use dioxus_hooks::*; use dioxus_signals::ReadableExt; use std::future::Future; /// Runs a future with a manual list of dependencies and returns a resource with the result if the future is finished or a suspended error if it is still running. /// /// /// On the server, this will wait until the future is resolved before continuing to render. When the future is resolved, the result will be serialized into the page and hydrated on the client without rerunning the future. /// /// /// <div class="warning"> /// /// Unlike [`use_resource`] dependencies are only tracked inside the function that spawns the async block, not the async block itself. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// // ❌ The future inside of use_server_future is not reactive /// let id = use_signal(|| 0); /// use_server_future(move || { /// async move { /// // But the future is not reactive which means that the future will not subscribe to any reads here /// println!("{id}"); /// } /// }); /// // ✅ The closure that creates the future for use_server_future is reactive /// let id = use_signal(|| 0); /// use_server_future(move || { /// // The closure itself is reactive which means the future will subscribe to any signals you read here /// let cloned_id = id(); /// async move { /// // But the future is not reactive which means that the future will not subscribe to any reads here /// println!("{cloned_id}"); /// } /// }); /// ``` /// /// </div> /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # async fn fetch_article(id: u32) -> String { unimplemented!() } /// use dioxus::prelude::*; /// /// fn App() -> Element { /// let mut article_id = use_signal(|| 0); /// // `use_server_future` will spawn a task that runs on the server and serializes the result to send to the client. /// // The future will rerun any time the /// // Since we bubble up the suspense with `?`, the server will wait for the future to resolve before rendering /// let article = use_server_future(move || fetch_article(article_id()))?; /// /// rsx! { /// "{article().unwrap()}" /// } /// } /// ``` #[must_use = "Consider using `cx.spawn` to run a future without reading its value"] #[track_caller] pub fn use_server_future<T, F, M>( mut future: impl FnMut() -> F + 'static, ) -> Result<Resource<T>, RenderError> where F: Future<Output = T> + 'static, T: Transportable<M>, M: 'static, { let serialize_context = use_hook(crate::transport::serialize_context); // We always create a storage entry, even if the data isn't ready yet to make it possible to deserialize pending server futures on the client #[allow(unused)] let storage_entry: crate::transport::SerializeContextEntry<T> = use_hook(|| serialize_context.create_entry()); #[cfg(feature = "server")] let caller = std::panic::Location::caller(); // If this is the first run and we are on the web client, the data might be cached #[cfg(feature = "web")] let initial_web_result = use_hook(|| std::rc::Rc::new(std::cell::RefCell::new(Some(storage_entry.get())))); let resource = use_resource(move || { #[cfg(feature = "server")] let storage_entry = storage_entry.clone(); let user_fut = future(); #[cfg(feature = "web")] let initial_web_result = initial_web_result.clone(); #[allow(clippy::let_and_return)] async move { // If this is the first run and we are on the web client, the data might be cached #[cfg(feature = "web")] match initial_web_result.take() { // The data was deserialized successfully from the server Some(Ok(o)) => return o, // The data is still pending from the server. Don't try to resolve it on the client Some(Err(crate::transport::TakeDataError::DataPending)) => { std::future::pending::<()>().await } // The data was not available on the server, rerun the future Some(Err(_)) => {} // This isn't the first run, so we don't need do anything None => {} } // Otherwise just run the future itself let out = user_fut.await; // If this is the first run and we are on the server, cache the data in the slot we reserved for it #[cfg(feature = "server")] storage_entry.insert(&out, caller); out } }); // On the first run, force this task to be polled right away in case its value is ready use_hook(|| { let _ = resource.task().poll_now(); }); // Suspend if the value isn't ready if resource.state().cloned() == UseResourceState::Pending { let task = resource.task(); if !task.paused() { return Err(suspend(task).unwrap_err()); } } Ok(resource) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/loader.rs
packages/fullstack-core/src/loader.rs
use dioxus_core::{use_hook, IntoAttributeValue, IntoDynNode, Subscribers}; use dioxus_core::{CapturedError, RenderError, Result, SuspendedFuture}; use dioxus_hooks::{use_resource, use_signal, Resource}; use dioxus_signals::{ read_impls, ReadSignal, Readable, ReadableBoxExt, ReadableExt, ReadableRef, Signal, Writable, WritableExt, WriteLock, }; use generational_box::{BorrowResult, UnsyncStorage}; use serde::{de::DeserializeOwned, Serialize}; use std::ops::Deref; use std::{cmp::PartialEq, future::Future}; /// A hook to create a resource that loads data asynchronously. /// /// This hook takes a closure that returns a future. This future will be executed on both the client /// and the server. The loader will return `Loading` until the future resolves, at which point it will /// return a `Loader<T>`. If the future fails, it will return `Loading::Failed`. /// /// After the loader has successfully loaded once, it will never suspend the component again, but will /// instead re-load the value in the background whenever any of its dependencies change. /// /// If an error occurs while re-loading, `use_loader` will once again emit a `Loading::Failed` value. /// The `use_loader` hook will never return a suspended state after the initial load. /// /// # On the server /// /// On the server, this hook will block the rendering of the component (and therefore, the page) until /// the future resolves. Any server futures called by `use_loader` will receive the same request context /// as the component that called `use_loader`. #[allow(clippy::result_large_err)] #[track_caller] pub fn use_loader<F, T, E>(mut future: impl FnMut() -> F + 'static) -> Result<Loader<T>, Loading> where F: Future<Output = Result<T, E>> + 'static, T: 'static + PartialEq + Serialize + DeserializeOwned, E: Into<CapturedError> + 'static, { let serialize_context = use_hook(crate::transport::serialize_context); // We always create a storage entry, even if the data isn't ready yet to make it possible to deserialize pending server futures on the client #[allow(unused)] let storage_entry: crate::transport::SerializeContextEntry<Result<T, CapturedError>> = use_hook(|| serialize_context.create_entry()); #[cfg(feature = "server")] let caller = std::panic::Location::caller(); // If this is the first run and we are on the web client, the data might be cached #[cfg(feature = "web")] let initial_web_result = use_hook(|| std::rc::Rc::new(std::cell::RefCell::new(Some(storage_entry.get())))); let mut error = use_signal(|| None as Option<CapturedError>); let mut value = use_signal(|| None as Option<T>); let mut loader_state = use_signal(|| LoaderState::Pending); let resource = use_resource(move || { #[cfg(feature = "server")] let storage_entry = storage_entry.clone(); let user_fut = future(); #[cfg(feature = "web")] let initial_web_result = initial_web_result.clone(); #[allow(clippy::let_and_return)] async move { // If this is the first run and we are on the web client, the data might be cached #[cfg(feature = "web")] match initial_web_result.take() { // The data was deserialized successfully from the server Some(Ok(o)) => { match o { Ok(v) => { value.set(Some(v)); loader_state.set(LoaderState::Ready); } Err(e) => { error.set(Some(e)); loader_state.set(LoaderState::Failed); } }; return; } // The data is still pending from the server. Don't try to resolve it on the client Some(Err(crate::transport::TakeDataError::DataPending)) => { std::future::pending::<()>().await } // The data was not available on the server, rerun the future Some(Err(_)) => {} // This isn't the first run, so we don't need do anything None => {} } // Otherwise just run the future itself let out = user_fut.await; // Remap the error to the captured error type so it's cheap to clone and pass out, just // slightly more cumbersome to access the inner error. let out = out.map_err(|e| { let anyhow_err: CapturedError = e.into(); anyhow_err }); // If this is the first run and we are on the server, cache the data in the slot we reserved for it #[cfg(feature = "server")] storage_entry.insert(&out, caller); match out { Ok(v) => { value.set(Some(v)); loader_state.set(LoaderState::Ready); } Err(e) => { error.set(Some(e)); loader_state.set(LoaderState::Failed); } }; } }); // On the first run, force this task to be polled right away in case its value is ready use_hook(|| { let _ = resource.task().poll_now(); }); let read_value = use_hook(|| value.map(|f| f.as_ref().unwrap()).boxed()); let handle = LoaderHandle { resource, error, state: loader_state, _marker: std::marker::PhantomData, }; match &*loader_state.read_unchecked() { LoaderState::Pending => Err(Loading::Pending(handle)), LoaderState::Failed => Err(Loading::Failed(handle)), LoaderState::Ready => Ok(Loader { real_value: value, read_value, error, state: loader_state, handle, }), } } /// A Loader is a signal that represents a value that is loaded asynchronously. /// /// Once a `Loader<T>` has been successfully created from `use_loader`, it can be use like a normal signal of type `T`. /// /// When the loader is re-reloading its values, it will no longer suspend its component, making it /// very useful for server-side-rendering. pub struct Loader<T: 'static> { /// This is a signal that unwraps the inner value. We can't give it out unless we know the inner value is Some(T)! read_value: ReadSignal<T>, /// This is the actual signal. We let the user set this value if they want to, but we can't let them set it to `None`. real_value: Signal<Option<T>>, error: Signal<Option<CapturedError>>, state: Signal<LoaderState>, handle: LoaderHandle, } impl<T: 'static> Loader<T> { /// Get the error that occurred during loading, if any. /// /// After initial load, this will return `None` until the next reload fails. pub fn error(&self) -> Option<CapturedError> { self.error.read().as_ref().cloned() } /// Restart the loading task. /// /// After initial load, this won't suspend the component, but will reload in the background. pub fn restart(&mut self) { self.handle.restart(); } /// Check if the loader has failed. pub fn is_error(&self) -> bool { self.error.read().is_some() && matches!(*self.state.read(), LoaderState::Failed) } /// Cancel the current loading task. pub fn cancel(&mut self) { self.handle.resource.cancel(); } pub fn loading(&self) -> bool { !self.handle.resource.finished() } } impl<T: 'static> Writable for Loader<T> { type WriteMetadata = <Signal<Option<T>> as Writable>::WriteMetadata; fn try_write_unchecked( &self, ) -> std::result::Result< dioxus_signals::WritableRef<'static, Self>, generational_box::BorrowMutError, > where Self::Target: 'static, { let writer = self.real_value.try_write_unchecked()?; Ok(WriteLock::map(writer, |f: &mut Option<T>| { f.as_mut() .expect("Loader value should be set if the `Loader<T>` exists") })) } } impl<T> Readable for Loader<T> { type Target = T; type Storage = UnsyncStorage; #[track_caller] fn try_read_unchecked( &self, ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static, { Ok(self.read_value.read_unchecked()) } /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.** /// /// If the signal has been dropped, this will panic. #[track_caller] fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>> where T: 'static, { Ok(self.read_value.peek_unchecked()) } fn subscribers(&self) -> Subscribers where T: 'static, { self.read_value.subscribers() } } impl<T> IntoAttributeValue for Loader<T> where T: Clone + IntoAttributeValue + PartialEq + 'static, { fn into_value(self) -> dioxus_core::AttributeValue { self.with(|f| f.clone().into_value()) } } impl<T> IntoDynNode for Loader<T> where T: Clone + IntoDynNode + PartialEq + 'static, { fn into_dyn_node(self) -> dioxus_core::DynamicNode { let t: T = self(); t.into_dyn_node() } } impl<T: 'static> PartialEq for Loader<T> { fn eq(&self, other: &Self) -> bool { self.read_value == other.read_value } } impl<T: Clone> Deref for Loader<T> where T: PartialEq + 'static, { type Target = dyn Fn() -> T; fn deref(&self) -> &Self::Target { unsafe { ReadableExt::deref_impl(self) } } } read_impls!(Loader<T> where T: PartialEq); impl<T> Clone for Loader<T> { fn clone(&self) -> Self { *self } } impl<T> Copy for Loader<T> {} #[derive(Clone, Copy, PartialEq, Hash, Eq, Debug)] pub enum LoaderState { /// The loader's future is still running Pending, /// The loader's future has completed successfully Ready, /// The loader's future has failed and now the loader is in an error state. Failed, } #[derive(PartialEq)] pub struct LoaderHandle<M = ()> { resource: Resource<()>, error: Signal<Option<CapturedError>>, state: Signal<LoaderState>, _marker: std::marker::PhantomData<M>, } impl LoaderHandle { /// Restart the loading task. pub fn restart(&mut self) { self.resource.restart(); } /// Get the current state of the loader. pub fn state(&self) -> LoaderState { *self.state.read() } pub fn error(&self) -> Option<CapturedError> { self.error.read().as_ref().cloned() } } impl Clone for LoaderHandle { fn clone(&self) -> Self { *self } } impl Copy for LoaderHandle {} #[derive(PartialEq)] pub enum Loading { /// The loader is still pending and the component should suspend. Pending(LoaderHandle), /// The loader has failed and an error will be returned up the tree. Failed(LoaderHandle), } impl std::fmt::Debug for Loading { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Loading::Pending(_) => write!(f, "Loading::Pending"), Loading::Failed(_) => write!(f, "Loading::Failed"), } } } impl std::fmt::Display for Loading { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Loading::Pending(_) => write!(f, "Loading is still pending"), Loading::Failed(_) => write!(f, "Loading has failed"), } } } /// Convert a Loading into a RenderError for use with the `?` operator in components impl From<Loading> for RenderError { fn from(val: Loading) -> Self { match val { Loading::Pending(t) => RenderError::Suspended(SuspendedFuture::new(t.resource.task())), Loading::Failed(err) => RenderError::Error( err.error .cloned() .expect("LoaderHandle in Failed state should always have an error"), ), } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/transport.rs
packages/fullstack-core/src/transport.rs
#![warn(missing_docs)] #![doc = include_str!("../README.md")] use base64::Engine; use dioxus_core::CapturedError; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use std::{cell::RefCell, io::Cursor, rc::Rc}; #[cfg(feature = "web")] thread_local! { static CONTEXT: RefCell<Option<HydrationContext>> = const { RefCell::new(None) }; } /// Data shared between the frontend and the backend for hydration /// of server functions. #[derive(Default, Clone)] pub struct HydrationContext { #[cfg(feature = "web")] /// Is resolving suspense done on the client suspense_finished: bool, data: Rc<RefCell<HTMLData>>, } impl HydrationContext { /// Create a new serialize context from the serialized data pub fn from_serialized( data: &[u8], debug_types: Option<Vec<String>>, debug_locations: Option<Vec<String>>, ) -> Self { Self { #[cfg(feature = "web")] suspense_finished: false, data: Rc::new(RefCell::new(HTMLData::from_serialized( data, debug_types, debug_locations, ))), } } /// Serialize the data in the context to be sent to the client pub fn serialized(&self) -> SerializedHydrationData { self.data.borrow().serialized() } /// Create a new entry in the data that will be sent to the client without inserting any data. Returns an id that can be used to insert data into the entry once it is ready. pub fn create_entry<T>(&self) -> SerializeContextEntry<T> { let entry_index = self.data.borrow_mut().create_entry(); SerializeContextEntry { index: entry_index, context: self.clone(), phantom: std::marker::PhantomData, } } /// Get the entry for the error in the suspense boundary pub fn error_entry(&self) -> SerializeContextEntry<Option<CapturedError>> { // The first entry is reserved for the error let entry_index = self.data.borrow_mut().create_entry_with_id(0); SerializeContextEntry { index: entry_index, context: self.clone(), phantom: std::marker::PhantomData, } } /// Extend this data with the data from another [`HydrationContext`] pub fn extend(&self, other: &Self) { self.data.borrow_mut().extend(&other.data.borrow()); } #[cfg(feature = "web")] /// Run a closure inside of this context pub fn in_context<T>(&self, f: impl FnOnce() -> T) -> T { CONTEXT.with(|context| { let old = context.borrow().clone(); *context.borrow_mut() = Some(self.clone()); let result = f(); *context.borrow_mut() = old; result }) } pub(crate) fn insert<T: Transportable<M>, M: 'static>( &self, id: usize, value: &T, location: &'static std::panic::Location<'static>, ) { self.data.borrow_mut().insert(id, value, location); } pub(crate) fn get<T: Transportable<M>, M: 'static>( &self, id: usize, ) -> Result<T, TakeDataError> { // If suspense is finished on the client, we can assume that the data is available #[cfg(feature = "web")] if self.suspense_finished { return Err(TakeDataError::DataNotAvailable); } self.data.borrow().get(id) } } /// An entry into the serialized context. The order entries are created in must be consistent /// between the server and the client. pub struct SerializeContextEntry<T> { /// The index this context will be inserted into inside the serialize context index: usize, /// The context this entry is associated with context: HydrationContext, phantom: std::marker::PhantomData<T>, } impl<T> Clone for SerializeContextEntry<T> { fn clone(&self) -> Self { Self { index: self.index, context: self.context.clone(), phantom: std::marker::PhantomData, } } } impl<T> SerializeContextEntry<T> { /// Insert data into an entry that was created with [`HydrationContext::create_entry`] pub fn insert<M: 'static>(self, value: &T, location: &'static std::panic::Location<'static>) where T: Transportable<M>, { self.context.insert(self.index, value, location); } /// Grab the data from the serialize context pub fn get<M: 'static>(&self) -> Result<T, TakeDataError> where T: Transportable<M>, { self.context.get(self.index) } } /// Check if the client is currently rendering a component for hydration. Always returns true on the server. pub fn is_hydrating() -> bool { #[cfg(feature = "web")] { // On the client, we can check if the context is set CONTEXT.with(|context| context.borrow().is_some()) } #[cfg(not(feature = "web"))] { true } } /// Get or insert the current serialize context. On the client, the hydration context this returns /// will always return `TakeDataError::DataNotAvailable` if hydration of the current chunk is finished. pub fn serialize_context() -> HydrationContext { #[cfg(feature = "web")] // On the client, the hydration logic provides the context in a global if let Some(current_context) = CONTEXT.with(|context| context.borrow().clone()) { current_context } else { // If the context is not set, then suspense is not active HydrationContext { suspense_finished: true, ..Default::default() } } #[cfg(not(feature = "web"))] { // On the server each scope creates the context lazily dioxus_core::has_context() .unwrap_or_else(|| dioxus_core::provide_context(HydrationContext::default())) } } pub(crate) struct HTMLData { /// The position of the cursor in the data. This is only used on the client pub(crate) cursor: usize, /// The data required for hydration pub data: Vec<Option<Vec<u8>>>, /// The types of each serialized data /// /// NOTE: we don't store this in the main data vec because we don't want to include it in /// release mode and we can't assume both the client and server are built with debug assertions /// matching #[cfg(debug_assertions)] pub debug_types: Vec<Option<String>>, /// The locations of each serialized data #[cfg(debug_assertions)] pub debug_locations: Vec<Option<String>>, } impl Default for HTMLData { fn default() -> Self { Self { cursor: 1, data: Vec::new(), #[cfg(debug_assertions)] debug_types: Vec::new(), #[cfg(debug_assertions)] debug_locations: Vec::new(), } } } impl HTMLData { #[allow(unused)] fn from_serialized( data: &[u8], debug_types: Option<Vec<String>>, debug_locations: Option<Vec<String>>, ) -> Self { let data = ciborium::from_reader(Cursor::new(data)).unwrap(); Self { cursor: 1, data, #[cfg(debug_assertions)] debug_types: debug_types .unwrap_or_default() .into_iter() .map(Some) .collect(), #[cfg(debug_assertions)] debug_locations: debug_locations .unwrap_or_default() .into_iter() .map(Some) .collect(), } } /// Create a new entry in the data that will be sent to the client without inserting any data. Returns an id that can be used to insert data into the entry once it is ready. fn create_entry(&mut self) -> usize { let id = self.cursor; self.cursor += 1; self.create_entry_with_id(id) } fn create_entry_with_id(&mut self, id: usize) -> usize { while id + 1 > self.data.len() { self.data.push(None); #[cfg(debug_assertions)] { self.debug_types.push(None); self.debug_locations.push(None); } } id } /// Insert data into an entry that was created with [`Self::create_entry`] fn insert<T: Transportable<M>, M: 'static>( &mut self, id: usize, value: &T, #[allow(unused)] location: &'static std::panic::Location<'static>, ) { let serialized = value.transport_to_bytes(); self.data[id] = Some(serialized); #[cfg(debug_assertions)] { self.debug_types[id] = Some(std::any::type_name::<T>().to_string()); self.debug_locations[id] = Some(location.to_string()); } } /// Get the data from the serialize context fn get<T: Transportable<M>, M: 'static>(&self, index: usize) -> Result<T, TakeDataError> { if index >= self.data.len() { tracing::trace!( "Tried to take more data than was available, len: {}, index: {}; This is normal if the server function was started on the client, but may indicate a bug if the server function result should be deserialized from the server", self.data.len(), index ); return Err(TakeDataError::DataNotAvailable); } let bytes = self.data[index].as_ref(); match bytes { Some(bytes) => match T::transport_from_bytes(bytes) { Ok(x) => Ok(x), Err(err) => { #[cfg(debug_assertions)] { let debug_type = self.debug_types.get(index); let debug_locations = self.debug_locations.get(index); if let (Some(Some(debug_type)), Some(Some(debug_locations))) = (debug_type, debug_locations) { let client_type = std::any::type_name::<T>(); let client_location = std::panic::Location::caller(); // We we have debug types and a location, we can provide a more helpful error message tracing::error!( "Error deserializing data: {err:?}\n\nThis type was serialized on the server at {debug_locations} with the type name {debug_type}. The client failed to deserialize the type {client_type} at {client_location}.", ); return Err(TakeDataError::DeserializationError(err)); } } // Otherwise, just log the generic deserialization error tracing::error!("Error deserializing data: {:?}", err); Err(TakeDataError::DeserializationError(err)) } }, None => Err(TakeDataError::DataPending), } } /// Extend this data with the data from another [`HTMLData`] pub(crate) fn extend(&mut self, other: &Self) { // Make sure this vectors error entry exists even if it is empty if self.data.is_empty() { self.data.push(None); #[cfg(debug_assertions)] { self.debug_types.push(None); self.debug_locations.push(None); } } let mut other_data_iter = other.data.iter().cloned(); #[cfg(debug_assertions)] let mut other_debug_types_iter = other.debug_types.iter().cloned(); #[cfg(debug_assertions)] let mut other_debug_locations_iter = other.debug_locations.iter().cloned(); // Merge the error entry from the other context if let Some(Some(other_error)) = other_data_iter.next() { self.data[0] = Some(other_error.clone()); #[cfg(debug_assertions)] { self.debug_types[0] = other_debug_types_iter.next().unwrap_or(None); self.debug_locations[0] = other_debug_locations_iter.next().unwrap_or(None); } } // Don't copy the error from the other context self.data.extend(other_data_iter); #[cfg(debug_assertions)] { self.debug_types.extend(other_debug_types_iter); self.debug_locations.extend(other_debug_locations_iter); } } /// Encode data as base64. This is intended to be used in the server to send data to the client. pub(crate) fn serialized(&self) -> SerializedHydrationData { let mut serialized = Vec::new(); ciborium::into_writer(&self.data, &mut serialized).unwrap(); let data = base64::engine::general_purpose::STANDARD.encode(serialized); #[cfg(debug_assertions)] let format_js_list_of_strings = |list: &[Option<String>]| { let body = list .iter() .map(|s| match s { Some(s) => { // Escape backslashes, quotes, and newlines let escaped = s .replace(r#"\"#, r#"\\"#) .replace("\n", r#"\n"#) .replace(r#"""#, r#"\""#); format!(r#""{escaped}""#) } None => r#""unknown""#.to_string(), }) .collect::<Vec<_>>() .join(","); format!("[{}]", body) }; SerializedHydrationData { data, #[cfg(debug_assertions)] debug_types: format_js_list_of_strings(&self.debug_types), #[cfg(debug_assertions)] debug_locations: format_js_list_of_strings(&self.debug_locations), } } } /// Data that was serialized on the server for hydration on the client. This includes /// extra information about the types and sources of the serialized data in debug mode pub struct SerializedHydrationData { /// The base64 encoded serialized data pub data: String, /// A list of the types of each serialized data #[cfg(debug_assertions)] pub debug_types: String, /// A list of the locations of each serialized data #[cfg(debug_assertions)] pub debug_locations: String, } /// An error that can occur when trying to take data from the server #[derive(Debug)] pub enum TakeDataError { /// Deserializing the data failed DeserializationError(ciborium::de::Error<std::io::Error>), /// No data was available DataNotAvailable, /// The server serialized a placeholder for the data, but it isn't available yet DataPending, } impl std::fmt::Display for TakeDataError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::DeserializationError(e) => write!(f, "DeserializationError: {}", e), Self::DataNotAvailable => write!(f, "DataNotAvailable"), Self::DataPending => write!(f, "DataPending"), } } } impl std::error::Error for TakeDataError {} /// Create a new entry in the serialize context for the head element hydration pub fn head_element_hydration_entry() -> SerializeContextEntry<bool> { serialize_context().create_entry() } /// A `Transportable` type can be safely transported from the server to the client, and be used for /// hydration. Not all types can sensibly be transported, but many can. This trait makes it possible /// to customize how types are transported which helps for non-serializable types like `dioxus_core::CapturedError`. /// /// By default, all types that implement `Serialize` and `DeserializeOwned` are transportable. /// /// You can also implement `Transportable` for `Result<T, dioxus_core::CapturedError>` where `T` is /// `Serialize` and `DeserializeOwned` to allow transporting results that may contain errors. /// /// Note that transporting a `Result<T, dioxus_core::CapturedError>` will lose various aspects of the original /// `dioxus_core::CapturedError` such as backtraces and source errors, but will preserve the error message. pub trait Transportable<M = ()>: 'static { /// Serialize the type to a byte vector for transport fn transport_to_bytes(&self) -> Vec<u8>; /// Deserialize the type from a byte slice fn transport_from_bytes(bytes: &[u8]) -> Result<Self, ciborium::de::Error<std::io::Error>> where Self: Sized; } impl<T> Transportable<()> for T where T: Serialize + DeserializeOwned + 'static, { fn transport_to_bytes(&self) -> Vec<u8> { let mut serialized = Vec::new(); ciborium::into_writer(self, &mut serialized).unwrap(); serialized } fn transport_from_bytes(bytes: &[u8]) -> Result<Self, ciborium::de::Error<std::io::Error>> where Self: Sized, { ciborium::from_reader(Cursor::new(bytes)) } } #[derive(Serialize, Deserialize)] struct TransportResultErr<T> { error: Result<T, CapturedError>, } #[doc(hidden)] pub struct TransportViaErrMarker; impl<T> Transportable<TransportViaErrMarker> for Result<T, anyhow::Error> where T: Serialize + DeserializeOwned + 'static, { fn transport_to_bytes(&self) -> Vec<u8> { let err = TransportResultErr { error: self .as_ref() .map_err(|e| CapturedError::from_display(e.to_string())), }; let mut serialized = Vec::new(); ciborium::into_writer(&err, &mut serialized).unwrap(); serialized } fn transport_from_bytes(bytes: &[u8]) -> Result<Self, ciborium::de::Error<std::io::Error>> where Self: Sized, { let err: TransportResultErr<T> = ciborium::from_reader(Cursor::new(bytes))?; match err.error { Ok(value) => Ok(Ok(value)), Err(captured) => Ok(Err(anyhow::Error::msg(captured.to_string()))), } } } #[doc(hidden)] pub struct TransportCapturedError; #[derive(Serialize, Deserialize)] struct TransportError { error: String, } impl Transportable<TransportCapturedError> for CapturedError { fn transport_to_bytes(&self) -> Vec<u8> { let err = TransportError { error: self.to_string(), }; let mut serialized = Vec::new(); ciborium::into_writer(&err, &mut serialized).unwrap(); serialized } fn transport_from_bytes(bytes: &[u8]) -> Result<Self, ciborium::de::Error<std::io::Error>> where Self: Sized, { let err: TransportError = ciborium::from_reader(Cursor::new(bytes))?; Ok(dioxus_core::CapturedError::msg::<String>(err.error)) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/fullstack-core/src/streaming.rs
packages/fullstack-core/src/streaming.rs
use crate::{HttpError, ServerFnError}; use axum_core::extract::FromRequest; use axum_core::response::IntoResponse; use dioxus_core::{CapturedError, ReactiveContext}; use http::StatusCode; use http::{request::Parts, HeaderMap}; use parking_lot::RwLock; use std::collections::HashSet; use std::fmt::Debug; use std::sync::Arc; /// The context provided by dioxus fullstack for server-side rendering. /// /// This context will only be set on the server during the initial streaming response /// and inside server functions. #[derive(Clone, Debug)] pub struct FullstackContext { // We expose the lock for request headers directly so it needs to be in a separate lock request_headers: Arc<RwLock<http::request::Parts>>, // The rest of the fields are only held internally, so we can group them together lock: Arc<RwLock<FullstackContextInner>>, } // `FullstackContext` is always set when either // 1. rendering the app via SSR // 2. handling a server function request tokio::task_local! { static FULLSTACK_CONTEXT: FullstackContext; } pub struct FullstackContextInner { current_status: StreamingStatus, current_status_subscribers: HashSet<ReactiveContext>, response_headers: Option<HeaderMap>, route_http_status: HttpError, route_http_status_subscribers: HashSet<ReactiveContext>, } impl Debug for FullstackContextInner { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FullstackContextInner") .field("current_status", &self.current_status) .field("response_headers", &self.response_headers) .field("route_http_status", &self.route_http_status) .finish() } } impl PartialEq for FullstackContext { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.lock, &other.lock) && Arc::ptr_eq(&self.request_headers, &other.request_headers) } } impl FullstackContext { /// Create a new streaming context. You should not need to call this directly. Dioxus fullstack will /// provide this context for you. pub fn new(parts: Parts) -> Self { Self { request_headers: RwLock::new(parts).into(), lock: RwLock::new(FullstackContextInner { current_status: StreamingStatus::RenderingInitialChunk, current_status_subscribers: Default::default(), route_http_status: HttpError { status: http::StatusCode::OK, message: None, }, route_http_status_subscribers: Default::default(), response_headers: Some(HeaderMap::new()), }) .into(), } } /// Commit the initial chunk of the response. This will be called automatically if you are using the /// dioxus router when the suspense boundary above the router is resolved. Otherwise, you will need /// to call this manually to start the streaming part of the response. /// /// Once this method has been called, the http response parts can no longer be modified. pub fn commit_initial_chunk(&mut self) { let mut lock = self.lock.write(); lock.current_status = StreamingStatus::InitialChunkCommitted; // The key type is mutable, but the hash is stable through mutations because we hash by pointer #[allow(clippy::mutable_key_type)] let subscribers = std::mem::take(&mut lock.current_status_subscribers); for subscriber in subscribers { subscriber.mark_dirty(); } } /// Get the current status of the streaming response. This method is reactive and will cause /// the current reactive context to rerun when the status changes. pub fn streaming_state(&self) -> StreamingStatus { let mut lock = self.lock.write(); // Register the current reactive context as a subscriber to changes in the streaming status if let Some(ctx) = ReactiveContext::current() { lock.current_status_subscribers.insert(ctx); } lock.current_status } /// Access the http request parts mutably. This will allow you to modify headers and other parts of the request. pub fn parts_mut(&self) -> parking_lot::RwLockWriteGuard<'_, http::request::Parts> { self.request_headers.write() } /// Run a future within the scope of this FullstackContext. pub async fn scope<F, R>(self, fut: F) -> R where F: std::future::Future<Output = R>, { FULLSTACK_CONTEXT.scope(self, fut).await } /// Extract an extension from the current request. pub fn extension<T: Clone + Send + Sync + 'static>(&self) -> Option<T> { let lock = self.request_headers.read(); lock.extensions.get::<T>().cloned() } /// Extract an axum extractor from the current request. /// /// The body of the request is always empty when using this method, as the body can only be consumed once in the server /// function extractors. pub async fn extract<T: FromRequest<Self, M>, M>() -> Result<T, ServerFnError> { let this = Self::current().unwrap_or_else(|| { // Create a dummy context if one doesn't exist, making the function usable outside of a request context FullstackContext::new( axum_core::extract::Request::builder() .method("GET") .uri("/") .header("X-Dummy-Header", "true") .body(()) .unwrap() .into_parts() .0, ) }); let parts = this.request_headers.read().clone(); let request = axum_core::extract::Request::from_parts(parts, Default::default()); match T::from_request(request, &this).await { Ok(res) => Ok(res), Err(err) => { let resp = err.into_response(); Err(ServerFnError::from_axum_response(resp).await) } } } /// Get the current `FullstackContext` if it exists. This will return `None` if called on the client /// or outside of a streaming response on the server or server function. pub fn current() -> Option<Self> { // Try to get the context from the task local (for server functions) if let Ok(context) = FULLSTACK_CONTEXT.try_get() { return Some(context); } // Otherwise, try to get it from the dioxus runtime context (for streaming SSR) if let Some(rt) = dioxus_core::Runtime::try_current() { let id = rt.try_current_scope_id()?; if let Some(ctx) = rt.consume_context::<FullstackContext>(id) { return Some(ctx); } } None } /// Get the current HTTP status for the route. This will default to 200 OK, but can be modified /// by calling `FullstackContext::commit_error_status` with an error. pub fn current_http_status(&self) -> HttpError { let mut lock = self.lock.write(); // Register the current reactive context as a subscriber to changes in the http status if let Some(ctx) = ReactiveContext::current() { lock.route_http_status_subscribers.insert(ctx); } lock.route_http_status.clone() } pub fn set_current_http_status(&mut self, status: HttpError) { let mut lock = self.lock.write(); lock.route_http_status = status; // The key type is mutable, but the hash is stable through mutations because we hash by pointer #[allow(clippy::mutable_key_type)] let subscribers = std::mem::take(&mut lock.route_http_status_subscribers); for subscriber in subscribers { subscriber.mark_dirty(); } } /// Add a header to the response. This will be sent to the client when the response is committed. pub fn add_response_header( &self, key: impl Into<http::header::HeaderName>, value: impl Into<http::header::HeaderValue>, ) { let mut lock = self.lock.write(); if let Some(headers) = lock.response_headers.as_mut() { headers.insert(key.into(), value.into()); } } /// Take the response headers out of the context. This will leave the context without any headers, /// so it should only be called once when the response is being committed. pub fn take_response_headers(&self) -> Option<HeaderMap> { let mut lock = self.lock.write(); lock.response_headers.take() } /// Set the current HTTP status for the route. This will be used when committing the response /// to the client. pub fn commit_http_status(status: StatusCode, message: Option<String>) { if let Some(mut ctx) = Self::current() { ctx.set_current_http_status(HttpError { status, message }); } } /// Commit the CapturedError as the current HTTP status for the route. /// This will attempt to downcast the error to known types and set the appropriate /// status code. If the error type is unknown, it will default to /// `StatusCode::INTERNAL_SERVER_ERROR`. pub fn commit_error_status(error: impl Into<CapturedError>) -> HttpError { let error = error.into(); let status = status_code_from_error(&error); let http_error = HttpError { status, message: Some(error.to_string()), }; if let Some(mut ctx) = Self::current() { ctx.set_current_http_status(http_error.clone()); } http_error } } /// The status of the streaming response #[derive(Clone, Copy, Debug, PartialEq)] pub enum StreamingStatus { /// The initial chunk is still being rendered. The http response parts can still be modified at this point. RenderingInitialChunk, /// The initial chunk has been committed and the response is now streaming. The http response parts /// have already been sent to the client and can no longer be modified. InitialChunkCommitted, } /// Commit the initial chunk of the response. This will be called automatically if you are using the /// dioxus router when the suspense boundary above the router is resolved. Otherwise, you will need /// to call this manually to start the streaming part of the response. /// /// On the client, this will do nothing. /// /// # Example /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_fullstack_core::*; /// # fn Children() -> Element { unimplemented!() } /// fn App() -> Element { /// // This will start streaming immediately after the current render is complete. /// use_hook(commit_initial_chunk); /// /// rsx! { Children {} } /// } /// ``` pub fn commit_initial_chunk() { crate::history::finalize_route(); if let Some(mut streaming) = FullstackContext::current() { streaming.commit_initial_chunk(); } } /// Extract an axum extractor from the current request. #[deprecated(note = "Use FullstackContext::extract instead", since = "0.7.0")] pub fn extract<T: FromRequest<FullstackContext, M>, M>( ) -> impl std::future::Future<Output = Result<T, ServerFnError>> { FullstackContext::extract::<T, M>() } /// Get the current status of the streaming response. This method is reactive and will cause /// the current reactive context to rerun when the status changes. /// /// On the client, this will always return `StreamingStatus::InitialChunkCommitted`. /// /// # Example /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_fullstack_core::*; /// #[component] /// fn MetaTitle(title: String) -> Element { /// // If streaming has already started, warn the user that the meta tag will not show /// // up in the initial chunk. /// use_hook(|| { /// if current_status() == StreamingStatus::InitialChunkCommitted { /// dioxus::logger::tracing::warn!("Since `MetaTitle` was rendered after the initial chunk was committed, the meta tag will not show up in the head without javascript enabled."); /// } /// }); /// /// rsx! { meta { property: "og:title", content: title } } /// } /// ``` pub fn current_status() -> StreamingStatus { if let Some(streaming) = FullstackContext::current() { streaming.streaming_state() } else { StreamingStatus::InitialChunkCommitted } } /// Convert a `CapturedError` into an appropriate HTTP status code. /// /// This will attempt to downcast the error to known types and return a corresponding status code. /// If the error type is unknown, it will default to `StatusCode::INTERNAL_SERVER_ERROR`. pub fn status_code_from_error(error: &CapturedError) -> StatusCode { if let Some(err) = error.downcast_ref::<ServerFnError>() { match err { ServerFnError::ServerError { code, .. } => { return StatusCode::from_u16(*code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) } _ => return StatusCode::INTERNAL_SERVER_ERROR, } } if let Some(err) = error.downcast_ref::<StatusCode>() { return *err; } if let Some(err) = error.downcast_ref::<HttpError>() { return err.status; } StatusCode::INTERNAL_SERVER_ERROR }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/lib.rs
packages/router-macro/src/lib.rs
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")] #![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")] extern crate proc_macro; use layout::Layout; use nest::{Nest, NestId}; use proc_macro::TokenStream; use proc_macro2::Span; use quote::{format_ident, quote, ToTokens}; use redirect::Redirect; use route::{Route, RouteType}; use segment::RouteSegment; use syn::{parse::ParseStream, parse_macro_input, Ident, Token, Type}; use proc_macro2::TokenStream as TokenStream2; use crate::{layout::LayoutId, route_tree::ParseRouteTree}; mod hash; mod layout; mod nest; mod query; mod redirect; mod route; mod route_tree; mod segment; /// Derives the Routable trait for an enum of routes /// /// Each variant must: /// 1. Be struct-like with {}'s /// 2. Contain all of the dynamic parameters of the current and nested routes /// 3. Have a `#[route("route")]` attribute /// /// Route Segments: /// 1. Static Segments: "/static" /// 2. Dynamic Segments: "/:dynamic" (where dynamic has a type that is FromStr in all child Variants) /// 3. Catch all Segments: "/:..segments" (where segments has a type that is FromSegments in all child Variants) /// 4. Query Segments: "/?:..query" (where query has a type that is FromQuery in all child Variants) or "/?:query&:other_query" (where query and other_query has a type that is FromQueryArgument in all child Variants) /// /// Routes are matched: /// 1. By there specificity this order: Query Routes ("/?:query"), Static Routes ("/route"), Dynamic Routes ("/:route"), Catch All Routes ("/:..route") /// 2. By the order they are defined in the enum /// /// All features: /// ```rust /// use dioxus::prelude::*; /// /// #[rustfmt::skip] /// #[derive(Clone, Debug, PartialEq, Routable)] /// enum Route { /// // Define routes with the route macro. If the name of the component is not the same as the variant, you can specify it as the second parameter /// #[route("/", IndexComponent)] /// Index {}, /// // Nests with parameters have types taken from child routes /// // Everything inside the nest has the added parameter `user_id: usize` /// #[nest("/user/:user_id")] /// // All children of layouts will be rendered inside the Outlet in the layout component /// // Creates a Layout UserFrame that has the parameter `user_id: usize` /// #[layout(UserFrame)] /// // If there is a component with the name Route1, you do not need to pass in the component name /// #[route("/:dynamic?:query")] /// Route1 { /// // The type is taken from the first instance of the dynamic parameter /// user_id: usize, /// dynamic: usize, /// query: String, /// }, /// #[route("/hello_world")] /// // You can opt out of the layout by using the `!` prefix /// #[layout(!UserFrame)] /// Route2 { user_id: usize }, /// // End layouts with #[end_layout] /// #[end_layout] /// // End nests with #[end_nest] /// #[end_nest] /// // Redirects take a path and a function that takes the parameters from the path and returns a new route /// #[redirect("/:id/user", |id: usize| Route::Route3 { dynamic: id.to_string()})] /// #[route("/:dynamic")] /// Route3 { dynamic: String }, /// } /// # #[component] /// # fn Route1(user_id: usize, dynamic: usize, query: String) -> Element { VNode::empty() } /// # #[component] /// # fn Route2(user_id: usize) -> Element { VNode::empty() } /// # #[component] /// # fn Route3(dynamic: String) -> Element { VNode::empty() } /// # #[component] /// # fn UserFrame(user_id: usize) -> Element { VNode::empty() } /// # #[component] /// # fn IndexComponent() -> Element { VNode::empty() } /// ``` /// /// # `#[route("path", component)]` /// /// The `#[route]` attribute is used to define a route. It takes up to 2 parameters: /// - `path`: The path to the enum variant (relative to the parent nest) /// - (optional) `component`: The component to render when the route is matched. If not specified, the name of the variant is used /// /// Routes are the most basic attribute. They allow you to define a route and the component to render when the route is matched. The component must take all dynamic parameters of the route and all parent nests. /// The next variant will be tied to the component. If you link to that variant, the component will be rendered. /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Routable)] /// enum Route { /// // Define routes that renders the IndexComponent /// // The Index component will be rendered when the route is matched (e.g. when the user navigates to /) /// #[route("/", Index)] /// Index {}, /// } /// # #[component] /// # fn Index() -> Element { VNode::empty() } /// ``` /// /// # `#[redirect("path", function)]` /// /// The `#[redirect]` attribute is used to define a redirect. It takes 2 parameters: /// - `path`: The path to the enum variant (relative to the parent nest) /// - `function`: A function that takes the parameters from the path and returns a new route /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Routable)] /// enum Route { /// // Redirects the /:id route to the Index route /// #[redirect("/:id", |id: usize| Route::Index {})] /// #[route("/", Index)] /// Index {}, /// } /// # #[component] /// # fn Index() -> Element { VNode::empty() } /// ``` /// /// Redirects allow you to redirect a route to another route. The function must take all dynamic parameters of the route and all parent nests. /// /// # `#[nest("path")]` /// /// The `#[nest]` attribute is used to define a nest. It takes 1 parameter: /// - `path`: The path to the nest (relative to the parent nest) /// /// Nests effect all nests, routes and redirects defined until the next `#[end_nest]` attribute. All children of nests are relative to the nest route and must include all dynamic parameters of the nest. /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Routable)] /// enum Route { /// // Nests all child routes in the /blog route /// #[nest("/blog")] /// // This is at /blog/:id /// #[redirect("/:id", |id: usize| Route::Index {})] /// // This is at /blog /// #[route("/", Index)] /// Index {}, /// } /// # #[component] /// # fn Index() -> Element { VNode::empty() } /// ``` /// /// # `#[end_nest]` /// /// The `#[end_nest]` attribute is used to end a nest. It takes no parameters. /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Routable)] /// enum Route { /// #[nest("/blog")] /// // This is at /blog/:id /// #[redirect("/:id", |id: usize| Route::Index {})] /// // This is at /blog /// #[route("/", Index)] /// Index {}, /// // Ends the nest /// #[end_nest] /// // This is at / /// #[route("/")] /// Home {}, /// } /// # #[component] /// # fn Index() -> Element { VNode::empty() } /// # #[component] /// # fn Home() -> Element { VNode::empty() } /// ``` /// /// # `#[layout(component)]` /// /// The `#[layout]` attribute is used to define a layout. It takes 1 parameter: /// - `component`: The component to render when the route is matched. If not specified, the name of the variant is used /// /// The layout component allows you to wrap all children of the layout in a component. The child routes are rendered in the Outlet of the layout component. The layout component must take all dynamic parameters of the nests it is nested in. /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Routable)] /// enum Route { /// #[layout(BlogFrame)] /// #[redirect("/:id", |id: usize| Route::Index {})] /// // Index will be rendered in the Outlet of the BlogFrame component /// #[route("/", Index)] /// Index {}, /// } /// # #[component] /// # fn Index() -> Element { VNode::empty() } /// # #[component] /// # fn BlogFrame() -> Element { VNode::empty() } /// ``` /// /// # `#[end_layout]` /// /// The `#[end_layout]` attribute is used to end a layout. It takes no parameters. /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Clone, Debug, PartialEq, Routable)] /// enum Route { /// #[layout(BlogFrame)] /// #[redirect("/:id", |id: usize| Route::Index {})] /// // Index will be rendered in the Outlet of the BlogFrame component /// #[route("/", Index)] /// Index {}, /// // Ends the layout /// #[end_layout] /// // This will be rendered standalone /// #[route("/")] /// Home {}, /// } /// # #[component] /// # fn Index() -> Element { VNode::empty() } /// # #[component] /// # fn BlogFrame() -> Element { VNode::empty() } /// # #[component] /// # fn Home() -> Element { VNode::empty() } /// ``` #[doc(alias = "route")] #[proc_macro_derive( Routable, attributes(route, nest, end_nest, layout, end_layout, redirect, child) )] pub fn routable(input: TokenStream) -> TokenStream { let routes_enum = parse_macro_input!(input as syn::ItemEnum); let route_enum = match RouteEnum::parse(routes_enum) { Ok(route_enum) => route_enum, Err(err) => return err.to_compile_error().into(), }; let error_type = route_enum.error_type(); let parse_impl = route_enum.parse_impl(); let display_impl = route_enum.impl_display(); let routable_impl = route_enum.routable_impl(); (quote! { const _: () = { #error_type #display_impl #routable_impl #parse_impl }; }) .into() } struct RouteEnum { name: Ident, endpoints: Vec<RouteEndpoint>, nests: Vec<Nest>, layouts: Vec<Layout>, site_map: Vec<SiteMapSegment>, } impl RouteEnum { fn parse(data: syn::ItemEnum) -> syn::Result<Self> { let name = &data.ident; let mut site_map = Vec::new(); let mut site_map_stack: Vec<Vec<SiteMapSegment>> = Vec::new(); let mut endpoints = Vec::new(); let mut layouts: Vec<Layout> = Vec::new(); let mut layout_stack = Vec::new(); let mut nests = Vec::new(); let mut nest_stack = Vec::new(); for variant in &data.variants { let mut excluded = Vec::new(); // Apply the any nesting attributes in order for attr in &variant.attrs { if attr.path().is_ident("nest") { let mut children_routes = Vec::new(); { // add all of the variants of the enum to the children_routes until we hit an end_nest let mut level = 0; 'o: for variant in &data.variants { children_routes.push(variant.fields.clone()); for attr in &variant.attrs { if attr.path().is_ident("nest") { level += 1; } else if attr.path().is_ident("end_nest") { level -= 1; if level < 0 { break 'o; } } } } } let nest_index = nests.len(); let parser = |input: ParseStream| { Nest::parse( input, children_routes .iter() .filter_map(|f: &syn::Fields| match f { syn::Fields::Named(fields) => Some(fields.clone()), _ => None, }) .collect(), nest_index, ) }; let nest = attr.parse_args_with(parser)?; // add the current segment to the site map stack let segments: Vec<_> = nest .segments .iter() .map(|seg| { let segment_type = seg.into(); SiteMapSegment { segment_type, children: Vec::new(), } }) .collect(); if !segments.is_empty() { site_map_stack.push(segments); } nests.push(nest); nest_stack.push(NestId(nest_index)); } else if attr.path().is_ident("end_nest") { nest_stack.pop(); // pop the current nest segment off the stack and add it to the parent or the site map if let Some(segment) = site_map_stack.pop() { let children = site_map_stack .last_mut() .map(|seg| &mut seg.last_mut().unwrap().children) .unwrap_or(&mut site_map); // Turn the list of segments in the segments stack into a tree let mut iter = segment.into_iter().rev(); let mut current = iter.next().unwrap(); for mut segment in iter { segment.children.push(current); current = segment; } children.push(current); } } else if attr.path().is_ident("layout") { let parser = |input: ParseStream| { let bang: Option<Token![!]> = input.parse().ok(); let exclude = bang.is_some(); Ok((exclude, Layout::parse(input, nest_stack.clone())?)) }; let (exclude, layout): (bool, Layout) = attr.parse_args_with(parser)?; if exclude { let Some(layout_index) = layouts.iter().position(|l| l.comp == layout.comp) else { return Err(syn::Error::new( Span::call_site(), "Attempted to exclude a layout that does not exist", )); }; excluded.push(LayoutId(layout_index)); } else { let layout_index = layouts.len(); layouts.push(layout); layout_stack.push(LayoutId(layout_index)); } } else if attr.path().is_ident("end_layout") { layout_stack.pop(); } else if attr.path().is_ident("redirect") { let parser = |input: ParseStream| { Redirect::parse(input, nest_stack.clone(), endpoints.len()) }; let redirect = attr.parse_args_with(parser)?; endpoints.push(RouteEndpoint::Redirect(redirect)); } } let active_nests = nest_stack.clone(); let mut active_layouts = layout_stack.clone(); active_layouts.retain(|&id| !excluded.contains(&id)); let route = Route::parse(active_nests, active_layouts, variant.clone())?; // add the route to the site map let mut segment = SiteMapSegment::new(&route.segments); if let RouteType::Child(child) = &route.ty { let new_segment = SiteMapSegment { segment_type: SegmentType::Child(child.ty.clone()), children: Vec::new(), }; match &mut segment { Some(segment) => { fn set_last_child_to( segment: &mut SiteMapSegment, new_segment: SiteMapSegment, ) { if let Some(last) = segment.children.last_mut() { set_last_child_to(last, new_segment); } else { segment.children = vec![new_segment]; } } set_last_child_to(segment, new_segment); } None => { segment = Some(new_segment); } } } if let Some(segment) = segment { let parent = site_map_stack.last_mut(); let children = match parent { Some(parent) => &mut parent.last_mut().unwrap().children, None => &mut site_map, }; children.push(segment); } endpoints.push(RouteEndpoint::Route(route)); } // pop any remaining site map segments while let Some(segment) = site_map_stack.pop() { let children = site_map_stack .last_mut() .map(|seg| &mut seg.last_mut().unwrap().children) .unwrap_or(&mut site_map); // Turn the list of segments in the segments stack into a tree let mut iter = segment.into_iter().rev(); let mut current = iter.next().unwrap(); for mut segment in iter { segment.children.push(current); current = segment; } children.push(current); } let myself = Self { name: name.clone(), endpoints, nests, layouts, site_map, }; Ok(myself) } fn impl_display(&self) -> TokenStream2 { let mut display_match = Vec::new(); for route in &self.endpoints { if let RouteEndpoint::Route(route) = route { display_match.push(route.display_match(&self.nests)); } } let name = &self.name; quote! { impl std::fmt::Display for #name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { #[allow(unused)] match self { #(#display_match)* } Ok(()) } } } } fn parse_impl(&self) -> TokenStream2 { let tree = ParseRouteTree::new(&self.endpoints, &self.nests); let name = &self.name; let error_name = format_ident!("{}MatchError", self.name); let tokens = tree.roots.iter().map(|&id| { let route = tree.get(id).unwrap(); route.to_tokens(&self.nests, &tree, self.name.clone(), error_name.clone()) }); quote! { impl<'a> ::core::convert::TryFrom<&'a str> for #name { type Error = <Self as ::std::str::FromStr>::Err; fn try_from(s: &'a str) -> ::std::result::Result<Self, Self::Error> { s.parse() } } impl ::std::str::FromStr for #name { type Err = dioxus_router::routable::RouteParseError<#error_name>; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let route = s; let (route, hash) = route.split_once('#').unwrap_or((route, "")); let (route, query) = route.split_once('?').unwrap_or((route, "")); // Remove any trailing slashes. We parse /route/ and /route in the same way // Note: we don't use trim because it includes more code let route = route.strip_suffix('/').unwrap_or(route); let query = dioxus_router::exports::percent_encoding::percent_decode_str(query) .decode_utf8() .unwrap_or(query.into()); let hash = dioxus_router::exports::percent_encoding::percent_decode_str(hash) .decode_utf8() .unwrap_or(hash.into()); let mut segments = route.split('/').map(|s| { dioxus_router::exports::percent_encoding::percent_decode_str(s) .decode_utf8() .unwrap_or(s.into()) }); // skip the first empty segment if s.starts_with('/') { let _ = segments.next(); } else { // if this route does not start with a slash, it is not a valid route return Err(dioxus_router::routable::RouteParseError { attempted_routes: Vec::new(), }); } let mut errors = Vec::new(); #(#tokens)* Err(dioxus_router::routable::RouteParseError { attempted_routes: errors, }) } } } } fn error_name(&self) -> Ident { Ident::new(&(self.name.to_string() + "MatchError"), Span::call_site()) } fn error_type(&self) -> TokenStream2 { let match_error_name = self.error_name(); let mut type_defs = Vec::new(); let mut error_variants = Vec::new(); let mut display_match = Vec::new(); for endpoint in &self.endpoints { match endpoint { RouteEndpoint::Route(route) => { let route_name = &route.route_name; let error_name = route.error_ident(); let route_str = &route.route; let comment = format!( " An error that can occur when trying to parse the route [`{}::{}`] ('{}').", self.name, route_name, route_str ); error_variants.push(quote! { #[doc = #comment] #route_name(#error_name) }); display_match.push(quote! { Self::#route_name(err) => write!(f, "Route '{}' ('{}') did not match:\n{}", stringify!(#route_name), #route_str, err)? }); type_defs.push(route.error_type()); } RouteEndpoint::Redirect(redirect) => { let error_variant = redirect.error_variant(); let error_name = redirect.error_ident(); let route_str = &redirect.route; let comment = format!( " An error that can occur when trying to parse the redirect '{}'.", route_str.value() ); error_variants.push(quote! { #[doc = #comment] #error_variant(#error_name) }); display_match.push(quote! { Self::#error_variant(err) => write!(f, "Redirect '{}' ('{}') did not match:\n{}", stringify!(#error_name), #route_str, err)? }); type_defs.push(redirect.error_type()); } } } for nest in &self.nests { let error_variant = nest.error_variant(); let error_name = nest.error_ident(); let route_str = &nest.route; let comment = format!( " An error that can occur when trying to parse the nested segment {} ('{}').", error_name, route_str ); error_variants.push(quote! { #[doc = #comment] #error_variant(#error_name) }); display_match.push(quote! { Self::#error_variant(err) => write!(f, "Nest '{}' ('{}') did not match:\n{}", stringify!(#error_name), #route_str, err)? }); type_defs.push(nest.error_type()); } let comment = format!( " An error that can occur when trying to parse the route enum [`{}`].", self.name ); quote! { #(#type_defs)* #[doc = #comment] #[allow(non_camel_case_types)] #[allow(clippy::derive_partial_eq_without_eq)] pub enum #match_error_name { #(#error_variants),* } impl ::std::fmt::Debug for #match_error_name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(f, "{}({})", stringify!(#match_error_name), self) } } impl ::std::fmt::Display for #match_error_name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { #(#display_match),* } Ok(()) } } } } fn routable_impl(&self) -> TokenStream2 { let name = &self.name; let site_map = &self.site_map; let mut matches = Vec::new(); // Collect all routes matches for route in &self.endpoints { if let RouteEndpoint::Route(route) = route { matches.push(route.routable_match(&self.layouts, &self.nests, name)); } } quote! { impl dioxus_router::routable::Routable for #name where Self: Clone { const SITE_MAP: &'static [dioxus_router::routable::SiteMapSegment] = &[ #(#site_map,)* ]; fn render(&self, level: usize) -> dioxus_core::Element { let myself = self.clone(); match (level, myself) { #(#matches)* _ => VNode::empty() } } } } } } #[allow(clippy::large_enum_variant)] enum RouteEndpoint { Route(Route), Redirect(Redirect), } struct SiteMapSegment { pub segment_type: SegmentType, pub children: Vec<SiteMapSegment>, } impl SiteMapSegment { fn new(segments: &[RouteSegment]) -> Option<Self> { let mut current = None; // walk backwards through the new segments, adding children as we go for segment in segments.iter().rev() { let segment_type = segment.into(); let mut segment = SiteMapSegment { segment_type, children: Vec::new(), }; // if we have a current segment, add it as a child if let Some(current) = current.take() { segment.children.push(current) } current = Some(segment); } current } } impl ToTokens for SiteMapSegment { fn to_tokens(&self, tokens: &mut TokenStream2) { let segment_type = &self.segment_type; let children = if let SegmentType::Child(ty) = &self.segment_type { quote! { #ty::SITE_MAP } } else { let children = self .children .iter() .map(|child| child.to_token_stream()) .collect::<Vec<_>>(); quote! { &[ #(#children,)* ] } }; tokens.extend(quote! { dioxus_router::routable::SiteMapSegment { segment_type: #segment_type, children: #children, } }); } } #[allow(clippy::large_enum_variant)] enum SegmentType { Static(String), Dynamic(String), CatchAll(String), Child(Type), } impl ToTokens for SegmentType { fn to_tokens(&self, tokens: &mut TokenStream2) { match self { SegmentType::Static(s) => { tokens.extend(quote! { dioxus_router::routable::SegmentType::Static(#s) }) } SegmentType::Dynamic(s) => { tokens.extend(quote! { dioxus_router::routable::SegmentType::Dynamic(#s) }) } SegmentType::CatchAll(s) => { tokens.extend(quote! { dioxus_router::routable::SegmentType::CatchAll(#s) }) } SegmentType::Child(_) => { tokens.extend(quote! { dioxus_router::routable::SegmentType::Child }) } } } } impl<'a> From<&'a RouteSegment> for SegmentType { fn from(value: &'a RouteSegment) -> Self { match value { RouteSegment::Static(s) => SegmentType::Static(s.to_string()), RouteSegment::Dynamic(s, _) => SegmentType::Dynamic(s.to_string()), RouteSegment::CatchAll(s, _) => SegmentType::CatchAll(s.to_string()), } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/redirect.rs
packages/router-macro/src/redirect.rs
use proc_macro2::{Ident, TokenStream}; use quote::{format_ident, quote}; use syn::LitStr; use crate::{ hash::HashFragment, nest::NestId, query::QuerySegment, segment::{create_error_type, parse_route_segments, RouteSegment}, }; #[derive(Debug)] pub(crate) struct Redirect { pub route: LitStr, pub nests: Vec<NestId>, pub segments: Vec<RouteSegment>, pub query: Option<QuerySegment>, pub hash: Option<HashFragment>, pub function: syn::ExprClosure, pub index: usize, } impl Redirect { pub fn error_ident(&self) -> Ident { format_ident!("Redirect{}ParseError", self.index) } pub fn error_variant(&self) -> Ident { format_ident!("Redirect{}", self.index) } pub fn error_type(&self) -> TokenStream { let error_name = self.error_ident(); create_error_type(&self.route.value(), error_name, &self.segments, None) } pub fn parse_query(&self) -> TokenStream { match &self.query { Some(query) => query.parse(), None => quote! {}, } } pub fn parse_hash(&self) -> TokenStream { match &self.hash { Some(hash) => hash.parse(), None => quote! {}, } } pub fn parse( input: syn::parse::ParseStream, active_nests: Vec<NestId>, index: usize, ) -> syn::Result<Self> { let path = input.parse::<syn::LitStr>()?; let _ = input.parse::<syn::Token![,]>(); let function = input.parse::<syn::ExprClosure>()?; let mut closure_arguments = Vec::new(); for arg in function.inputs.iter() { match arg { syn::Pat::Type(pat) => match &*pat.pat { syn::Pat::Ident(ident) => { closure_arguments.push((ident.ident.clone(), (*pat.ty).clone())); } _ => { return Err(syn::Error::new_spanned( arg, "Expected closure argument to be a typed pattern", )) } }, _ => { return Err(syn::Error::new_spanned( arg, "Expected closure argument to be a typed pattern", )) } } } let (segments, query, hash) = parse_route_segments( path.span(), #[allow(clippy::map_identity)] closure_arguments.iter().map(|(name, ty)| (name, ty)), &path.value(), )?; Ok(Redirect { route: path, nests: active_nests, segments, query, hash, function, index, }) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/nest.rs
packages/router-macro/src/nest.rs
use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{Ident, LitStr}; use crate::segment::{create_error_type, parse_route_segments, RouteSegment}; #[derive(Debug, Clone, Copy)] pub struct NestId(pub usize); #[derive(Debug, Clone)] pub struct Nest { pub route: String, pub segments: Vec<RouteSegment>, index: usize, } impl Nest { pub fn parse( input: syn::parse::ParseStream, children_routes: Vec<syn::FieldsNamed>, index: usize, ) -> syn::Result<Self> { // Parse the route let route: LitStr = input.parse()?; let route_segments = parse_route_segments( route.span(), children_routes .iter() .flat_map(|f| f.named.iter()) .map(|f| (f.ident.as_ref().unwrap(), &f.ty)), &route.value(), )? .0; for seg in &route_segments { if let RouteSegment::CatchAll(name, _) = seg { return Err(syn::Error::new_spanned( name, format!( "Catch-all segments are not allowed in nested routes: {}", route.value() ), )); } } Ok(Self { route: route.value(), segments: route_segments, index, }) } } impl Nest { pub fn dynamic_segments(&self) -> impl Iterator<Item = TokenStream> + '_ { self.dynamic_segments_names().map(|i| quote! {#i}) } pub fn dynamic_segments_names(&self) -> impl Iterator<Item = Ident> + '_ { self.segments.iter().filter_map(|seg| seg.name()) } pub fn write(&self) -> TokenStream { let write_segments = self.segments.iter().map(|s| s.write_segment()); quote! { { #(#write_segments)* } } } pub fn error_ident(&self) -> Ident { format_ident!("Nest{}ParseError", self.index) } pub fn error_variant(&self) -> Ident { format_ident!("Nest{}", self.index) } pub fn error_type(&self) -> TokenStream { let error_name = self.error_ident(); create_error_type(&self.route, error_name, &self.segments, None) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/layout.rs
packages/router-macro/src/layout.rs
use proc_macro2::TokenStream; use quote::quote; use syn::Path; use crate::nest::{Nest, NestId}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct LayoutId(pub usize); #[derive(Debug)] pub struct Layout { pub comp: Path, pub active_nests: Vec<NestId>, } impl Layout { pub fn routable_match(&self, nests: &[Nest]) -> TokenStream { let comp_name = &self.comp; let dynamic_segments = self .active_nests .iter() .flat_map(|id| nests[id.0].dynamic_segments()); quote! { rsx! { #comp_name { #(#dynamic_segments: #dynamic_segments,)* } } } } } impl Layout { pub fn parse(input: syn::parse::ParseStream, active_nests: Vec<NestId>) -> syn::Result<Self> { // Then parse the component name let _ = input.parse::<syn::Token![,]>(); let comp: Path = input.parse()?; Ok(Self { comp, active_nests }) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/hash.rs
packages/router-macro/src/hash.rs
use quote::quote; use syn::{Ident, Type}; use proc_macro2::TokenStream as TokenStream2; #[derive(Debug)] pub struct HashFragment { pub ident: Ident, pub ty: Type, } impl HashFragment { pub fn contains_ident(&self, ident: &Ident) -> bool { self.ident == *ident } pub fn parse(&self) -> TokenStream2 { let ident = &self.ident; let ty = &self.ty; quote! { let #ident = <#ty as dioxus_router::routable::FromHashFragment>::from_hash_fragment(&*hash); } } pub fn write(&self) -> TokenStream2 { let ident = &self.ident; quote! { { let __hash = #ident.to_string(); if !__hash.is_empty() { write!(f, "#{}", dioxus_router::exports::percent_encoding::utf8_percent_encode(&__hash, dioxus_router::exports::FRAGMENT_ASCII_SET))?; } } } } pub fn parse_from_str<'a>( route_span: proc_macro2::Span, mut fields: impl Iterator<Item = (&'a Ident, &'a Type)>, hash: &str, ) -> syn::Result<Self> { // check if the route has a hash string let Some(hash) = hash.strip_prefix(':') else { return Err(syn::Error::new( route_span, "Failed to parse `:`. Hash fragments must be in the format '#:<field>'", )); }; let hash_ident = Ident::new(hash, proc_macro2::Span::call_site()); let field = fields.find(|(name, _)| *name == &hash_ident); let ty = if let Some((_, ty)) = field { ty.clone() } else { return Err(syn::Error::new( route_span, format!("Could not find a field with the name '{}'", hash_ident), )); }; Ok(Self { ident: hash_ident, ty, }) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/query.rs
packages/router-macro/src/query.rs
use quote::quote; use syn::{Ident, Type}; use proc_macro2::TokenStream as TokenStream2; #[allow(clippy::large_enum_variant)] #[derive(Debug)] pub enum QuerySegment { Single(FullQuerySegment), Segments(Vec<QueryArgument>), } impl QuerySegment { pub fn contains_ident(&self, ident: &Ident) -> bool { match self { QuerySegment::Single(segment) => segment.ident == *ident, QuerySegment::Segments(segments) => { segments.iter().any(|segment| segment.ident == *ident) } } } pub fn parse(&self) -> TokenStream2 { match self { QuerySegment::Single(segment) => segment.parse(), QuerySegment::Segments(segments) => { let mut tokens = TokenStream2::new(); tokens.extend(quote! { let split_query: std::collections::HashMap<&str, &str> = query.split('&').filter_map(|s| s.split_once('=')).collect(); }); for segment in segments { tokens.extend(segment.parse()); } tokens } } } pub fn write(&self) -> TokenStream2 { match self { QuerySegment::Single(segment) => segment.write(), QuerySegment::Segments(segments) => { let mut tokens = TokenStream2::new(); tokens.extend(quote! { write!(f, "?")?; }); for (i, segment) in segments.iter().enumerate() { tokens.extend(segment.write(i == segments.len() - 1)); } tokens } } } pub fn parse_from_str<'a>( route_span: proc_macro2::Span, mut fields: impl Iterator<Item = (&'a Ident, &'a Type)>, query: &str, ) -> syn::Result<Self> { // check if the route has a query string if let Some(query) = query.strip_prefix(":..") { let query_ident = Ident::new(query, proc_macro2::Span::call_site()); let field = fields.find(|(name, _)| *name == &query_ident); let ty = if let Some((_, ty)) = field { ty.clone() } else { return Err(syn::Error::new( route_span, format!("Could not find a field with the name '{}'", query_ident), )); }; Ok(QuerySegment::Single(FullQuerySegment { ident: query_ident, ty, })) } else { let mut query_arguments = Vec::new(); for segment in query.split('&') { if segment.is_empty() { return Err(syn::Error::new( route_span, "Query segments should be non-empty", )); } if let Some(query_argument) = segment.strip_prefix(':') { let query_ident = Ident::new(query_argument, proc_macro2::Span::call_site()); let field = fields.find(|(name, _)| *name == &query_ident); let ty = if let Some((_, ty)) = field { ty.clone() } else { return Err(syn::Error::new( route_span, format!("Could not find a field with the name '{}'", query_ident), )); }; query_arguments.push(QueryArgument { ident: query_ident, ty, }); } else { return Err(syn::Error::new( route_span, "Query segments should be a : followed by the name of the query argument", )); } } Ok(QuerySegment::Segments(query_arguments)) } } } #[derive(Debug)] pub struct FullQuerySegment { pub ident: Ident, pub ty: Type, } impl FullQuerySegment { pub fn parse(&self) -> TokenStream2 { let ident = &self.ident; let ty = &self.ty; quote! { let #ident = <#ty as dioxus_router::routable::FromQuery>::from_query(&*query); } } pub fn write(&self) -> TokenStream2 { let ident = &self.ident; quote! { { let as_string = #ident.to_string(); write!(f, "?{}", dioxus_router::exports::percent_encoding::utf8_percent_encode(&as_string, dioxus_router::exports::QUERY_ASCII_SET))?; } } } } #[derive(Debug)] pub struct QueryArgument { pub ident: Ident, pub ty: Type, } impl QueryArgument { pub fn parse(&self) -> TokenStream2 { let ident = &self.ident; let ty = &self.ty; quote! { let #ident = match split_query.get(stringify!(#ident)) { Some(query_argument) => { use dioxus_router::routable::FromQueryArgument; <#ty>::from_query_argument(query_argument).unwrap_or_default() }, None => <#ty as Default>::default(), }; } } pub fn write(&self, trailing: bool) -> TokenStream2 { let ident = &self.ident; let write_ampersand = if !trailing { quote! { if !as_string.is_empty() { write!(f, "&")?; } } } else { quote! {} }; quote! { { let as_string = dioxus_router::routable::DisplayQueryArgument::new(stringify!(#ident), #ident).to_string(); write!(f, "{}", dioxus_router::exports::percent_encoding::utf8_percent_encode(&as_string, dioxus_router::exports::QUERY_ASCII_SET))?; #write_ampersand } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/route.rs
packages/router-macro/src/route.rs
use quote::{format_ident, quote, quote_spanned}; use syn::parse::Parse; use syn::parse::ParseStream; use syn::parse_quote; use syn::Field; use syn::Path; use syn::Type; use syn::{Ident, LitStr}; use proc_macro2::TokenStream as TokenStream2; use crate::hash::HashFragment; use crate::layout::Layout; use crate::layout::LayoutId; use crate::nest::Nest; use crate::nest::NestId; use crate::query::QuerySegment; use crate::segment::create_error_type; use crate::segment::parse_route_segments; use crate::segment::RouteSegment; struct RouteArgs { route: LitStr, comp_name: Option<Path>, } impl Parse for RouteArgs { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let route = input.parse::<LitStr>()?; Ok(RouteArgs { route, comp_name: { let _ = input.parse::<syn::Token![,]>(); input.parse().ok() }, }) } } struct ChildArgs { route: LitStr, } impl Parse for ChildArgs { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let route = input.parse::<LitStr>()?; Ok(ChildArgs { route }) } } #[derive(Debug)] pub(crate) struct Route { pub route_name: Ident, pub ty: RouteType, pub route: String, pub segments: Vec<RouteSegment>, pub query: Option<QuerySegment>, pub hash: Option<HashFragment>, pub nests: Vec<NestId>, pub layouts: Vec<LayoutId>, fields: Vec<(Ident, Type)>, } impl Route { pub(crate) fn parse( nests: Vec<NestId>, layouts: Vec<LayoutId>, variant: syn::Variant, ) -> syn::Result<Self> { let route_attr = variant .attrs .iter() .find(|attr| attr.path().is_ident("route")); let route; let ty; let route_name = variant.ident.clone(); match route_attr { Some(attr) => { let args = attr.parse_args::<RouteArgs>()?; let comp_name = args.comp_name.unwrap_or_else(|| parse_quote!(#route_name)); ty = RouteType::Leaf { component: comp_name, }; route = args.route.value(); } None => { if let Some(route_attr) = variant .attrs .iter() .find(|attr| attr.path().is_ident("child")) { let args = route_attr.parse_args::<ChildArgs>()?; route = args.route.value(); match &variant.fields { syn::Fields::Named(fields) => { // find either a field with #[child] or a field named "child" let child_field = fields.named.iter().find(|f| { f.attrs .iter() .any(|attr| attr.path().is_ident("child")) || *f.ident.as_ref().unwrap() == "child" }); match child_field{ Some(child) => { ty = RouteType::Child(child.clone()); } None => { return Err(syn::Error::new_spanned( variant.clone(), "Routable variants with a #[child(..)] attribute must have a field named \"child\" or a field with a #[child] attribute", )); } } } _ => { return Err(syn::Error::new_spanned( variant.clone(), "Routable variants with a #[child(..)] attribute must have named fields", )) } } } else { return Err(syn::Error::new_spanned( variant.clone(), "Routable variants must either have a #[route(..)] attribute or a #[child(..)] attribute", )); } } }; let fields = match &variant.fields { syn::Fields::Named(fields) => fields .named .iter() .filter_map(|f| { if let RouteType::Child(child) = &ty { if f.ident == child.ident { return None; } } Some((f.ident.clone().unwrap(), f.ty.clone())) }) .collect(), _ => Vec::new(), }; let (route_segments, query, hash) = { parse_route_segments( variant.ident.span(), fields.iter().map(|f| (&f.0, &f.1)), &route, )? }; Ok(Self { ty, route_name, segments: route_segments, route, query, hash, nests, layouts, fields, }) } pub(crate) fn display_match(&self, nests: &[Nest]) -> TokenStream2 { let name = &self.route_name; let dynamic_segments = self.dynamic_segments(); let write_query: Option<TokenStream2> = self.query.as_ref().map(|q| q.write()); let write_hash = self.hash.as_ref().map(|q| q.write()); match &self.ty { RouteType::Child(field) => { let write_nests = self.nests.iter().map(|id| nests[id.0].write()); let write_segments = self.segments.iter().map(|s| s.write_segment()); let child = field.ident.as_ref().unwrap(); quote! { Self::#name { #(#dynamic_segments,)* #child } => { use ::std::fmt::Display; use ::std::fmt::Write; let mut route = String::new(); { let f = &mut route; #(#write_nests)* #(#write_segments)* } if route.ends_with('/') { route.pop(); } f.write_str(&route)?; #child.fmt(f)?; } } } RouteType::Leaf { .. } => { let write_nests = self.nests.iter().map(|id| nests[id.0].write()); let write_segments = self.segments.iter().map(|s| s.write_segment()); quote! { Self::#name { #(#dynamic_segments,)* } => { #(#write_nests)* #(#write_segments)* #write_query #write_hash } } } } } pub(crate) fn routable_match( &self, layouts: &[Layout], nests: &[Nest], router_name: &Ident, ) -> TokenStream2 { let name = &self.route_name; let mut tokens = TokenStream2::new(); // First match all layouts for (idx, layout_id) in self.layouts.iter().copied().enumerate() { let render_layout = layouts[layout_id.0].routable_match(nests); let dynamic_segments = self.dynamic_segments(); let mut field_name = None; if let RouteType::Child(field) = &self.ty { field_name = field.ident.as_ref(); } let field_name = field_name.map(|f| quote!(#f,)); // This is a layout tokens.extend(quote! { #[allow(unused)] (#idx, Self::#name { #(#dynamic_segments,)* #field_name .. }) => { #render_layout } }); } // Then match the route let last_index = self.layouts.len(); tokens.extend(match &self.ty { RouteType::Child(field) => { let field_name = field.ident.as_ref().unwrap(); quote! { #[allow(unused)] (#last_index.., Self::#name { #field_name, .. }) => { rsx! { dioxus_router::components::child_router::ChildRouter { route: #field_name, // Try to parse the current route as a parent route, and then match it as a child route parse_route_from_root_route: |__route| if let Ok(__route) = __route.parse() { if let Self::#name { #field_name, .. } = __route { Some(#field_name) } else { None } } else { None }, // Try to parse the child route and turn it into a parent route format_route_as_root_route: |#field_name| Self::#name { #field_name: #field_name }.to_string(), } } } } } RouteType::Leaf { component } => { let dynamic_segments = self.dynamic_segments(); let dynamic_segments_from_route = self.dynamic_segments(); let component = quote_spanned! { name.span() => #component }; /* The implementation of this is pretty gnarly/gross. We achieve the bundle splitting by wrapping the incoming function in a new component that suspends based on an internal lazy loader. This lets us use suspense features without breaking the rules of hooks. The router derive is quite complex so this shoves the complexity towards the "leaf" of the codegen rather to its core. In the future though, we should think about restructuring the router macro completely since its codegen makes up nearly 30-40% of the binary size in the dioxus docsite. */ use sha2::Digest; let dynamic_segments_receiver = self.dynamic_segments(); let dynamic_segments_from_route_ = self.dynamic_segments(); let dynamic_segments_from_route__ = self.dynamic_segments(); let unique_identifier = base16::encode_lower( &sha2::Sha256::digest(format!("{name} {span:?}", span = name.span()))[..16], ); let module_name = format_ident!("module{}{unique_identifier}", name).to_string(); let comp_name = format_ident!("route{}{unique_identifier}", name); quote! { #[allow(unused)] (#last_index, Self::#name { #(#dynamic_segments,)* }) => { dioxus::config_macros::maybe_wasm_split! { if wasm_split { { fn #comp_name(args: #router_name) -> Element { match args { #router_name::#name { #(#dynamic_segments_from_route_,)* } => { rsx! { #component { #(#dynamic_segments_from_route__: #dynamic_segments_from_route__,)* } } } _ => unreachable!() } } #[component] fn LoaderInner(args: NoPartialEq<#router_name>) -> Element { static MODULE: wasm_split::LazyLoader<#router_name, Element> = wasm_split::lazy_loader!(extern #module_name fn #comp_name(props: #router_name) -> Element); use_resource(|| async move { MODULE.load().await }).suspend()?; MODULE.call(args.0).unwrap() } struct NoPartialEq<T>(T); impl<T: Clone> Clone for NoPartialEq<T> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<T: ::std::fmt::Display> ::std::fmt::Display for NoPartialEq<T> { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { self.0.fmt(f) } } impl<T> PartialEq for NoPartialEq<T> { fn eq(&self, _other: &Self) -> bool { false } } rsx! { LoaderInner { args: NoPartialEq(#router_name::#name { #(#dynamic_segments_receiver,)* } ) } } } } else { { rsx! { #component { #(#dynamic_segments_from_route: #dynamic_segments_from_route,)* } } } } } } } } }); tokens } fn dynamic_segments(&self) -> impl Iterator<Item = TokenStream2> + '_ { self.fields.iter().map(|(name, _)| { quote! {#name} }) } pub(crate) fn construct(&self, nests: &[Nest], enum_name: Ident) -> TokenStream2 { let segments = self.fields.iter().map(|(name, _)| { let mut from_route = false; for id in &self.nests { let nest = &nests[id.0]; if nest.dynamic_segments_names().any(|i| &i == name) { from_route = true } } for segment in &self.segments { if segment.name().as_ref() == Some(name) { from_route = true } } if let Some(query) = &self.query { if query.contains_ident(name) { from_route = true } } if let Some(hash) = &self.hash { if hash.contains_ident(name) { from_route = true } } if from_route { quote! {#name} } else { quote! {#name: Default::default()} } }); match &self.ty { RouteType::Child(field) => { let name = &self.route_name; let child_name = field.ident.as_ref().unwrap(); quote! { #enum_name::#name { #child_name, #(#segments,)* } } } RouteType::Leaf { .. } => { let name = &self.route_name; quote! { #enum_name::#name { #(#segments,)* } } } } } pub(crate) fn error_ident(&self) -> Ident { format_ident!("{}ParseError", self.route_name) } pub(crate) fn error_type(&self) -> TokenStream2 { let error_name = self.error_ident(); let child_type = match &self.ty { RouteType::Child(field) => Some(&field.ty), RouteType::Leaf { .. } => None, }; create_error_type(&self.route, error_name, &self.segments, child_type) } pub(crate) fn parse_query(&self) -> TokenStream2 { match &self.query { Some(query) => query.parse(), None => quote! {}, } } pub(crate) fn parse_hash(&self) -> TokenStream2 { match &self.hash { Some(hash) => hash.parse(), None => quote! {}, } } } #[allow(clippy::large_enum_variant)] #[derive(Debug)] pub(crate) enum RouteType { Child(Field), Leaf { component: Path }, }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/route_tree.rs
packages/router-macro/src/route_tree.rs
use proc_macro2::TokenStream; use quote::quote; use slab::Slab; use syn::Ident; use crate::{ nest::{Nest, NestId}, redirect::Redirect, route::{Route, RouteType}, segment::{static_segment_idx, RouteSegment}, RouteEndpoint, }; #[derive(Debug, Clone, Default)] pub(crate) struct ParseRouteTree<'a> { pub roots: Vec<usize>, entries: Slab<RouteTreeSegmentData<'a>>, } impl<'a> ParseRouteTree<'a> { pub fn get(&self, index: usize) -> Option<&RouteTreeSegmentData<'a>> { self.entries.get(index) } pub fn get_mut(&mut self, element: usize) -> Option<&mut RouteTreeSegmentData<'a>> { self.entries.get_mut(element) } fn sort_children(&mut self) { let mut old_roots = self.roots.clone(); self.sort_ids(&mut old_roots); self.roots = old_roots; for id in self.roots.clone() { self.sort_children_of_id(id); } } fn sort_ids(&self, ids: &mut [usize]) { ids.sort_by_key(|&seg| { let seg = self.get(seg).unwrap(); match seg { RouteTreeSegmentData::Static { .. } => 0, RouteTreeSegmentData::Nest { .. } => 1, RouteTreeSegmentData::Route(route) => { // Routes that end in a catch all segment should be checked last match route.segments.last() { Some(RouteSegment::CatchAll(..)) => 2, _ => 1, } } RouteTreeSegmentData::Redirect(redirect) => { // Routes that end in a catch all segment should be checked last match redirect.segments.last() { Some(RouteSegment::CatchAll(..)) => 2, _ => 1, } } } }); } fn sort_children_of_id(&mut self, id: usize) { // Sort segments so that all static routes are checked before dynamic routes let mut children = self.children(id); self.sort_ids(&mut children); if let Some(old) = self.try_children_mut(id) { old.clone_from(&children) } for id in children { self.sort_children_of_id(id); } } fn children(&self, element: usize) -> Vec<usize> { let element = self.entries.get(element).unwrap(); match element { RouteTreeSegmentData::Static { children, .. } => children.clone(), RouteTreeSegmentData::Nest { children, .. } => children.clone(), _ => Vec::new(), } } fn try_children_mut(&mut self, element: usize) -> Option<&mut Vec<usize>> { let element = self.entries.get_mut(element).unwrap(); match element { RouteTreeSegmentData::Static { children, .. } => Some(children), RouteTreeSegmentData::Nest { children, .. } => Some(children), _ => None, } } fn children_mut(&mut self, element: usize) -> &mut Vec<usize> { self.try_children_mut(element) .expect("Cannot get children of non static or nest segment") } pub(crate) fn new(endpoints: &'a [RouteEndpoint], nests: &'a [Nest]) -> Self { let routes = endpoints .iter() .map(|endpoint| match endpoint { RouteEndpoint::Route(route) => PathIter::new_route(route, nests), RouteEndpoint::Redirect(redirect) => PathIter::new_redirect(redirect, nests), }) .collect::<Vec<_>>(); let mut myself = Self::default(); myself.roots = myself.construct(routes); myself.sort_children(); myself } pub fn construct(&mut self, routes: Vec<PathIter<'a>>) -> Vec<usize> { let mut segments = Vec::new(); // Add all routes to the tree for mut route in routes { let mut current_route: Option<usize> = None; // First add all nests while let Some(nest) = route.next_nest() { let segments_iter = nest.segments.iter(); // Add all static segments of the nest 'o: for (index, segment) in segments_iter.enumerate() { match segment { RouteSegment::Static(segment) => { // Check if the segment already exists { // Either look for the segment in the current route or in the static segments let segments = current_route .map(|id| self.children(id)) .unwrap_or_else(|| segments.clone()); for &seg_id in segments.iter() { let seg = self.get(seg_id).unwrap(); if let RouteTreeSegmentData::Static { segment: s, .. } = seg { if *s == segment { // If it does, just update the current route current_route = Some(seg_id); continue 'o; } } } } let static_segment = RouteTreeSegmentData::Static { segment, children: Vec::new(), error_variant: StaticErrorVariant { variant_parse_error: nest.error_ident(), enum_variant: nest.error_variant(), }, index, }; // If it doesn't, add the segment to the current route let static_segment = self.entries.insert(static_segment); let current_children = current_route .map(|id| self.children_mut(id)) .unwrap_or_else(|| &mut segments); current_children.push(static_segment); // Update the current route current_route = Some(static_segment); } // If there is a dynamic segment, stop adding static segments RouteSegment::Dynamic(..) => break, RouteSegment::CatchAll(..) => { unimplemented!("Catch all segments are not allowed in nests") } } } // Add the nest to the current route let nest = RouteTreeSegmentData::Nest { nest, children: Vec::new(), }; let nest = self.entries.insert(nest); let segments = match current_route.and_then(|id| self.get_mut(id)) { Some(RouteTreeSegmentData::Static { children, .. }) => children, Some(RouteTreeSegmentData::Nest { children, .. }) => children, Some(r) => { unreachable!("{current_route:?}\n{r:?} is not a static or nest segment",) } None => &mut segments, }; segments.push(nest); // Update the current route current_route = Some(nest); } match route.next_static_segment() { // If there is a static segment, check if it already exists in the tree Some((i, segment)) => { let current_children = current_route .map(|id| self.children(id)) .unwrap_or_else(|| segments.clone()); let found = current_children.iter().find_map(|&id| { let seg = self.get(id).unwrap(); match seg { RouteTreeSegmentData::Static { segment: s, .. } => { (s == &segment).then_some(id) } _ => None, } }); match found { Some(id) => { // If it exists, add the route to the children of the segment let new_children = self.construct(vec![route]); self.children_mut(id).extend(new_children); } None => { // If it doesn't exist, add the route as a new segment let data = RouteTreeSegmentData::Static { segment, error_variant: route.error_variant(), children: self.construct(vec![route]), index: i, }; let id = self.entries.insert(data); let current_children_mut = current_route .map(|id| self.children_mut(id)) .unwrap_or_else(|| &mut segments); current_children_mut.push(id); } } } // If there is no static segment, add the route to the current_route None => { let id = self.entries.insert(route.final_segment); let current_children_mut = current_route .map(|id| self.children_mut(id)) .unwrap_or_else(|| &mut segments); current_children_mut.push(id); } } } segments } } #[derive(Debug, Clone)] pub struct StaticErrorVariant { variant_parse_error: Ident, enum_variant: Ident, } // First deduplicate the routes by the static part of the route #[derive(Debug, Clone)] pub(crate) enum RouteTreeSegmentData<'a> { Static { segment: &'a str, error_variant: StaticErrorVariant, index: usize, children: Vec<usize>, }, Nest { nest: &'a Nest, children: Vec<usize>, }, Route(&'a Route), Redirect(&'a Redirect), } impl RouteTreeSegmentData<'_> { pub fn to_tokens( &self, nests: &[Nest], tree: &ParseRouteTree, enum_name: syn::Ident, error_enum_name: syn::Ident, ) -> TokenStream { match self { RouteTreeSegmentData::Static { segment, children, index, error_variant: StaticErrorVariant { variant_parse_error, enum_variant, }, } => { let children = children.iter().map(|child| { let child = tree.get(*child).unwrap(); child.to_tokens(nests, tree, enum_name.clone(), error_enum_name.clone()) }); if segment.is_empty() { return quote! { { #(#children)* } }; } let error_ident = static_segment_idx(*index); quote! { { let mut segments = segments.clone(); let segment = segments.next(); if let Some(segment) = segment.as_deref() { if #segment == segment { #(#children)* } else { errors.push(#error_enum_name::#enum_variant(#variant_parse_error::#error_ident(segment.to_string()))) } } } } } RouteTreeSegmentData::Route(route) => { // At this point, we have matched all static segments, so we can just check if the remaining segments match the route let variant_parse_error = route.error_ident(); let enum_variant = &route.route_name; let route_segments = route .segments .iter() .enumerate() .skip_while(|(_, seg)| matches!(seg, RouteSegment::Static(_))) .filter(|(i, _)| { // Don't add any trailing static segments. We strip them during parsing so that routes can accept either `/route/` and `/route` !is_trailing_static_segment(&route.segments, *i) }); let construct_variant = route.construct(nests, enum_name); let parse_query = route.parse_query(); let parse_hash = route.parse_hash(); let insure_not_trailing = match route.ty { RouteType::Leaf { .. } => route .segments .last() .map(|seg| !matches!(seg, RouteSegment::CatchAll(_, _))) .unwrap_or(true), RouteType::Child(_) => false, }; let print_route_segment = print_route_segment( route_segments.peekable(), return_constructed( insure_not_trailing, construct_variant, &error_enum_name, enum_variant, &variant_parse_error, parse_query, parse_hash, ), &error_enum_name, enum_variant, &variant_parse_error, ); match &route.ty { RouteType::Child(child) => { let ty = &child.ty; let child_name = &child.ident; quote! { let mut trailing = String::from("/"); for seg in segments.clone() { trailing += &*seg; trailing += "/"; } match #ty::from_str(&trailing).map_err(|err| #error_enum_name::#enum_variant(#variant_parse_error::ChildRoute(err))) { Ok(#child_name) => { #print_route_segment } Err(err) => { errors.push(err); } } } } RouteType::Leaf { .. } => print_route_segment, } } Self::Nest { nest, children } => { // At this point, we have matched all static segments, so we can just check if the remaining segments match the route let variant_parse_error: Ident = nest.error_ident(); let enum_variant = nest.error_variant(); let route_segments = nest .segments .iter() .enumerate() .skip_while(|(_, seg)| matches!(seg, RouteSegment::Static(_))); let parse_children = children .iter() .map(|child| { let child = tree.get(*child).unwrap(); child.to_tokens(nests, tree, enum_name.clone(), error_enum_name.clone()) }) .collect(); print_route_segment( route_segments.peekable(), parse_children, &error_enum_name, &enum_variant, &variant_parse_error, ) } Self::Redirect(redirect) => { // At this point, we have matched all static segments, so we can just check if the remaining segments match the route let variant_parse_error = redirect.error_ident(); let enum_variant = &redirect.error_variant(); let route_segments = redirect .segments .iter() .enumerate() .skip_while(|(_, seg)| matches!(seg, RouteSegment::Static(_))); let parse_query = redirect.parse_query(); let parse_hash = redirect.parse_hash(); let insure_not_trailing = redirect .segments .last() .map(|seg| !matches!(seg, RouteSegment::CatchAll(_, _))) .unwrap_or(true); let redirect_function = &redirect.function; let args = redirect_function.inputs.iter().map(|pat| match pat { syn::Pat::Type(ident) => { let name = &ident.pat; quote! {#name} } _ => panic!("Expected closure argument to be a typed pattern"), }); let return_redirect = quote! { (#redirect_function)(#(#args,)*) }; print_route_segment( route_segments.peekable(), return_constructed( insure_not_trailing, return_redirect, &error_enum_name, enum_variant, &variant_parse_error, parse_query, parse_hash, ), &error_enum_name, enum_variant, &variant_parse_error, ) } } } } fn print_route_segment<'a, I: Iterator<Item = (usize, &'a RouteSegment)>>( mut s: std::iter::Peekable<I>, success_tokens: TokenStream, error_enum_name: &Ident, enum_variant: &Ident, variant_parse_error: &Ident, ) -> TokenStream { if let Some((i, route)) = s.next() { let children = print_route_segment( s, success_tokens, error_enum_name, enum_variant, variant_parse_error, ); route.try_parse( i, error_enum_name, enum_variant, variant_parse_error, children, ) } else { quote! { #success_tokens } } } fn return_constructed( insure_not_trailing: bool, construct_variant: TokenStream, error_enum_name: &Ident, enum_variant: &Ident, variant_parse_error: &Ident, parse_query: TokenStream, parse_hash: TokenStream, ) -> TokenStream { if insure_not_trailing { quote! { let remaining_segments = segments.clone(); let mut segments_clone = segments.clone(); let next_segment = segments_clone.next(); // This is the last segment, return the parsed route if next_segment.is_none() { #parse_query #parse_hash return Ok(#construct_variant); } else { let mut trailing = String::new(); for seg in remaining_segments { trailing += &*seg; trailing += "/"; } trailing.pop(); errors.push(#error_enum_name::#enum_variant(#variant_parse_error::ExtraSegments(trailing))) } } } else { quote! { #parse_query #parse_hash return Ok(#construct_variant); } } } pub struct PathIter<'a> { final_segment: RouteTreeSegmentData<'a>, active_nests: &'a [NestId], all_nests: &'a [Nest], segments: &'a [RouteSegment], error_ident: Ident, error_variant: Ident, nest_index: usize, static_segment_index: usize, } impl<'a> PathIter<'a> { fn new_route(route: &'a Route, nests: &'a [Nest]) -> Self { Self { final_segment: RouteTreeSegmentData::Route(route), active_nests: &*route.nests, segments: &*route.segments, error_ident: route.error_ident(), error_variant: route.route_name.clone(), all_nests: nests, nest_index: 0, static_segment_index: 0, } } fn new_redirect(redirect: &'a Redirect, nests: &'a [Nest]) -> Self { Self { final_segment: RouteTreeSegmentData::Redirect(redirect), active_nests: &*redirect.nests, segments: &*redirect.segments, error_ident: redirect.error_ident(), error_variant: redirect.error_variant(), all_nests: nests, nest_index: 0, static_segment_index: 0, } } fn next_nest(&mut self) -> Option<&'a Nest> { let idx = self.nest_index; let nest_index = self.active_nests.get(idx)?; let nest = &self.all_nests[nest_index.0]; self.nest_index += 1; Some(nest) } fn next_static_segment(&mut self) -> Option<(usize, &'a str)> { let idx = self.static_segment_index; let segment = self.segments.get(idx)?; // Don't add any trailing static segments. We strip them during parsing so that routes can accept either `/route/` and `/route` if is_trailing_static_segment(self.segments, idx) { return None; } match segment { RouteSegment::Static(segment) => { self.static_segment_index += 1; Some((idx, segment)) } _ => None, } } fn error_variant(&self) -> StaticErrorVariant { StaticErrorVariant { variant_parse_error: self.error_ident.clone(), enum_variant: self.error_variant.clone(), } } } // If this is the last segment and it is an empty trailing segment, skip parsing it. The parsing code handles parsing /path/ and /path pub(crate) fn is_trailing_static_segment(segments: &[RouteSegment], index: usize) -> bool { // This can only be a trailing segment if we have more than one segment and this is the last segment matches!(segments.get(index), Some(RouteSegment::Static(segment)) if segment.is_empty() && index == segments.len() - 1 && segments.len() > 1) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router-macro/src/segment.rs
packages/router-macro/src/segment.rs
use quote::{format_ident, quote, ToTokens}; use syn::{Ident, Type}; use proc_macro2::{Span, TokenStream as TokenStream2}; use crate::{hash::HashFragment, query::QuerySegment}; #[derive(Debug, Clone)] pub enum RouteSegment { Static(String), Dynamic(Ident, Type), CatchAll(Ident, Type), } impl RouteSegment { pub fn name(&self) -> Option<Ident> { match self { Self::Static(_) => None, Self::Dynamic(ident, _) => Some(ident.clone()), Self::CatchAll(ident, _) => Some(ident.clone()), } } pub fn write_segment(&self) -> TokenStream2 { match self { Self::Static(segment) => quote! { write!(f, "/{}", #segment)?; }, Self::Dynamic(ident, _) => quote! { { let as_string = #ident.to_string(); write!(f, "/{}", dioxus_router::exports::percent_encoding::utf8_percent_encode(&as_string, dioxus_router::exports::PATH_ASCII_SET))?; } }, Self::CatchAll(ident, _) => quote! { dioxus_router::ToRouteSegments::display_route_segments(#ident,f)?; }, } } pub fn error_name(&self, idx: usize) -> Ident { match self { Self::Static(_) => static_segment_idx(idx), Self::Dynamic(ident, _) => format_ident!("{}ParseError", ident), Self::CatchAll(ident, _) => format_ident!("{}ParseError", ident), } } pub fn missing_error_name(&self) -> Option<Ident> { match self { Self::Dynamic(ident, _) => Some(format_ident!("{}MissingError", ident)), _ => None, } } pub fn try_parse( &self, idx: usize, error_enum_name: &Ident, error_enum_variant: &Ident, inner_parse_enum: &Ident, parse_children: TokenStream2, ) -> TokenStream2 { let error_name = self.error_name(idx); match self { Self::Static(segment) => { quote! { { let mut segments = segments.clone(); let segment = segments.next(); let segment = segment.as_deref(); if let Some(#segment) = segment { #parse_children } else { errors.push(#error_enum_name::#error_enum_variant(#inner_parse_enum::#error_name(segment.map(|s|s.to_string()).unwrap_or_default()))); } } } } Self::Dynamic(name, ty) => { let missing_error_name = self.missing_error_name().unwrap(); quote! { { let mut segments = segments.clone(); let segment = segments.next(); let parsed = if let Some(segment) = segment.as_deref() { <#ty as dioxus_router::routable::FromRouteSegment>::from_route_segment(segment).map_err(|err| #error_enum_name::#error_enum_variant(#inner_parse_enum::#error_name(err))) } else { Err(#error_enum_name::#error_enum_variant(#inner_parse_enum::#missing_error_name)) }; match parsed { Ok(#name) => { #parse_children } Err(err) => { errors.push(err); } } } } } Self::CatchAll(name, ty) => { quote! { { let parsed = { let remaining_segments: Vec<_> = segments.collect(); let mut new_segments: Vec<&str> = Vec::new(); for segment in &remaining_segments { new_segments.push(&*segment); } <#ty as dioxus_router::routable::FromRouteSegments>::from_route_segments(&new_segments).map_err(|err| #error_enum_name::#error_enum_variant(#inner_parse_enum::#error_name(err))) }; match parsed { Ok(#name) => { #parse_children } Err(err) => { errors.push(err); } } } } } } } } pub fn static_segment_idx(idx: usize) -> Ident { format_ident!("StaticSegment{}ParseError", idx) } pub fn parse_route_segments<'a>( route_span: Span, fields: impl Iterator<Item = (&'a Ident, &'a Type)> + Clone, route: &str, ) -> syn::Result<( Vec<RouteSegment>, Option<QuerySegment>, Option<HashFragment>, )> { let mut route_segments = Vec::new(); let (route_string, hash) = match route.rsplit_once('#') { Some((route, hash)) => ( route, Some(HashFragment::parse_from_str( route_span, fields.clone(), hash, )?), ), None => (route, None), }; let (route_string, query) = match route_string.rsplit_once('?') { Some((route, query)) => ( route, Some(QuerySegment::parse_from_str( route_span, fields.clone(), query, )?), ), None => (route_string, None), }; let mut iterator = route_string.split('/'); // skip the first empty segment let first = iterator.next(); if first != Some("") { return Err(syn::Error::new( route_span, format!( "Routes should start with /. Error found in the route '{}'", route ), )); } while let Some(segment) = iterator.next() { if let Some(segment) = segment.strip_prefix(':') { let spread = segment.starts_with(".."); let ident = if spread { segment[2..].to_string() } else { segment.to_string() }; let field = fields.clone().find(|(name, _)| **name == ident); let ty = if let Some(field) = field { field.1.clone() } else { return Err(syn::Error::new( route_span, format!("Could not find a field with the name '{}'", ident,), )); }; if spread { route_segments.push(RouteSegment::CatchAll( Ident::new(&ident, Span::call_site()), ty, )); if iterator.next().is_some() { return Err(syn::Error::new( route_span, "Catch-all route segments must be the last segment in a route. The route segments after the catch-all segment will never be matched.", )); } else { break; } } else { route_segments.push(RouteSegment::Dynamic( Ident::new(&ident, Span::call_site()), ty, )); } } else { route_segments.push(RouteSegment::Static(segment.to_string())); } } Ok((route_segments, query, hash)) } pub(crate) fn create_error_type( route: &str, error_name: Ident, segments: &[RouteSegment], child_type: Option<&Type>, ) -> TokenStream2 { let mut error_variants = Vec::new(); let mut display_match = Vec::new(); for (i, segment) in segments.iter().enumerate() { let error_name = segment.error_name(i); match segment { RouteSegment::Static(index) => { let comment = format!( " An error that can occur when trying to parse the static segment '/{}'.", index ); error_variants.push(quote! { #[doc = #comment] #error_name(String) }); display_match.push(quote! { Self::#error_name(found) => write!(f, "Static segment '{}' did not match instead found '{}'", #index, found)? }); } RouteSegment::Dynamic(ident, ty) => { let missing_error = segment.missing_error_name().unwrap(); let comment = format!( " An error that can occur when trying to parse the dynamic segment '/:{}'.", ident ); error_variants.push(quote! { #[doc = #comment] #error_name(<#ty as dioxus_router::routable::FromRouteSegment>::Err) }); display_match.push(quote! { Self::#error_name(err) => write!(f, "Dynamic segment '({}:{})' did not match: {}", stringify!(#ident), stringify!(#ty), err)? }); error_variants.push(quote! { #[doc = #comment] #missing_error }); display_match.push(quote! { Self::#missing_error => write!(f, "Dynamic segment '({}:{})' was missing", stringify!(#ident), stringify!(#ty))? }); } RouteSegment::CatchAll(ident, ty) => { let comment = format!( " An error that can occur when trying to parse the catch-all segment '/:..{}'.", ident ); error_variants.push(quote! { #[doc = #comment] #error_name(<#ty as dioxus_router::routable::FromRouteSegments>::Err) }); display_match.push(quote! { Self::#error_name(err) => write!(f, "Catch-all segment '({}:{})' did not match: {}", stringify!(#ident), stringify!(#ty), err)? }); } } } let child_type_variant = child_type .map(|child_type| { let comment = format!( " An error that can occur when trying to parse the child route [`{}`].", child_type.to_token_stream() ); quote! { #[doc = #comment] ChildRoute(<#child_type as std::str::FromStr>::Err) } }) .into_iter(); let child_type_error = child_type .map(|_| { quote! { Self::ChildRoute(error) => { write!(f, "{}", error)? } } }) .into_iter(); let comment = format!( " An error that can occur when trying to parse the route variant `{}`.", route ); quote! { #[doc = #comment] #[allow(non_camel_case_types)] #[allow(clippy::derive_partial_eq_without_eq)] pub enum #error_name { #[doc = " An error that can occur when extra segments are provided after the route."] ExtraSegments(String), #(#child_type_variant,)* #(#error_variants,)* } impl ::std::fmt::Debug for #error_name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { write!(f, "{}({})", stringify!(#error_name), self) } } impl ::std::fmt::Display for #error_name { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match self { Self::ExtraSegments(segments) => { write!(f, "Found additional trailing segments: {}", segments)? }, #(#child_type_error,)* #(#display_match,)* } Ok(()) } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/effect.rs
packages/core/src/effect.rs
use crate::innerlude::ScopeOrder; use std::borrow::Borrow; use std::cell::RefCell; use std::collections::VecDeque; /// Effects will always run after all changes to the DOM have been applied. /// /// Effects are the lowest priority task in the scheduler. /// They are run after all other dirty scopes and futures have been resolved. Other dirty scopes and futures may cause the component this effect is attached to to rerun, which would update the DOM. pub(crate) struct Effect { // The scope that the effect is attached to pub(crate) order: ScopeOrder, // The callbacks that will be run when effects are rerun effect: RefCell<VecDeque<Box<dyn FnOnce() + 'static>>>, } impl Effect { pub(crate) fn new(order: ScopeOrder, f: Box<dyn FnOnce() + 'static>) -> Self { let mut effect = VecDeque::new(); effect.push_back(f); Self { order, effect: RefCell::new(effect), } } pub(crate) fn push_back(&self, f: impl FnOnce() + 'static) { self.effect.borrow_mut().push_back(Box::new(f)); } pub(crate) fn run(&self) { let mut effect = self.effect.borrow_mut(); while let Some(f) = effect.pop_front() { f(); } } } impl Ord for Effect { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.order.cmp(&other.order) } } impl PartialOrd for Effect { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl PartialEq for Effect { fn eq(&self, other: &Self) -> bool { self.order == other.order } } impl Eq for Effect {} impl Borrow<ScopeOrder> for Effect { fn borrow(&self) -> &ScopeOrder { &self.order } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/render_error.rs
packages/core/src/render_error.rs
use std::{ fmt::{Debug, Display}, sync::Arc, }; use crate::innerlude::*; /// An error that can occur while rendering a component #[derive(Debug, Clone, PartialEq)] pub enum RenderError { /// The render function returned early due to an error. /// /// We captured the error, wrapped it in an Arc, and stored it here. You can no longer modify the error, /// but you can cheaply pass it around. Error(CapturedError), /// The component was suspended Suspended(SuspendedFuture), } impl Default for RenderError { fn default() -> Self { struct RenderAbortedEarly; impl Debug for RenderAbortedEarly { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Render aborted early") } } impl Display for RenderAbortedEarly { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Render aborted early") } } impl std::error::Error for RenderAbortedEarly {} Self::Error(CapturedError(Arc::new(RenderAbortedEarly.into()))) } } impl Display for RenderError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Error(e) => write!(f, "Render aborted: {e}"), Self::Suspended(e) => write!(f, "Component suspended: {e:?}"), } } } impl From<CapturedError> for RenderError { fn from(e: CapturedError) -> Self { Self::Error(e) } } impl<E: Into<anyhow::Error>> From<E> for RenderError { fn from(e: E) -> Self { let anyhow_err = e.into(); if let Some(suspended) = anyhow_err.downcast_ref::<SuspendedFuture>() { return Self::Suspended(suspended.clone()); } if let Some(render_error) = anyhow_err.downcast_ref::<RenderError>() { return render_error.clone(); } Self::Error(CapturedError(Arc::new(anyhow_err))) } } /// An `anyhow::Error` wrapped in an `Arc` so it can be cheaply cloned and passed around. #[derive(Debug, Clone)] pub struct CapturedError(pub Arc<anyhow::Error>); impl CapturedError { /// Create a `CapturedError` from anything that implements `Display`. pub fn from_display(t: impl Display) -> Self { Self(Arc::new(anyhow::anyhow!(t.to_string()))) } /// Create a `CapturedError` from anything that implements `std::error::Error`. pub fn new<E>(error: E) -> Self where E: std::error::Error + Send + Sync + 'static, { anyhow::Error::new(error).into() } /// Create a `CapturedError` from anything that implements `Display` and `Debug`. pub fn msg<M>(t: M) -> Self where M: Display + Debug + Send + Sync + 'static, { anyhow::Error::msg(t).into() } /// Create a `CapturedError` from a boxed `std::error::Error`. pub fn from_boxed(boxed_error: Box<dyn std::error::Error + Send + Sync + 'static>) -> Self { anyhow::Error::from_boxed(boxed_error).into() } /// Returns the strong count of the underlying error. pub fn _strong_count(&self) -> usize { std::sync::Arc::strong_count(&self.0) } /// Try to unwrap the underlying error if this is the only reference to it. pub fn into_inner(self) -> Option<anyhow::Error> { Arc::try_unwrap(self.0).ok() } } #[cfg(feature = "serialize")] impl serde::Serialize for CapturedError { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(&self.0.to_string()) } } #[cfg(feature = "serialize")] impl<'de> serde::Deserialize<'de> for CapturedError { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; Ok(Self::from_display(s)) } } impl std::ops::Deref for CapturedError { type Target = anyhow::Error; fn deref(&self) -> &Self::Target { &self.0 } } impl<E: Into<anyhow::Error>> From<E> for CapturedError { fn from(e: E) -> Self { Self(Arc::new(e.into())) } } impl std::fmt::Display for CapturedError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&*self.0, f) } } impl PartialEq for CapturedError { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.0, &other.0) } } #[test] fn assert_errs_can_downcast() { fn assert_is_stderr_like<T: Send + Sync + Display + Debug>() {} assert_is_stderr_like::<RenderError>(); assert_is_stderr_like::<CapturedError>(); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/launch.rs
packages/core/src/launch.rs
//! This module contains utilities renderers use to integrate with the launch function. /// A marker trait for platform configs. We use this marker to /// make sure that the user doesn't accidentally pass in a config /// builder instead of the config pub trait LaunchConfig: 'static {} impl LaunchConfig for () {}
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/tasks.rs
packages/core/src/tasks.rs
use crate::innerlude::Effect; use crate::innerlude::ScopeOrder; use crate::innerlude::{remove_future, spawn, Runtime}; use crate::scope_context::ScopeStatus; use crate::scope_context::SuspenseLocation; use crate::ScopeId; use futures_util::task::ArcWake; use slotmap::DefaultKey; use std::marker::PhantomData; use std::sync::Arc; use std::task::Waker; use std::{cell::Cell, future::Future}; use std::{cell::RefCell, rc::Rc}; use std::{pin::Pin, task::Poll}; /// A task's unique identifier. /// /// `Task` is a unique identifier for a task that has been spawned onto the runtime. It can be used to cancel the task #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct Task { pub(crate) id: TaskId, // We add a raw pointer to make this !Send + !Sync unsend: PhantomData<*const ()>, } pub(crate) type TaskId = slotmap::DefaultKey; impl Task { /// Create a task from a raw id pub(crate) const fn from_id(id: slotmap::DefaultKey) -> Self { Self { id, unsend: PhantomData, } } /// Start a new future on the same thread as the rest of the VirtualDom. /// /// This future will not contribute to suspense resolving, so you should primarily use this for reacting to changes /// and long running tasks. /// /// Whenever the component that owns this future is dropped, the future will be dropped as well. /// /// Spawning a future onto the root scope will cause it to be dropped when the root component is dropped - which /// will only occur when the VirtualDom itself has been dropped. pub fn new(task: impl Future<Output = ()> + 'static) -> Self { spawn(task) } /// Drop the task immediately. pub fn cancel(self) { remove_future(self); } /// Pause the task. pub fn pause(&self) { self.set_active(false); } /// Resume the task. pub fn resume(&self) { self.set_active(true); } /// Check if the task is paused. pub fn paused(&self) -> bool { Runtime::with(|rt| { if let Some(task) = rt.tasks.borrow().get(self.id) { !task.active.get() } else { false } }) } /// Wake the task. #[track_caller] pub fn wake(&self) { Runtime::with(|rt| { _ = rt .sender .unbounded_send(SchedulerMsg::TaskNotified(self.id)) }) } /// Poll the task immediately. #[track_caller] pub fn poll_now(&self) -> Poll<()> { Runtime::with(|rt| rt.handle_task_wakeup(*self)) } /// Set the task as active or paused. #[track_caller] pub fn set_active(&self, active: bool) { Runtime::with(|rt| { if let Some(task) = rt.tasks.borrow().get(self.id) { let was_active = task.active.replace(active); if !was_active && active { _ = rt .sender .unbounded_send(SchedulerMsg::TaskNotified(self.id)); } } }) } } impl Runtime { /// Start a new future on the same thread as the rest of the VirtualDom. /// /// **You should generally use `spawn` instead of this method unless you specifically need to need to run a task during suspense** /// /// This future will not contribute to suspense resolving but it will run during suspense. /// /// Because this future runs during suspense, you need to be careful to work with hydration. It is not recommended to do any async IO work in this future, as it can easily cause hydration issues. However, you can use isomorphic tasks to do work that can be consistently replicated on the server and client like logging or responding to state changes. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::spawn_isomorphic; /// // ❌ Do not do requests in isomorphic tasks. It may resolve at a different time on the server and client, causing hydration issues. /// let mut state = use_signal(|| None); /// spawn_isomorphic(async move { /// state.set(Some(reqwest::get("https://api.example.com").await)); /// }); /// /// // ✅ You may wait for a signal to change and then log it /// let mut state = use_signal(|| 0); /// spawn_isomorphic(async move { /// loop { /// tokio::time::sleep(std::time::Duration::from_secs(1)).await; /// println!("State is {state}"); /// } /// }); /// ``` pub fn spawn_isomorphic( &self, scope: ScopeId, task: impl Future<Output = ()> + 'static, ) -> Task { self.spawn_task_of_type(scope, task, TaskType::Isomorphic) } /// Start a new future on the same thread as the rest of the VirtualDom. /// /// This future will not contribute to suspense resolving, so you should primarily use this for reacting to changes /// and long running tasks. /// /// Whenever the component that owns this future is dropped, the future will be dropped as well. /// /// Spawning a future onto the root scope will cause it to be dropped when the root component is dropped - which /// will only occur when the VirtualDom itself has been dropped. pub fn spawn(&self, scope: ScopeId, task: impl Future<Output = ()> + 'static) -> Task { self.spawn_task_of_type(scope, task, TaskType::ClientOnly) } fn spawn_task_of_type( &self, scope: ScopeId, task: impl Future<Output = ()> + 'static, ty: TaskType, ) -> Task { self.spawn_task_of_type_inner(scope, Box::pin(task), ty) } // a non-momorphic version of spawn_task_of_type, helps with binari sizes fn spawn_task_of_type_inner( &self, scope: ScopeId, pinned_task: Pin<Box<dyn Future<Output = ()>>>, ty: TaskType, ) -> Task { // Insert the task, temporarily holding a borrow on the tasks map let (task, task_id) = { let mut tasks = self.tasks.borrow_mut(); let mut task_id = Task::from_id(DefaultKey::default()); let mut local_task = None; tasks.insert_with_key(|key| { task_id = Task::from_id(key); let new_task = Rc::new(LocalTask { scope, active: Cell::new(true), parent: self.current_task(), task: RefCell::new(pinned_task), waker: futures_util::task::waker(Arc::new(LocalTaskHandle { id: task_id.id, tx: self.sender.clone(), })), ty: RefCell::new(ty), }); local_task = Some(new_task.clone()); new_task }); (local_task.unwrap(), task_id) }; // Get a borrow on the task, holding no borrows on the tasks map debug_assert!(self.tasks.try_borrow_mut().is_ok()); debug_assert!(task.task.try_borrow_mut().is_ok()); self.sender .unbounded_send(SchedulerMsg::TaskNotified(task_id.id)) .expect("Scheduler should exist"); task_id } /// Queue an effect to run after the next render pub(crate) fn queue_effect(&self, id: ScopeId, f: impl FnOnce() + 'static) { let effect = Box::new(f) as Box<dyn FnOnce() + 'static>; let Some(scope) = self.try_get_state(id) else { return; }; let mut status = scope.status.borrow_mut(); match &mut *status { ScopeStatus::Mounted => { self.queue_effect_on_mounted_scope(id, effect); } ScopeStatus::Unmounted { effects_queued, .. } => { effects_queued.push(effect); } } } /// Queue an effect to run after the next render without checking if the scope is mounted pub(crate) fn queue_effect_on_mounted_scope( &self, id: ScopeId, f: Box<dyn FnOnce() + 'static>, ) { // Add the effect to the queue of effects to run after the next render for the given scope let mut effects = self.pending_effects.borrow_mut(); let height = self.get_state(id).height(); let scope_order = ScopeOrder::new(height, id); match effects.get(&scope_order) { Some(effects) => effects.push_back(f), None => { effects.insert(Effect::new(scope_order, f)); } } } /// Get the currently running task pub fn current_task(&self) -> Option<Task> { self.current_task.get() } /// Get the parent task of the given task, if it exists pub fn parent_task(&self, task: Task) -> Option<Task> { self.tasks.borrow().get(task.id)?.parent } pub(crate) fn task_scope(&self, task: Task) -> Option<ScopeId> { self.tasks.borrow().get(task.id).map(|t| t.scope) } #[track_caller] pub(crate) fn handle_task_wakeup(&self, id: Task) -> Poll<()> { #[cfg(debug_assertions)] { // Ensure we are currently inside a `Runtime`. Runtime::current(); } let task = self.tasks.borrow().get(id.id).cloned(); // The task was removed from the scheduler, so we can just ignore it let Some(task) = task else { return Poll::Ready(()); }; // If a task woke up but is paused, we can just ignore it if !task.active.get() { return Poll::Pending; } let mut cx = std::task::Context::from_waker(&task.waker); // poll the future with the scope on the stack let poll_result = self.with_scope_on_stack(task.scope, || { self.current_task.set(Some(id)); let poll_result = task.task.borrow_mut().as_mut().poll(&mut cx); if poll_result.is_ready() { // Remove it from the scope so we dont try to double drop it when the scope dropes self.get_state(task.scope) .spawned_tasks .borrow_mut() .remove(&id); self.remove_task(id); } poll_result }); self.current_task.set(None); poll_result } /// Drop the future with the given Task /// /// This does not abort the task, so you'll want to wrap it in an abort handle if that's important to you pub(crate) fn remove_task(&self, id: Task) -> Option<Rc<LocalTask>> { // Remove the task from the task list let task = self.tasks.borrow_mut().remove(id.id); if let Some(task) = &task { // Remove the task from suspense if let TaskType::Suspended { boundary } = &*task.ty.borrow() { self.suspended_tasks.set(self.suspended_tasks.get() - 1); if let SuspenseLocation::UnderSuspense(boundary) = boundary { boundary.remove_suspended_task(id); } } // Remove the task from pending work. We could reuse the slot before the task is polled and discarded so we need to remove it from pending work instead of filtering out dead tasks when we try to poll them if let Some(scope) = self.try_get_state(task.scope) { let order = ScopeOrder::new(scope.height(), scope.id); if let Some(dirty_tasks) = self.dirty_tasks.borrow_mut().get(&order) { dirty_tasks.remove(id); } } } task } /// Check if a task should be run during suspense pub(crate) fn task_runs_during_suspense(&self, task: Task) -> bool { let borrow = self.tasks.borrow(); let task: Option<&LocalTask> = borrow.get(task.id).map(|t| &**t); matches!(task, Some(LocalTask { ty, .. }) if ty.borrow().runs_during_suspense()) } } /// the task itself is the waker pub(crate) struct LocalTask { scope: ScopeId, parent: Option<Task>, task: RefCell<Pin<Box<dyn Future<Output = ()> + 'static>>>, waker: Waker, ty: RefCell<TaskType>, active: Cell<bool>, } impl LocalTask { /// Suspend the task, returns true if the task was already suspended pub(crate) fn suspend(&self, boundary: SuspenseLocation) -> bool { // Make this a suspended task so it runs during suspense let old_type = self.ty.replace(TaskType::Suspended { boundary }); matches!(old_type, TaskType::Suspended { .. }) } } #[derive(Clone)] enum TaskType { ClientOnly, Suspended { boundary: SuspenseLocation }, Isomorphic, } impl TaskType { fn runs_during_suspense(&self) -> bool { matches!(self, TaskType::Isomorphic | TaskType::Suspended { .. }) } } /// The type of message that can be sent to the scheduler. /// /// These messages control how the scheduler will process updates to the UI. #[derive(Debug)] pub(crate) enum SchedulerMsg { /// All components have been marked as dirty, requiring a full render #[allow(unused)] AllDirty, /// Immediate updates from Components that mark them as dirty Immediate(ScopeId), /// A task has woken and needs to be progressed TaskNotified(slotmap::DefaultKey), /// An effect has been queued to run after the next render EffectQueued, } struct LocalTaskHandle { id: slotmap::DefaultKey, tx: futures_channel::mpsc::UnboundedSender<SchedulerMsg>, } impl ArcWake for LocalTaskHandle { fn wake_by_ref(arc_self: &Arc<Self>) { _ = arc_self .tx .unbounded_send(SchedulerMsg::TaskNotified(arc_self.id)); } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/hotreload_utils.rs
packages/core/src/hotreload_utils.rs
use std::{ any::{Any, TypeId}, hash::{Hash, Hasher}, }; #[cfg(feature = "serialize")] use crate::nodes::deserialize_string_leaky; use crate::{ Attribute, AttributeValue, DynamicNode, Template, TemplateAttribute, TemplateNode, VNode, VText, }; #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[doc(hidden)] #[derive(Debug, PartialEq, Clone)] pub struct HotreloadedLiteral { pub name: String, pub value: HotReloadLiteral, } #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[doc(hidden)] #[derive(Debug, PartialEq, Clone)] pub enum HotReloadLiteral { Fmted(FmtedSegments), Float(f64), Int(i64), Bool(bool), } impl HotReloadLiteral { pub fn as_fmted(&self) -> Option<&FmtedSegments> { match self { Self::Fmted(segments) => Some(segments), _ => None, } } pub fn as_float(&self) -> Option<f64> { match self { Self::Float(f) => Some(*f), _ => None, } } pub fn as_int(&self) -> Option<i64> { match self { Self::Int(i) => Some(*i), _ => None, } } pub fn as_bool(&self) -> Option<bool> { match self { Self::Bool(b) => Some(*b), _ => None, } } } impl Hash for HotReloadLiteral { fn hash<H: Hasher>(&self, state: &mut H) { match self { Self::Fmted(segments) => segments.hash(state), Self::Float(f) => f.to_bits().hash(state), Self::Int(i) => i.hash(state), Self::Bool(b) => b.hash(state), } } } #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[doc(hidden)] #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub struct FmtedSegments { pub(crate) segments: Vec<FmtSegment>, } impl FmtedSegments { pub fn new(segments: Vec<FmtSegment>) -> Self { Self { segments } } /// Render the formatted string by stitching together the segments pub(crate) fn render_with(&self, dynamic_text: &[String]) -> String { let mut out = String::new(); for segment in &self.segments { match segment { FmtSegment::Literal { value } => out.push_str(value), FmtSegment::Dynamic { id } => out.push_str(&dynamic_text[*id]), } } out } } type StaticStr = &'static str; #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[doc(hidden)] #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub enum FmtSegment { Literal { #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_string_leaky") )] value: StaticStr, }, Dynamic { id: usize, }, } // let __pool = DynamicValuePool::new( // vec![...], // vec![...], // vec![...], // ); // VNode::new( // None, // Template { // name: "...", // roots: &[...], // node_paths: &[..], // attr_paths: &[...], // }, // Box::new([...]), // Box::new([...]), // ) // Open questions: // - How do we handle type coercion for different sized component property integers? // - Should non-string hot literals go through the centralized pool? // - Should formatted strings be a runtime concept? #[doc(hidden)] pub struct DynamicLiteralPool { dynamic_text: Box<[String]>, } impl DynamicLiteralPool { pub fn new(dynamic_text: Vec<String>) -> Self { Self { dynamic_text: dynamic_text.into_boxed_slice(), } } // TODO: This should be marked as private in the next major release pub fn get_component_property<'a, T>( &self, id: usize, hot_reload: &'a HotReloadedTemplate, f: impl FnOnce(&'a HotReloadLiteral) -> Option<T>, ) -> Option<T> { let value = hot_reload.component_values.get(id)?; f(value) } fn get_component_property_or_default<'a, T: Default>( &self, id: usize, hot_reload: &'a HotReloadedTemplate, f: impl FnOnce(&'a HotReloadLiteral) -> Option<T>, ) -> Option<T> { // If the component was removed since the last hot reload, the hot reload template may not // have the property. If that is the case, just use a default value since the component is // never rendered. if id >= hot_reload.component_values.len() { return Some(T::default()); } self.get_component_property(id, hot_reload, f) } /// Get a component property of a specific type at the component property index pub fn component_property<T: 'static>( &mut self, id: usize, hot_reload: &HotReloadedTemplate, // We pass in the original value for better type inference // For example, if the original literal is `0i128`, we know the output must be the type `i128` _coherse_type: T, ) -> T { fn assert_type<T: 'static, T2: 'static>(t: T) -> T2 { *(Box::new(t) as Box<dyn Any>).downcast::<T2>().unwrap() } let grab_float = || { self.get_component_property_or_default(id, hot_reload, HotReloadLiteral::as_float).unwrap_or_else(|| { tracing::error!("Expected a float component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id)); Default::default() }) }; let grab_int = || { self.get_component_property_or_default(id, hot_reload, HotReloadLiteral::as_int).unwrap_or_else(|| { tracing::error!("Expected a integer component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id)); Default::default() }) }; let grab_bool = || { self.get_component_property_or_default(id, hot_reload, HotReloadLiteral::as_bool).unwrap_or_else(|| { tracing::error!("Expected a bool component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id)); Default::default() }) }; let grab_fmted = || { self.get_component_property_or_default(id, hot_reload, |fmted| HotReloadLiteral::as_fmted(fmted).map(|segments| self.render_formatted(segments))).unwrap_or_else(|| { tracing::error!("Expected a string component property, because the type was {}. The CLI gave the hot reloading engine a type of {:?}. This is probably caused by a bug in dioxus hot reloading. Please report this issue.", std::any::type_name::<T>(), hot_reload.component_values.get(id)); Default::default() }) }; match TypeId::of::<T>() { // Any string types that accept a literal _ if TypeId::of::<String>() == TypeId::of::<T>() => assert_type(grab_fmted()), _ if TypeId::of::<&str>() == TypeId::of::<T>() => { assert_type(Box::leak(grab_fmted().into_boxed_str()) as &'static str) } // Any integer types that accept a literal _ if TypeId::of::<i128>() == TypeId::of::<T>() => assert_type(grab_int() as i128), _ if TypeId::of::<i64>() == TypeId::of::<T>() => assert_type(grab_int()), _ if TypeId::of::<i32>() == TypeId::of::<T>() => assert_type(grab_int() as i32), _ if TypeId::of::<i16>() == TypeId::of::<T>() => assert_type(grab_int() as i16), _ if TypeId::of::<i8>() == TypeId::of::<T>() => assert_type(grab_int() as i8), _ if TypeId::of::<isize>() == TypeId::of::<T>() => assert_type(grab_int() as isize), _ if TypeId::of::<u128>() == TypeId::of::<T>() => assert_type(grab_int() as u128), _ if TypeId::of::<u64>() == TypeId::of::<T>() => assert_type(grab_int() as u64), _ if TypeId::of::<u32>() == TypeId::of::<T>() => assert_type(grab_int() as u32), _ if TypeId::of::<u16>() == TypeId::of::<T>() => assert_type(grab_int() as u16), _ if TypeId::of::<u8>() == TypeId::of::<T>() => assert_type(grab_int() as u8), _ if TypeId::of::<usize>() == TypeId::of::<T>() => assert_type(grab_int() as usize), // Any float types that accept a literal _ if TypeId::of::<f64>() == TypeId::of::<T>() => assert_type(grab_float()), _ if TypeId::of::<f32>() == TypeId::of::<T>() => assert_type(grab_float() as f32), // Any bool types that accept a literal _ if TypeId::of::<bool>() == TypeId::of::<T>() => assert_type(grab_bool()), _ => panic!("Unsupported component property type"), } } pub fn render_formatted(&self, segments: &FmtedSegments) -> String { segments.render_with(&self.dynamic_text) } } #[doc(hidden)] pub struct DynamicValuePool { dynamic_attributes: Box<[Box<[Attribute]>]>, dynamic_nodes: Box<[DynamicNode]>, literal_pool: DynamicLiteralPool, } impl DynamicValuePool { pub fn new( dynamic_nodes: Vec<DynamicNode>, dynamic_attributes: Vec<Box<[Attribute]>>, literal_pool: DynamicLiteralPool, ) -> Self { Self { dynamic_attributes: dynamic_attributes.into_boxed_slice(), dynamic_nodes: dynamic_nodes.into_boxed_slice(), literal_pool, } } pub fn render_with(&mut self, hot_reload: &HotReloadedTemplate) -> VNode { // Get the node_paths from a depth first traversal of the template let key = hot_reload .key .as_ref() .map(|key| self.literal_pool.render_formatted(key)); let dynamic_nodes = hot_reload .dynamic_nodes .iter() .map(|node| self.render_dynamic_node(node)) .collect(); let dynamic_attrs = hot_reload .dynamic_attributes .iter() .map(|attr| self.render_attribute(attr)) .collect(); VNode::new(key, hot_reload.template, dynamic_nodes, dynamic_attrs) } fn render_dynamic_node(&mut self, node: &HotReloadDynamicNode) -> DynamicNode { match node { // If the node is dynamic, take it from the pool and return it HotReloadDynamicNode::Dynamic(id) => self.dynamic_nodes[*id].clone(), // Otherwise, format the text node and return it HotReloadDynamicNode::Formatted(segments) => DynamicNode::Text(VText { value: self.literal_pool.render_formatted(segments), }), } } fn render_attribute(&mut self, attr: &HotReloadDynamicAttribute) -> Box<[Attribute]> { match attr { HotReloadDynamicAttribute::Dynamic(id) => self.dynamic_attributes[*id].clone(), HotReloadDynamicAttribute::Named(NamedAttribute { name, namespace, value, }) => Box::new([Attribute { name, namespace: *namespace, value: match value { HotReloadAttributeValue::Literal(HotReloadLiteral::Fmted(segments)) => { AttributeValue::Text(self.literal_pool.render_formatted(segments)) } HotReloadAttributeValue::Literal(HotReloadLiteral::Float(f)) => { AttributeValue::Float(*f) } HotReloadAttributeValue::Literal(HotReloadLiteral::Int(i)) => { AttributeValue::Int(*i) } HotReloadAttributeValue::Literal(HotReloadLiteral::Bool(b)) => { AttributeValue::Bool(*b) } HotReloadAttributeValue::Dynamic(id) => { self.dynamic_attributes[*id][0].value.clone() } }, volatile: false, }]), } } } #[doc(hidden)] #[derive(Debug, Clone, PartialEq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub struct HotReloadTemplateWithLocation { pub key: TemplateGlobalKey, pub template: HotReloadedTemplate, } #[doc(hidden)] #[derive(Debug, Clone, PartialEq, Hash, PartialOrd, Eq, Ord)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub struct TemplateGlobalKey { pub file: String, pub line: usize, pub column: usize, pub index: usize, } type StaticTemplateArray = &'static [TemplateNode]; #[doc(hidden)] #[derive(Debug, PartialEq, Clone)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub struct HotReloadedTemplate { pub key: Option<FmtedSegments>, pub dynamic_nodes: Vec<HotReloadDynamicNode>, pub dynamic_attributes: Vec<HotReloadDynamicAttribute>, pub component_values: Vec<HotReloadLiteral>, #[cfg_attr( feature = "serialize", serde(deserialize_with = "crate::nodes::deserialize_leaky") )] pub roots: StaticTemplateArray, /// The template that is computed from the hot reload roots template: Template, } impl HotReloadedTemplate { pub fn new( key: Option<FmtedSegments>, dynamic_nodes: Vec<HotReloadDynamicNode>, dynamic_attributes: Vec<HotReloadDynamicAttribute>, component_values: Vec<HotReloadLiteral>, roots: &'static [TemplateNode], ) -> Self { let node_paths = Self::node_paths(roots); let attr_paths = Self::attr_paths(roots); let template = Template { roots, node_paths, attr_paths, }; Self { key, dynamic_nodes, dynamic_attributes, component_values, roots, template, } } fn node_paths(roots: &'static [TemplateNode]) -> &'static [&'static [u8]] { fn add_node_paths( roots: &[TemplateNode], node_paths: &mut Vec<&'static [u8]>, current_path: Vec<u8>, ) { for (idx, node) in roots.iter().enumerate() { let mut path = current_path.clone(); path.push(idx as u8); match node { TemplateNode::Element { children, .. } => { add_node_paths(children, node_paths, path); } TemplateNode::Text { .. } => {} TemplateNode::Dynamic { id } => { debug_assert_eq!(node_paths.len(), *id); node_paths.push(Box::leak(path.into_boxed_slice())); } } } } let mut node_paths = Vec::new(); add_node_paths(roots, &mut node_paths, Vec::new()); let leaked: &'static [&'static [u8]] = Box::leak(node_paths.into_boxed_slice()); leaked } fn attr_paths(roots: &'static [TemplateNode]) -> &'static [&'static [u8]] { fn add_attr_paths( roots: &[TemplateNode], attr_paths: &mut Vec<&'static [u8]>, current_path: Vec<u8>, ) { for (idx, node) in roots.iter().enumerate() { let mut path = current_path.clone(); path.push(idx as u8); if let TemplateNode::Element { children, attrs, .. } = node { for attr in *attrs { if let TemplateAttribute::Dynamic { id } = attr { debug_assert_eq!(attr_paths.len(), *id); attr_paths.push(Box::leak(path.clone().into_boxed_slice())); } } add_attr_paths(children, attr_paths, path); } } } let mut attr_paths = Vec::new(); add_attr_paths(roots, &mut attr_paths, Vec::new()); let leaked: &'static [&'static [u8]] = Box::leak(attr_paths.into_boxed_slice()); leaked } } #[doc(hidden)] #[derive(Debug, PartialEq, Clone, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub enum HotReloadDynamicNode { Dynamic(usize), Formatted(FmtedSegments), } #[doc(hidden)] #[derive(Debug, PartialEq, Clone, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub enum HotReloadDynamicAttribute { Dynamic(usize), Named(NamedAttribute), } #[doc(hidden)] #[derive(Debug, PartialEq, Clone, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub struct NamedAttribute { /// The name of this attribute. #[cfg_attr( feature = "serialize", serde(deserialize_with = "crate::nodes::deserialize_string_leaky") )] name: StaticStr, /// The namespace of this attribute. Does not exist in the HTML spec #[cfg_attr( feature = "serialize", serde(deserialize_with = "crate::nodes::deserialize_option_leaky") )] namespace: Option<StaticStr>, value: HotReloadAttributeValue, } impl NamedAttribute { pub fn new( name: &'static str, namespace: Option<&'static str>, value: HotReloadAttributeValue, ) -> Self { Self { name, namespace, value, } } } #[doc(hidden)] #[derive(Debug, PartialEq, Clone, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] pub enum HotReloadAttributeValue { Literal(HotReloadLiteral), Dynamic(usize), }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/lib.rs
packages/core/src/lib.rs
#![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")] #![warn(missing_docs)] mod any_props; mod arena; mod diff; mod effect; mod error_boundary; mod events; mod fragment; mod generational_box; mod global_context; mod launch; mod mutations; mod nodes; mod properties; mod reactive_context; mod render_error; mod root_wrapper; mod runtime; mod scheduler; mod scope_arena; mod scope_context; mod scopes; mod suspense; mod tasks; mod virtual_dom; mod hotreload_utils; /// Items exported from this module are used in macros and should not be used directly. #[doc(hidden)] pub mod internal { #[doc(hidden)] pub use crate::hotreload_utils::{ DynamicLiteralPool, DynamicValuePool, FmtSegment, FmtedSegments, HotReloadAttributeValue, HotReloadDynamicAttribute, HotReloadDynamicNode, HotReloadLiteral, HotReloadTemplateWithLocation, HotReloadedTemplate, HotreloadedLiteral, NamedAttribute, TemplateGlobalKey, }; #[allow(non_snake_case)] #[doc(hidden)] pub fn Err<T, E>(e: E) -> Result<T, E> { std::result::Result::Err(e) } pub use anyhow::__anyhow; #[doc(hidden)] pub use generational_box; } pub(crate) mod innerlude { pub(crate) use crate::any_props::*; pub use crate::arena::*; pub(crate) use crate::effect::*; pub use crate::error_boundary::*; pub use crate::events::*; pub use crate::fragment::*; pub use crate::generational_box::*; pub use crate::global_context::*; pub use crate::launch::*; pub use crate::mutations::*; pub use crate::nodes::*; pub use crate::properties::*; pub use crate::reactive_context::*; pub use crate::render_error::*; pub use crate::runtime::{Runtime, RuntimeGuard}; pub use crate::scheduler::*; pub use crate::scopes::*; pub use crate::suspense::*; pub use crate::tasks::*; pub use crate::virtual_dom::*; pub use anyhow::anyhow; pub use anyhow::Context as AnyhowContext; // pub use anyhow::Error as AnyhowError; // pub type Error = CapturedError; /// A result type with a default error of [`CapturedError`]. pub type Result<T, E = CapturedError> = std::result::Result<T, E>; /// An [`Element`] is a possibly-none [`VNode`] created by calling `render` on [`ScopeId`] or [`ScopeState`]. /// /// An Errored [`Element`] will propagate the error to the nearest error boundary. pub type Element = std::result::Result<VNode, RenderError>; /// A [`Component`] is a function that takes [`Properties`] and returns an [`Element`]. pub type Component<P = ()> = fn(P) -> Element; } pub use crate::innerlude::{ anyhow, consume_context, consume_context_from_scope, current_owner, current_scope_id, fc_to_builder, generation, has_context, needs_update, needs_update_any, parent_scope, provide_context, provide_create_error_boundary, provide_root_context, queue_effect, remove_future, schedule_update, schedule_update_any, spawn, spawn_forever, spawn_isomorphic, suspend, throw_error, try_consume_context, use_after_render, use_before_render, use_drop, use_hook, use_hook_with_cleanup, with_owner, AnyValue, AnyhowContext, Attribute, AttributeValue, Callback, CapturedError, Component, ComponentFunction, DynamicNode, Element, ElementId, ErrorBoundary, ErrorContext, Event, EventHandler, Fragment, HasAttributes, IntoAttributeValue, IntoDynNode, LaunchConfig, ListenerCallback, MarkerWrapper, Mutation, Mutations, NoOpMutations, OptionStringFromMarker, Properties, ReactiveContext, RenderError, Result, Runtime, RuntimeGuard, ScopeId, ScopeState, SpawnIfAsync, SubscriberList, Subscribers, SuperFrom, SuperInto, SuspendedFuture, SuspenseBoundary, SuspenseBoundaryProps, SuspenseContext, Task, Template, TemplateAttribute, TemplateNode, VComponent, VNode, VNodeInner, VPlaceholder, VText, VirtualDom, WriteMutations, }; /// Equivalent to `Ok::<_, dioxus::CapturedError>(value)`. /// /// This simplifies creation of an `dioxus::Result` in places where type /// inference cannot deduce the `E` type of the result &mdash; without needing /// to write`Ok::<_, dioxus::CapturedError>(value)`. /// /// One might think that `dioxus::Result::Ok(value)` would work in such cases /// but it does not. /// /// ```console /// error[E0282]: type annotations needed for `std::result::Result<i32, E>` /// --> src/main.rs:11:13 /// | /// 11 | let _ = dioxus::Result::Ok(1); /// | - ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result` /// | | /// | consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified /// ``` #[allow(non_snake_case)] pub fn Ok<T>(value: T) -> Result<T, CapturedError> { Result::Ok(value) } pub use const_format;
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/properties.rs
packages/core/src/properties.rs
use std::fmt::Arguments; use crate::innerlude::*; /// Every "Props" used for a component must implement the `Properties` trait. This trait gives some hints to Dioxus /// on how to memoize the props and some additional optimizations that can be made. We strongly encourage using the /// derive macro to implement the `Properties` trait automatically. /// /// Dioxus requires your props to be 'static, `Clone`, and `PartialEq`. We use the `PartialEq` trait to determine if /// the props have changed when we diff the component. /// /// ## Example /// /// ```rust /// # use dioxus::prelude::*; /// #[derive(Props, PartialEq, Clone)] /// struct MyComponentProps { /// data: String /// } /// /// fn MyComponent(props: MyComponentProps) -> Element { /// rsx! { /// div { "Hello {props.data}" } /// } /// } /// ``` /// /// Or even better, derive your entire props struct with the [`#[crate::component]`] macro: /// /// ```rust /// # use dioxus::prelude::*; /// #[component] /// fn MyComponent(data: String) -> Element { /// rsx! { /// div { "Hello {data}" } /// } /// } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`Props` is not implemented for `{Self}`", label = "Props", note = "Props is a trait that is automatically implemented for all structs that can be used as props for a component", note = "If you manually created a new properties struct, you may have forgotten to add `#[derive(Props, PartialEq, Clone)]` to your struct", ) )] pub trait Properties: Clone + Sized + 'static { /// The type of the builder for this component. /// Used to create "in-progress" versions of the props. type Builder; /// Create a builder for this component. fn builder() -> Self::Builder; /// Make the old props equal to the new props. Return if the props were equal and should be memoized. fn memoize(&mut self, other: &Self) -> bool; /// Create a component from the props. fn into_vcomponent<M: 'static>(self, render_fn: impl ComponentFunction<Self, M>) -> VComponent { let type_name = std::any::type_name_of_val(&render_fn); VComponent::new(render_fn, self, type_name) } } impl Properties for () { type Builder = EmptyBuilder; fn builder() -> Self::Builder { EmptyBuilder {} } fn memoize(&mut self, _other: &Self) -> bool { true } } /// Root properties never need to be memoized, so we can use a dummy implementation. pub(crate) struct RootProps<P>(pub P); impl<P> Clone for RootProps<P> where P: Clone, { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<P> Properties for RootProps<P> where P: Clone + 'static, { type Builder = P; fn builder() -> Self::Builder { unreachable!("Root props technically are never built") } fn memoize(&mut self, _other: &Self) -> bool { true } } // We allow components to use the () generic parameter if they have no props. This impl enables the "build" method // that the macros use to anonymously complete prop construction. pub struct EmptyBuilder; impl EmptyBuilder { pub fn build(self) {} } /// This utility function launches the builder method so that the rsx! macro can use the typed-builder pattern /// to initialize a component's props. pub fn fc_to_builder<P, M>(_: impl ComponentFunction<P, M>) -> <P as Properties>::Builder where P: Properties, { P::builder() } /// Any component that implements the `ComponentFn` trait can be used as a component. /// /// This trait is automatically implemented for functions that are in one of the following forms: /// - `fn() -> Element` /// - `fn(props: Properties) -> Element` /// /// You can derive it automatically for any function with arguments that implement PartialEq with the `#[component]` attribute: /// ```rust /// # use dioxus::prelude::*; /// #[component] /// fn MyComponent(a: u32, b: u32) -> Element { /// rsx! { "a: {a}, b: {b}" } /// } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`Component<{Props}>` is not implemented for `{Self}`", label = "Component", note = "Components are functions in the form `fn() -> Element`, `fn(props: Properties) -> Element`, or `#[component] fn(partial_eq1: u32, partial_eq2: u32) -> Element`.", note = "You may have forgotten to add `#[component]` to your function to automatically implement the `ComponentFunction` trait." ) )] pub trait ComponentFunction<Props, Marker = ()>: Clone + 'static { /// Get the raw address of the component render function. fn fn_ptr(&self) -> usize; /// Convert the component to a function that takes props and returns an element. fn rebuild(&self, props: Props) -> Element; } /// Accept any callbacks that take props impl<F, P> ComponentFunction<P> for F where F: Fn(P) -> Element + Clone + 'static, { fn rebuild(&self, props: P) -> Element { subsecond::HotFn::current(self.clone()).call((props,)) } fn fn_ptr(&self) -> usize { subsecond::HotFn::current(self.clone()).ptr_address().0 as usize } } /// Accept any callbacks that take no props pub struct EmptyMarker; impl<F> ComponentFunction<(), EmptyMarker> for F where F: Fn() -> Element + Clone + 'static, { fn rebuild(&self, props: ()) -> Element { subsecond::HotFn::current(self.clone()).call(props) } fn fn_ptr(&self) -> usize { subsecond::HotFn::current(self.clone()).ptr_address().0 as usize } } /// A enhanced version of the `Into` trait that allows with more flexibility. pub trait SuperInto<O, M = ()> { /// Convert from a type to another type. fn super_into(self) -> O; } impl<T, O, M> SuperInto<O, M> for T where O: SuperFrom<T, M>, { fn super_into(self) -> O { O::super_from(self) } } /// A enhanced version of the `From` trait that allows with more flexibility. pub trait SuperFrom<T, M = ()> { /// Convert from a type to another type. fn super_from(_: T) -> Self; } // first implement for all types that are that implement the From trait impl<T, O> SuperFrom<T, ()> for O where O: From<T>, { fn super_from(input: T) -> Self { Self::from(input) } } #[doc(hidden)] pub struct OptionStringFromMarker; impl<'a> SuperFrom<&'a str, OptionStringFromMarker> for Option<String> { fn super_from(input: &'a str) -> Self { Some(String::from(input)) } } #[doc(hidden)] pub struct OptionArgumentsFromMarker; impl<'a> SuperFrom<Arguments<'a>, OptionArgumentsFromMarker> for Option<String> { fn super_from(input: Arguments<'a>) -> Self { Some(input.to_string()) } } #[doc(hidden)] pub struct OptionCallbackMarker<T>(std::marker::PhantomData<T>); // Closure can be created from FnMut -> async { anything } or FnMut -> Ret impl< Function: FnMut(Args) -> Spawn + 'static, Args: 'static, Spawn: SpawnIfAsync<Marker, Ret> + 'static, Ret: 'static, Marker, > SuperFrom<Function, OptionCallbackMarker<Marker>> for Option<Callback<Args, Ret>> { fn super_from(input: Function) -> Self { Some(Callback::new(input)) } } #[test] #[allow(unused)] fn optional_callback_compiles() { fn compiles() { // Converting from closures (without type hints in the closure works) let callback: Callback<i32, i32> = (|num| num * num).super_into(); let callback: Callback<i32, ()> = (|num| async move { println!("{num}") }).super_into(); // Converting from closures to optional callbacks works let optional: Option<Callback<i32, i32>> = (|num| num * num).super_into(); let optional: Option<Callback<i32, ()>> = (|num| async move { println!("{num}") }).super_into(); } } #[test] #[allow(unused)] fn from_props_compiles() { // T -> T works let option: i32 = 0i32.super_into(); let option: i32 = 0.super_into(); // Note we don't need type hints on all inputs let option: i128 = 0.super_into(); let option: &'static str = "hello world".super_into(); // // T -> From<T> works let option: i64 = 0i32.super_into(); let option: String = "hello world".super_into(); // T -> Option works let option: Option<i32> = 0i32.super_into(); let option: Option<i32> = 0.super_into(); let option: Option<i128> = 0.super_into(); fn takes_option_string<M>(_: impl SuperInto<Option<String>, M>) {} takes_option_string("hello world"); takes_option_string("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/packages/core/src/root_wrapper.rs
packages/core/src/root_wrapper.rs
use crate::{ fc_to_builder, properties::RootProps, DynamicNode, Element, ErrorBoundary, Properties, SuspenseBoundary, Template, TemplateNode, VComponent, VNode, }; // We wrap the root scope in a component that renders it inside a default ErrorBoundary and SuspenseBoundary #[allow(non_snake_case)] #[allow(clippy::let_and_return)] pub(crate) fn RootScopeWrapper(props: RootProps<VComponent>) -> Element { static TEMPLATE: Template = Template { roots: &[TemplateNode::Dynamic { id: 0usize }], node_paths: &[&[0u8]], attr_paths: &[], }; Element::Ok(VNode::new( None, TEMPLATE, Box::new([DynamicNode::Component( fc_to_builder(SuspenseBoundary) .fallback(|_| Element::Ok(VNode::placeholder())) .children(Ok(VNode::new( None, TEMPLATE, Box::new([DynamicNode::Component({ fc_to_builder(ErrorBoundary) .children(Element::Ok(VNode::new( None, TEMPLATE, Box::new([DynamicNode::Component(props.0)]), Box::new([]), ))) .build() .into_vcomponent(ErrorBoundary) })]), Box::new([]), ))) .build() .into_vcomponent(SuspenseBoundary), )]), Box::new([]), )) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/error_boundary.rs
packages/core/src/error_boundary.rs
use crate::{ innerlude::{provide_context, CapturedError}, try_consume_context, use_hook, Element, IntoDynNode, Properties, ReactiveContext, Subscribers, Template, TemplateAttribute, TemplateNode, VNode, }; use std::{ any::Any, cell::RefCell, fmt::{Debug, Display}, rc::Rc, }; /// Return early with an error. #[macro_export] macro_rules! bail { ($msg:literal $(,)?) => { return $crate::internal::Err($crate::internal::__anyhow!($msg).into()) }; ($err:expr $(,)?) => { return $crate::internal::Err($crate::internal::__anyhow!($err).into()) }; ($fmt:expr, $($arg:tt)*) => { return $crate::internal::Err($crate::internal::__anyhow!($fmt, $($arg)*).into()) }; } /// A panic in a component that was caught by an error boundary. /// /// <div class="warning"> /// /// WASM currently does not support caching unwinds, so this struct will not be created in WASM. /// /// </div> pub(crate) struct CapturedPanic(pub(crate) Box<dyn Any + Send + 'static>); unsafe impl Sync for CapturedPanic {} impl std::error::Error for CapturedPanic {} impl Debug for CapturedPanic { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("CapturedPanic").finish() } } impl Display for CapturedPanic { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_fmt(format_args!("Encountered panic: {:?}", self.0)) } } /// A context supplied by fullstack to create hydration compatible error boundaries. Generally, this /// is not present and the default in memory error boundary is used. If fullstack is enabled, it will /// provide its own factory that handles syncing errors to the hydration context #[derive(Clone, Copy)] struct CreateErrorBoundary(fn() -> ErrorContext); impl Default for CreateErrorBoundary { fn default() -> Self { Self(|| ErrorContext::new(None)) } } /// Provides a method that is used to create error boundaries in `use_error_boundary_provider`. /// This is only called from fullstack to create a hydration compatible error boundary #[doc(hidden)] pub fn provide_create_error_boundary(create_error_boundary: fn() -> ErrorContext) { provide_context(CreateErrorBoundary(create_error_boundary)); } /// Create an error boundary with the current error boundary factory (either hydration compatible or default) fn create_error_boundary() -> ErrorContext { let create_error_boundary = try_consume_context::<CreateErrorBoundary>().unwrap_or_default(); (create_error_boundary.0)() } /// Provide an error boundary to catch errors from child components. This needs to called in a hydration comptable /// order if fullstack is enabled pub fn use_error_boundary_provider() -> ErrorContext { use_hook(|| provide_context(create_error_boundary())) } /// A context with information about suspended components #[derive(Clone)] pub struct ErrorContext { error: Rc<RefCell<Option<CapturedError>>>, subscribers: Subscribers, } impl Debug for ErrorContext { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ErrorContext") .field("error", &self.error) .finish() } } impl PartialEq for ErrorContext { fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.error, &other.error) } } impl ErrorContext { /// Create a new suspense boundary in a specific scope pub fn new(error: Option<CapturedError>) -> Self { Self { error: Rc::new(RefCell::new(error)), subscribers: Subscribers::new(), } } /// Get the current error, if any. If multiple components have errored, this will return the first /// error that made it to this boundary. pub fn error(&self) -> Option<CapturedError> { // Subscribe to the current reactive context if one exists. This is usually // the error boundary component that is rendering the errors if let Some(rc) = ReactiveContext::current() { self.subscribers.add(rc); } self.error.borrow().clone() } /// Push an error into this Error Boundary pub fn insert_error(&self, error: CapturedError) { self.error.borrow_mut().replace(error); self.mark_dirty() } /// Clear all errors from this Error Boundary pub fn clear_errors(&self) { self.error.borrow_mut().take(); self.mark_dirty(); } /// Mark the error context as dirty and notify all subscribers fn mark_dirty(&self) { let mut this_subscribers_vec = Vec::new(); self.subscribers .visit(|subscriber| this_subscribers_vec.push(*subscriber)); for subscriber in this_subscribers_vec { self.subscribers.remove(&subscriber); subscriber.mark_dirty(); } } } #[allow(clippy::type_complexity)] #[derive(Clone)] pub struct ErrorHandler(Rc<dyn Fn(ErrorContext) -> Element>); impl<F: Fn(ErrorContext) -> Element + 'static> From<F> for ErrorHandler { fn from(value: F) -> Self { Self(Rc::new(value)) } } fn default_handler(errors: ErrorContext) -> Element { static TEMPLATE: Template = Template { roots: &[TemplateNode::Element { tag: "div", namespace: None, attrs: &[TemplateAttribute::Static { name: "color", namespace: Some("style"), value: "red", }], children: &[TemplateNode::Dynamic { id: 0usize }], }], node_paths: &[&[0u8, 0u8]], attr_paths: &[], }; std::result::Result::Ok(VNode::new( None, TEMPLATE, Box::new([errors .error() .iter() .map(|e| { static TEMPLATE: Template = Template { roots: &[TemplateNode::Element { tag: "pre", namespace: None, attrs: &[], children: &[TemplateNode::Dynamic { id: 0usize }], }], node_paths: &[&[0u8, 0u8]], attr_paths: &[], }; VNode::new( None, TEMPLATE, Box::new([e.to_string().into_dyn_node()]), Default::default(), ) }) .into_dyn_node()]), Default::default(), )) } #[derive(Clone)] pub struct ErrorBoundaryProps { children: Element, handle_error: ErrorHandler, } /// Create a new error boundary component that catches any errors thrown from child components /// /// ## Details /// /// Error boundaries handle errors within a specific part of your application. They are similar to `try/catch` in JavaScript, but they only catch errors in the tree below them. /// Any errors passed up from a child will be caught by the nearest error boundary. Error boundaries are quick to implement, but it can be useful to individually handle errors /// in your components to provide a better user experience when you know that an error is likely to occur. /// /// ## Example /// /// ```rust, no_run /// use dioxus::prelude::*; /// /// fn App() -> Element { /// let mut multiplier = use_signal(|| String::from("2")); /// rsx! { /// input { /// r#type: "text", /// value: multiplier, /// oninput: move |e| multiplier.set(e.value()) /// } /// ErrorBoundary { /// handle_error: |errors: ErrorContext| { /// rsx! { /// div { /// "Oops, we encountered an error. Please report {errors:?} to the developer of this application" /// } /// } /// }, /// Counter { /// multiplier /// } /// } /// } /// } /// /// #[component] /// fn Counter(multiplier: ReadSignal<String>) -> Element { /// let multiplier_parsed = multiplier().parse::<usize>()?; /// let mut count = use_signal(|| multiplier_parsed); /// rsx! { /// button { /// onclick: move |_| { /// let multiplier_parsed = multiplier().parse::<usize>()?; /// *count.write() *= multiplier_parsed; /// Ok(()) /// }, /// "{count}x{multiplier}" /// } /// } /// } /// ``` /// /// ## Resetting the error boundary /// /// Once the error boundary catches an error, it will render the rsx returned from the handle_error function instead of the children. To reset the error boundary, /// you can call the [`ErrorContext::clear_errors`] method. This will clear all errors and re-render the children. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// fn App() -> Element { /// let mut multiplier = use_signal(|| String::new()); /// rsx! { /// input { /// r#type: "text", /// value: multiplier, /// oninput: move |e| multiplier.set(e.value()) /// } /// ErrorBoundary { /// handle_error: |errors: ErrorContext| { /// rsx! { /// div { /// "Oops, we encountered an error. Please report {errors:?} to the developer of this application" /// } /// button { /// onclick: move |_| { /// errors.clear_errors(); /// }, /// "try again" /// } /// } /// }, /// Counter { /// multiplier /// } /// } /// } /// } /// /// #[component] /// fn Counter(multiplier: ReadSignal<String>) -> Element { /// let multiplier_parsed = multiplier().parse::<usize>()?; /// let mut count = use_signal(|| multiplier_parsed); /// rsx! { /// button { /// onclick: move |_| { /// let multiplier_parsed = multiplier().parse::<usize>()?; /// *count.write() *= multiplier_parsed; /// Ok(()) /// }, /// "{count}x{multiplier}" /// } /// } /// } /// ``` #[allow(non_upper_case_globals, non_snake_case)] pub fn ErrorBoundary(props: ErrorBoundaryProps) -> Element { let error_boundary = use_error_boundary_provider(); let errors = error_boundary.error(); let has_errors = errors.is_some(); // Drop errors before running user code that might borrow the error lock drop(errors); if has_errors { (props.handle_error.0)(error_boundary.clone()) } else { std::result::Result::Ok({ static TEMPLATE: Template = Template { roots: &[TemplateNode::Dynamic { id: 0usize }], node_paths: &[&[0u8]], attr_paths: &[], }; VNode::new( None, TEMPLATE, Box::new([(props.children).into_dyn_node()]), Default::default(), ) }) } } impl ErrorBoundaryProps { /** Create a builder for building `ErrorBoundaryProps`. On the builder, call `.children(...)`(optional), `.handle_error(...)`(optional) to set the values of the fields. Finally, call `.build()` to create the instance of `ErrorBoundaryProps`. */ #[allow(dead_code)] pub fn builder() -> ErrorBoundaryPropsBuilder<((), ())> { ErrorBoundaryPropsBuilder { fields: ((), ()) } } } #[must_use] #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub struct ErrorBoundaryPropsBuilder<TypedBuilderFields> { fields: TypedBuilderFields, } impl<TypedBuilderFields> Clone for ErrorBoundaryPropsBuilder<TypedBuilderFields> where TypedBuilderFields: Clone, { fn clone(&self) -> Self { Self { fields: self.fields.clone(), } } } impl Properties for ErrorBoundaryProps { type Builder = ErrorBoundaryPropsBuilder<((), ())>; fn builder() -> Self::Builder { ErrorBoundaryProps::builder() } fn memoize(&mut self, other: &Self) -> bool { *self = other.clone(); false } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub trait ErrorBoundaryPropsBuilder_Optional<T> { fn into_value<F: FnOnce() -> T>(self, default: F) -> T; } impl<T> ErrorBoundaryPropsBuilder_Optional<T> for () { fn into_value<F: FnOnce() -> T>(self, default: F) -> T { default() } } impl<T> ErrorBoundaryPropsBuilder_Optional<T> for (T,) { fn into_value<F: FnOnce() -> T>(self, _: F) -> T { self.0 } } #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__handle_error> ErrorBoundaryPropsBuilder<((), __handle_error)> { pub fn children( self, children: Element, ) -> ErrorBoundaryPropsBuilder<((Element,), __handle_error)> { let children = (children,); let (_, handle_error) = self.fields; ErrorBoundaryPropsBuilder { fields: (children, handle_error), } } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_children {} #[doc(hidden)] #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__handle_error> ErrorBoundaryPropsBuilder<((Element,), __handle_error)> { #[deprecated(note = "Repeated field children")] pub fn children( self, _: ErrorBoundaryPropsBuilder_Error_Repeated_field_children, ) -> ErrorBoundaryPropsBuilder<((Element,), __handle_error)> { self } } #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__children> ErrorBoundaryPropsBuilder<(__children, ())> { pub fn handle_error( self, handle_error: impl ::core::convert::Into<ErrorHandler>, ) -> ErrorBoundaryPropsBuilder<(__children, (ErrorHandler,))> { let handle_error = (handle_error.into(),); let (children, _) = self.fields; ErrorBoundaryPropsBuilder { fields: (children, handle_error), } } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub enum ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error {} #[doc(hidden)] #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__children> ErrorBoundaryPropsBuilder<(__children, (ErrorHandler,))> { #[deprecated(note = "Repeated field handle_error")] pub fn handle_error( self, _: ErrorBoundaryPropsBuilder_Error_Repeated_field_handle_error, ) -> ErrorBoundaryPropsBuilder<(__children, (ErrorHandler,))> { self } } #[allow(dead_code, non_camel_case_types, missing_docs)] impl< __handle_error: ErrorBoundaryPropsBuilder_Optional<ErrorHandler>, __children: ErrorBoundaryPropsBuilder_Optional<Element>, > ErrorBoundaryPropsBuilder<(__children, __handle_error)> { pub fn build(self) -> ErrorBoundaryProps { let (children, handle_error) = self.fields; let children = ErrorBoundaryPropsBuilder_Optional::into_value(children, VNode::empty); let handle_error = ErrorBoundaryPropsBuilder_Optional::into_value(handle_error, || { ErrorHandler(Rc::new(default_handler)) }); ErrorBoundaryProps { children, handle_error, } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/fragment.rs
packages/core/src/fragment.rs
use crate::innerlude::*; /// Create inline fragments using Component syntax. /// /// ## Details /// /// Fragments capture a series of children without rendering extra nodes. /// /// Creating fragments explicitly with the Fragment component is particularly useful when rendering lists or tables and /// a key is needed to identify each item. /// /// ## Example /// /// ```rust /// # use dioxus::prelude::*; /// let value = 1; /// rsx! { /// Fragment { key: "{value}" } /// }; /// ``` /// /// ## Usage /// /// Fragments are incredibly useful when necessary, but *do* add cost in the diffing phase. /// Try to avoid highly nested fragments if you can. Unlike React, there is no protection against infinitely nested fragments. /// /// This function defines a dedicated `Fragment` component that can be used to create inline fragments in the RSX macro. /// /// You want to use this free-function when your fragment needs a key and simply returning multiple nodes from rsx! won't cut it. #[allow(non_upper_case_globals, non_snake_case)] pub fn Fragment(cx: FragmentProps) -> Element { cx.0 } #[derive(Clone, PartialEq)] pub struct FragmentProps(pub(crate) Element); pub struct FragmentBuilder<const BUILT: bool>(Element); impl FragmentBuilder<false> { pub fn children(self, children: Element) -> FragmentBuilder<true> { FragmentBuilder(children) } } impl<const A: bool> FragmentBuilder<A> { pub fn build(self) -> FragmentProps { FragmentProps(self.0) } } /// Access the children elements passed into the component /// /// This enables patterns where a component is passed children from its parent. /// /// ## Details /// /// Unlike React, Dioxus allows *only* lists of children to be passed from parent to child - not arbitrary functions /// or classes. If you want to generate nodes instead of accepting them as a list, consider declaring a closure /// on the props that takes Context. /// /// If a parent passes children into a component, the child will always re-render when the parent re-renders. In other /// words, a component cannot be automatically memoized if it borrows nodes from its parent, even if the component's /// props are valid for the static lifetime. /// /// ## Example /// /// ```rust /// # use dioxus::prelude::*; /// fn app() -> Element { /// rsx! { /// CustomCard { /// h1 {} /// p {} /// } /// } /// } /// /// #[component] /// fn CustomCard(children: Element) -> Element { /// rsx! { /// div { /// h1 {"Title card"} /// {children} /// } /// } /// } /// ``` impl Properties for FragmentProps { type Builder = FragmentBuilder<false>; fn builder() -> Self::Builder { FragmentBuilder(VNode::empty()) } fn memoize(&mut self, new: &Self) -> bool { let equal = self == new; if !equal { let new_clone = new.clone(); self.0 = new_clone.0; } equal } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/arena.rs
packages/core/src/arena.rs
use crate::innerlude::ScopeOrder; use crate::{virtual_dom::VirtualDom, ScopeId}; /// An Element's unique identifier. /// /// `ElementId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is /// unmounted, then the `ElementId` will be reused for a new component. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct ElementId(pub usize); /// An Element that can be bubbled to's unique identifier. /// /// `BubbleId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is /// unmounted, then the `BubbleId` will be reused for a new component. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(crate) struct MountId(pub(crate) usize); impl Default for MountId { fn default() -> Self { Self::PLACEHOLDER } } impl MountId { pub(crate) const PLACEHOLDER: Self = Self(usize::MAX); pub(crate) fn as_usize(self) -> Option<usize> { if self.mounted() { Some(self.0) } else { None } } #[allow(unused)] pub(crate) fn mounted(self) -> bool { self != Self::PLACEHOLDER } } #[derive(Debug, Clone, Copy)] pub struct ElementRef { // the pathway of the real element inside the template pub(crate) path: ElementPath, // The actual element pub(crate) mount: MountId, } #[derive(Clone, Copy, Debug)] pub struct ElementPath { pub(crate) path: &'static [u8], } impl VirtualDom { pub(crate) fn next_element(&mut self) -> ElementId { let mut elements = self.runtime.elements.borrow_mut(); ElementId(elements.insert(None)) } pub(crate) fn reclaim(&mut self, el: ElementId) { if !self.try_reclaim(el) { tracing::error!("cannot reclaim {:?}", el); } } pub(crate) fn try_reclaim(&mut self, el: ElementId) -> bool { // We never reclaim the unmounted elements or the root element if el.0 == 0 || el.0 == usize::MAX { return true; } let mut elements = self.runtime.elements.borrow_mut(); elements.try_remove(el.0).is_some() } // Drop a scope without dropping its children // // Note: This will not remove any ids from the arena pub(crate) fn drop_scope(&mut self, id: ScopeId) { let height = { let scope = self.scopes.remove(id.0); let context = scope.state(); context.height }; self.dirty_scopes.remove(&ScopeOrder::new(height, id)); // If this scope was a suspense boundary, remove it from the resolved scopes self.resolved_scopes.retain(|s| s != &id); } } impl ElementPath { pub(crate) fn is_descendant(&self, small: &[u8]) -> bool { small.len() <= self.path.len() && small == &self.path[..small.len()] } } #[test] fn is_descendant() { let event_path = ElementPath { path: &[1, 2, 3, 4, 5], }; assert!(event_path.is_descendant(&[1, 2, 3, 4, 5])); assert!(event_path.is_descendant(&[1, 2, 3, 4])); assert!(event_path.is_descendant(&[1, 2, 3])); assert!(event_path.is_descendant(&[1, 2])); assert!(event_path.is_descendant(&[1])); assert!(!event_path.is_descendant(&[1, 2, 3, 4, 5, 6])); assert!(!event_path.is_descendant(&[2, 3, 4])); } impl PartialEq<&[u8]> for ElementPath { fn eq(&self, other: &&[u8]) -> bool { self.path.eq(*other) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/mutations.rs
packages/core/src/mutations.rs
use crate::{arena::ElementId, AttributeValue, Template}; /// Something that can handle the mutations that are generated by the diffing process and apply them to the Real DOM /// /// This object provides a bunch of important information for a renderer to use patch the Real Dom with the state of the /// VirtualDom. This includes the scopes that were modified, the templates that were discovered, and a list of changes /// in the form of a [`Mutation`]. /// /// These changes are specific to one subtree, so to patch multiple subtrees, you'd need to handle each set separately. /// /// Templates, however, apply to all subtrees, not just target subtree. /// /// Mutations are the only link between the RealDOM and the VirtualDOM. pub trait WriteMutations { /// Add these m children to the target element /// /// Id: The ID of the element being mounted to /// M: The number of nodes on the stack to append to the target element fn append_children(&mut self, id: ElementId, m: usize); /// Assign the element at the given path the target ElementId. /// /// The path is in the form of a list of indices based on children. Templates cannot have more than 255 children per /// element, hence the use of a single byte. /// /// Path: The path of the child of the topmost node on the stack. A path of `[]` represents the topmost node. A path of `[0]` represents the first child. `[0,1,2]` represents 1st child's 2nd child's 3rd child. /// Id: The ID we're assigning to this element/placeholder. This will be used later to modify the element or replace it with another element. fn assign_node_id(&mut self, path: &'static [u8], id: ElementId); /// Create a placeholder in the DOM that we will use later. /// /// Dioxus currently requires the use of placeholders to maintain a re-entrance point for things like list diffing /// /// Id: The ID we're assigning to this element/placeholder. This will be used later to modify the element or replace it with another element. fn create_placeholder(&mut self, id: ElementId); /// Create a node specifically for text with the given value /// /// Value: The text content of this text node /// Id: The ID we're assigning to this specific text nodes. This will be used later to modify the element or replace it with another element. fn create_text_node(&mut self, value: &str, id: ElementId); /// Load and clone an existing node from a template saved under that specific name /// /// Dioxus guarantees that the renderer will have already been provided the template. /// When the template is picked up in the template list, it should be saved under its "name" - here, the name /// /// Name: The unique "name" of the template based on the template location. When paired with `rsx!`, this is autogenerated /// Index: The index root we loading from the template. The template is stored as a list of nodes. This index represents the position of that root /// Id: The ID we're assigning to this element being loaded from the template (This will be used later to move the element around in lists) fn load_template(&mut self, template: Template, index: usize, id: ElementId); /// Replace the target element (given by its ID) with the topmost m nodes on the stack /// /// id: The ID of the node we're going to replace with new nodes /// m: The number of nodes on the stack to replace the target element with fn replace_node_with(&mut self, id: ElementId, m: usize); /// Replace an existing element in the template at the given path with the m nodes on the stack /// /// Path: The path of the child of the topmost node on the stack. A path of `[]` represents the topmost node. A path of `[0]` represents the first child. `[0,1,2]` represents 1st child's 2nd child's 3rd child. /// M: The number of nodes on the stack to replace the target element with fn replace_placeholder_with_nodes(&mut self, path: &'static [u8], m: usize); /// Insert a number of nodes after a given node. /// /// Id: The ID of the node to insert after. /// M: The number of nodes on the stack to insert after the target node. fn insert_nodes_after(&mut self, id: ElementId, m: usize); /// Insert a number of nodes before a given node. /// /// Id: The ID of the node to insert before. /// M: The number of nodes on the stack to insert before the target node. fn insert_nodes_before(&mut self, id: ElementId, m: usize); /// Set the value of a node's attribute. /// /// Name: The name of the attribute to set. /// NS: The (optional) namespace of the attribute. For instance, "style" is in the "style" namespace. /// Value: The value of the attribute. /// Id: The ID of the node to set the attribute of. fn set_attribute( &mut self, name: &'static str, ns: Option<&'static str>, value: &AttributeValue, id: ElementId, ); /// Set the text content of a node. /// /// Value: The textcontent of the node /// Id: The ID of the node to set the textcontent of. fn set_node_text(&mut self, value: &str, id: ElementId); /// Create a new Event Listener. /// /// Name: The name of the event to listen for. /// Id: The ID of the node to attach the listener to. fn create_event_listener(&mut self, name: &'static str, id: ElementId); /// Remove an existing Event Listener. /// /// Name: The name of the event to remove. /// Id: The ID of the node to remove. fn remove_event_listener(&mut self, name: &'static str, id: ElementId); /// Remove a particular node from the DOM /// /// Id: The ID of the node to remove. fn remove_node(&mut self, id: ElementId); /// Push the given root node onto our stack. /// /// Id: The ID of the root node to push. fn push_root(&mut self, id: ElementId); } /// A `Mutation` represents a single instruction for the renderer to use to modify the UI tree to match the state /// of the Dioxus VirtualDom. /// /// These edits can be serialized and sent over the network or through any interface #[derive(Debug, PartialEq)] pub enum Mutation { /// Add these m children to the target element AppendChildren { /// The ID of the element being mounted to id: ElementId, /// The number of nodes on the stack to append to the target element m: usize, }, /// Assign the element at the given path the target ElementId. /// /// The path is in the form of a list of indices based on children. Templates cannot have more than 255 children per /// element, hence the use of a single byte. AssignId { /// The path of the child of the topmost node on the stack /// /// A path of `[]` represents the topmost node. A path of `[0]` represents the first child. /// `[0,1,2]` represents 1st child's 2nd child's 3rd child. path: &'static [u8], /// The ID we're assigning to this element/placeholder. /// /// This will be used later to modify the element or replace it with another element. id: ElementId, }, /// Create a placeholder in the DOM that we will use later. /// /// Dioxus currently requires the use of placeholders to maintain a re-entrance point for things like list diffing CreatePlaceholder { /// The ID we're assigning to this element/placeholder. /// /// This will be used later to modify the element or replace it with another element. id: ElementId, }, /// Create a node specifically for text with the given value CreateTextNode { /// The text content of this text node value: String, /// The ID we're assigning to this specific text nodes /// /// This will be used later to modify the element or replace it with another element. id: ElementId, }, /// Load and clone an existing node from a template with a given ID /// /// Dioxus guarantees that the renderer will have already been provided the template. /// When the template is picked up in the template list, it should be saved under its "name" - here, the name LoadTemplate { /// Which root are we loading from the template? /// /// The template is stored as a list of nodes. This index represents the position of that root index: usize, /// The ID we're assigning to this element being loaded from the template /// /// This will be used later to move the element around in lists id: ElementId, }, /// Replace the target element (given by its ID) with the topmost m nodes on the stack ReplaceWith { /// The ID of the node we're going to replace with id: ElementId, /// The number of nodes on the stack to replace the target element with m: usize, }, /// Replace an existing element in the template at the given path with the m nodes on the stack ReplacePlaceholder { /// The path of the child of the topmost node on the stack /// /// A path of `[]` represents the topmost node. A path of `[0]` represents the first child. /// `[0,1,2]` represents 1st child's 2nd child's 3rd child. path: &'static [u8], /// The number of nodes on the stack to replace the target element with m: usize, }, /// Insert a number of nodes after a given node. InsertAfter { /// The ID of the node to insert after. id: ElementId, /// The number of nodes on the stack to insert after the target node. m: usize, }, /// Insert a number of nodes before a given node. InsertBefore { /// The ID of the node to insert before. id: ElementId, /// The number of nodes on the stack to insert before the target node. m: usize, }, /// Set the value of a node's attribute. SetAttribute { /// The name of the attribute to set. name: &'static str, /// The (optional) namespace of the attribute. /// For instance, "style" is in the "style" namespace. ns: Option<&'static str>, /// The value of the attribute. value: AttributeValue, /// The ID of the node to set the attribute of. id: ElementId, }, /// Set the textcontent of a node. SetText { /// The textcontent of the node value: String, /// The ID of the node to set the textcontent of. id: ElementId, }, /// Create a new Event Listener. NewEventListener { /// The name of the event to listen for. name: String, /// The ID of the node to attach the listener to. id: ElementId, }, /// Remove an existing Event Listener. RemoveEventListener { /// The name of the event to remove. name: String, /// The ID of the node to remove. id: ElementId, }, /// Remove a particular node from the DOM Remove { /// The ID of the node to remove. id: ElementId, }, /// Push the given root node onto our stack. PushRoot { /// The ID of the root node to push. id: ElementId, }, } /// A static list of mutations that can be applied to the DOM. Note: this list does not contain any `Any` attribute values #[derive(Debug, PartialEq, Default)] pub struct Mutations { /// Any mutations required to patch the renderer to match the layout of the VirtualDom pub edits: Vec<Mutation>, } impl WriteMutations for Mutations { fn append_children(&mut self, id: ElementId, m: usize) { self.edits.push(Mutation::AppendChildren { id, m }) } fn assign_node_id(&mut self, path: &'static [u8], id: ElementId) { self.edits.push(Mutation::AssignId { path, id }) } fn create_placeholder(&mut self, id: ElementId) { self.edits.push(Mutation::CreatePlaceholder { id }) } fn create_text_node(&mut self, value: &str, id: ElementId) { self.edits.push(Mutation::CreateTextNode { value: value.into(), id, }) } fn load_template(&mut self, _template: Template, index: usize, id: ElementId) { self.edits.push(Mutation::LoadTemplate { index, id }) } fn replace_node_with(&mut self, id: ElementId, m: usize) { self.edits.push(Mutation::ReplaceWith { id, m }) } fn replace_placeholder_with_nodes(&mut self, path: &'static [u8], m: usize) { self.edits.push(Mutation::ReplacePlaceholder { path, m }) } fn insert_nodes_after(&mut self, id: ElementId, m: usize) { self.edits.push(Mutation::InsertAfter { id, m }) } fn insert_nodes_before(&mut self, id: ElementId, m: usize) { self.edits.push(Mutation::InsertBefore { id, m }) } fn set_attribute( &mut self, name: &'static str, ns: Option<&'static str>, value: &AttributeValue, id: ElementId, ) { self.edits.push(Mutation::SetAttribute { name, ns, value: match value { AttributeValue::Text(s) => AttributeValue::Text(s.clone()), AttributeValue::Bool(b) => AttributeValue::Bool(*b), AttributeValue::Float(n) => AttributeValue::Float(*n), AttributeValue::Int(n) => AttributeValue::Int(*n), AttributeValue::None => AttributeValue::None, _ => panic!("Cannot serialize attribute value"), }, id, }) } fn set_node_text(&mut self, value: &str, id: ElementId) { self.edits.push(Mutation::SetText { value: value.into(), id, }) } fn create_event_listener(&mut self, name: &'static str, id: ElementId) { self.edits.push(Mutation::NewEventListener { name: name.into(), id, }) } fn remove_event_listener(&mut self, name: &'static str, id: ElementId) { self.edits.push(Mutation::RemoveEventListener { name: name.into(), id, }) } fn remove_node(&mut self, id: ElementId) { self.edits.push(Mutation::Remove { id }) } fn push_root(&mut self, id: ElementId) { self.edits.push(Mutation::PushRoot { id }) } } /// A struct that ignores all mutations pub struct NoOpMutations; impl WriteMutations for NoOpMutations { fn append_children(&mut self, _: ElementId, _: usize) {} fn assign_node_id(&mut self, _: &'static [u8], _: ElementId) {} fn create_placeholder(&mut self, _: ElementId) {} fn create_text_node(&mut self, _: &str, _: ElementId) {} fn load_template(&mut self, _: Template, _: usize, _: ElementId) {} fn replace_node_with(&mut self, _: ElementId, _: usize) {} fn replace_placeholder_with_nodes(&mut self, _: &'static [u8], _: usize) {} fn insert_nodes_after(&mut self, _: ElementId, _: usize) {} fn insert_nodes_before(&mut self, _: ElementId, _: usize) {} fn set_attribute( &mut self, _: &'static str, _: Option<&'static str>, _: &AttributeValue, _: ElementId, ) { } fn set_node_text(&mut self, _: &str, _: ElementId) {} fn create_event_listener(&mut self, _: &'static str, _: ElementId) {} fn remove_event_listener(&mut self, _: &'static str, _: ElementId) {} fn remove_node(&mut self, _: ElementId) {} fn push_root(&mut self, _: ElementId) {} }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/runtime.rs
packages/core/src/runtime.rs
use crate::nodes::VNodeMount; use crate::scheduler::ScopeOrder; use crate::scope_context::SuspenseLocation; use crate::{arena::ElementRef, CapturedError}; use crate::{ innerlude::{DirtyTasks, Effect}, SuspenseContext, }; use crate::{ innerlude::{LocalTask, SchedulerMsg}, scope_context::Scope, scopes::ScopeId, Task, }; use crate::{AttributeValue, ElementId, Event}; use generational_box::{AnyStorage, Owner}; use slab::Slab; use slotmap::DefaultKey; use std::any::Any; use std::collections::BTreeSet; use std::{ cell::{Cell, Ref, RefCell}, rc::Rc, }; use tracing::instrument; thread_local! { static RUNTIMES: RefCell<Vec<Rc<Runtime>>> = const { RefCell::new(vec![]) }; } /// A global runtime that is shared across all scopes that provides the async runtime and context API pub struct Runtime { // We use this to track the current scope // This stack should only be modified through [`Runtime::with_scope_on_stack`] to ensure that the stack is correctly restored scope_stack: RefCell<Vec<ScopeId>>, // We use this to track the current suspense location. Generally this lines up with the scope stack, but it may be different for children of a suspense boundary // This stack should only be modified through [`Runtime::with_suspense_location`] to ensure that the stack is correctly restored suspense_stack: RefCell<Vec<SuspenseLocation>>, // A hand-rolled slab of scope states pub(crate) scope_states: RefCell<Vec<Option<Scope>>>, // We use this to track the current task pub(crate) current_task: Cell<Option<Task>>, /// Tasks created with cx.spawn pub(crate) tasks: RefCell<slotmap::SlotMap<DefaultKey, Rc<LocalTask>>>, // Currently suspended tasks pub(crate) suspended_tasks: Cell<usize>, pub(crate) rendering: Cell<bool>, pub(crate) sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>, // The effects that need to be run after the next render pub(crate) pending_effects: RefCell<BTreeSet<Effect>>, // Tasks that are waiting to be polled pub(crate) dirty_tasks: RefCell<BTreeSet<DirtyTasks>>, // The element ids that are used in the renderer // These mark a specific place in a whole rsx block pub(crate) elements: RefCell<Slab<Option<ElementRef>>>, // Once nodes are mounted, the information about where they are mounted is stored here // We need to store this information on the virtual dom so that we know what nodes are mounted where when we bubble events // Each mount is associated with a whole rsx block. [`VirtualDom::elements`] link to a specific node in the block pub(crate) mounts: RefCell<Slab<VNodeMount>>, } impl Runtime { pub(crate) fn new(sender: futures_channel::mpsc::UnboundedSender<SchedulerMsg>) -> Rc<Self> { let mut elements = Slab::default(); // the root element is always given element ID 0 since it's the container for the entire tree elements.insert(None); Rc::new(Self { sender, rendering: Cell::new(false), scope_states: Default::default(), scope_stack: Default::default(), suspense_stack: Default::default(), current_task: Default::default(), tasks: Default::default(), suspended_tasks: Default::default(), pending_effects: Default::default(), dirty_tasks: Default::default(), elements: RefCell::new(elements), mounts: Default::default(), }) } /// Get the current runtime pub fn current() -> Rc<Self> { RUNTIMES .with(|stack| stack.borrow().last().cloned()) .unwrap_or_else(|| { panic!( "Must be called from inside a Dioxus runtime. Help: Some APIs in dioxus require a global runtime to be present. If you are calling one of these APIs from outside of a dioxus runtime (typically in a web-sys closure or dynamic library), you will need to grab the runtime from a scope that has it and then move it into your new scope with a runtime guard. For example, if you are trying to use dioxus apis from a web-sys closure, you can grab the runtime from the scope it is created in: ```rust use dioxus::prelude::*; static COUNT: GlobalSignal<i32> = Signal::global(|| 0); #[component] fn MyComponent() -> Element {{ use_effect(|| {{ // Grab the runtime from the MyComponent scope let runtime = Runtime::current().expect(\"Components run in the Dioxus runtime\"); // Move the runtime into the web-sys closure scope let web_sys_closure = Closure::new(|| {{ // Then create a guard to provide the runtime to the closure let _guard = RuntimeGuard::new(runtime); // and run whatever code needs the runtime tracing::info!(\"The count is: {{COUNT}}\"); }}); }}) }} ```" ) }) } /// Try to get the current runtime, returning None if it doesn't exist (outside the context of a dioxus app) pub fn try_current() -> Option<Rc<Self>> { RUNTIMES.with(|stack| stack.borrow().last().cloned()) } /// Wrap a closure so that it always runs in the runtime that is currently active pub fn wrap_closure<'a, I, O>(f: impl Fn(I) -> O + 'a) -> impl Fn(I) -> O + 'a { let current_runtime = Self::current(); move |input| match current_runtime.try_current_scope_id() { Some(scope) => current_runtime.in_scope(scope, || f(input)), None => { let _runtime_guard = RuntimeGuard::new(current_runtime.clone()); f(input) } } } /// Run a closure with the rendering flag set to true pub(crate) fn while_rendering<T>(&self, f: impl FnOnce() -> T) -> T { self.rendering.set(true); let result = f(); self.rendering.set(false); result } /// Run a closure with the rendering flag set to false pub(crate) fn while_not_rendering<T>(&self, f: impl FnOnce() -> T) -> T { let previous = self.rendering.get(); self.rendering.set(false); let result = f(); self.rendering.set(previous); result } /// Create a scope context. This slab is synchronized with the scope slab. pub(crate) fn create_scope(&self, context: Scope) { let id = context.id; let mut scopes = self.scope_states.borrow_mut(); if scopes.len() <= id.0 { scopes.resize_with(id.0 + 1, Default::default); } scopes[id.0] = Some(context); } pub(crate) fn remove_scope(self: &Rc<Self>, id: ScopeId) { { let borrow = self.scope_states.borrow(); if let Some(scope) = &borrow[id.0] { // Manually drop tasks, hooks, and contexts inside of the runtime self.in_scope(id, || { // Drop all spawned tasks - order doesn't matter since tasks don't rely on eachother // In theory nested tasks might not like this for id in scope.spawned_tasks.take() { self.remove_task(id); } // Drop all queued effects self.pending_effects .borrow_mut() .remove(&ScopeOrder::new(scope.height, scope.id)); // Drop all hooks in reverse order in case a hook depends on another hook. for hook in scope.hooks.take().drain(..).rev() { drop(hook); } // Drop all contexts scope.shared_contexts.take(); }); } } self.scope_states.borrow_mut()[id.0].take(); } /// Get the owner for the current scope. #[track_caller] pub fn current_owner<S: AnyStorage>(&self) -> Owner<S> { self.get_state(self.current_scope_id()).owner() } /// Get the owner for the current scope. #[track_caller] pub fn scope_owner<S: AnyStorage>(&self, scope: ScopeId) -> Owner<S> { self.get_state(scope).owner() } /// Get the current scope id pub fn current_scope_id(&self) -> ScopeId { self.scope_stack.borrow().last().copied().unwrap() } /// Try to get the current scope id, returning None if it we aren't actively inside a scope pub fn try_current_scope_id(&self) -> Option<ScopeId> { self.scope_stack.borrow().last().copied() } /// Call this function with the current scope set to the given scope #[track_caller] pub fn in_scope<O>(self: &Rc<Self>, id: ScopeId, f: impl FnOnce() -> O) -> O { let _runtime_guard = RuntimeGuard::new(self.clone()); { self.push_scope(id); } let o = f(); { self.pop_scope(); } o } /// Get the current suspense location pub(crate) fn current_suspense_location(&self) -> Option<SuspenseLocation> { self.suspense_stack.borrow().last().cloned() } /// Run a callback a [`SuspenseLocation`] at the top of the stack pub(crate) fn with_suspense_location<O>( &self, suspense_location: SuspenseLocation, f: impl FnOnce() -> O, ) -> O { self.suspense_stack.borrow_mut().push(suspense_location); let o = f(); self.suspense_stack.borrow_mut().pop(); o } /// Run a callback with the current scope at the top of the stack pub(crate) fn with_scope_on_stack<O>(&self, scope: ScopeId, f: impl FnOnce() -> O) -> O { self.push_scope(scope); let o = f(); self.pop_scope(); o } /// Push a scope onto the stack fn push_scope(&self, scope: ScopeId) { let suspense_location = self .scope_states .borrow() .get(scope.0) .and_then(|s| s.as_ref()) .map(|s| s.suspense_location()) .unwrap_or_default(); self.suspense_stack.borrow_mut().push(suspense_location); self.scope_stack.borrow_mut().push(scope); } /// Pop a scope off the stack fn pop_scope(&self) { self.scope_stack.borrow_mut().pop(); self.suspense_stack.borrow_mut().pop(); } /// Get the state for any scope given its ID /// /// This is useful for inserting or removing contexts from a scope, or rendering out its root node pub(crate) fn get_state(&self, id: ScopeId) -> Ref<'_, Scope> { Ref::filter_map(self.scope_states.borrow(), |scopes| { scopes.get(id.0).and_then(|f| f.as_ref()) }) .ok() .unwrap() } /// Get the state for any scope given its ID /// /// This is useful for inserting or removing contexts from a scope, or rendering out its root node pub(crate) fn try_get_state(&self, id: ScopeId) -> Option<Ref<'_, Scope>> { Ref::filter_map(self.scope_states.borrow(), |contexts| { contexts.get(id.0).and_then(|f| f.as_ref()) }) .ok() } /// Pushes a new scope onto the stack pub(crate) fn push(runtime: Rc<Runtime>) { RUNTIMES.with(|stack| stack.borrow_mut().push(runtime)); } /// Pops a scope off the stack pub(crate) fn pop() { RUNTIMES.with(|stack| stack.borrow_mut().pop().unwrap()); } /// Runs a function with the current runtime pub(crate) fn with<R>(callback: impl FnOnce(&Runtime) -> R) -> R { callback(&Self::current()) } /// Runs a function with the current scope pub(crate) fn with_current_scope<R>(callback: impl FnOnce(&Scope) -> R) -> R { Self::with(|rt| Self::with_scope(rt.current_scope_id(), callback)) } /// Runs a function with the current scope pub(crate) fn with_scope<R>(scope: ScopeId, callback: impl FnOnce(&Scope) -> R) -> R { let rt = Runtime::current(); Self::in_scope(&rt, scope, || callback(&rt.get_state(scope))) } /// Finish a render. This will mark all effects as ready to run and send the render signal. pub(crate) fn finish_render(&self) { // If there are new effects we can run, send a message to the scheduler to run them (after the renderer has applied the mutations) if !self.pending_effects.borrow().is_empty() { self.sender .unbounded_send(SchedulerMsg::EffectQueued) .expect("Scheduler should exist"); } } /// Check if we should render a scope pub(crate) fn scope_should_render(&self, scope_id: ScopeId) -> bool { // If there are no suspended futures, we know the scope is not and we can skip context checks if self.suspended_tasks.get() == 0 { return true; } // If this is not a suspended scope, and we are under a frozen context, then we should let scopes = self.scope_states.borrow(); let scope = &scopes[scope_id.0].as_ref().unwrap(); !matches!(scope.suspense_location(), SuspenseLocation::UnderSuspense(suspense) if suspense.is_suspended()) } /// Call a listener inside the VirtualDom with data from outside the VirtualDom. **The ElementId passed in must be the id of an element with a listener, not a static node or a text node.** /// /// This method will identify the appropriate element. The data must match up with the listener declared. Note that /// this method does not give any indication as to the success of the listener call. If the listener is not found, /// nothing will happen. /// /// It is up to the listeners themselves to mark nodes as dirty. /// /// If you have multiple events, you can call this method multiple times before calling "render_with_deadline" #[instrument(skip(self, event), level = "trace", name = "Runtime::handle_event")] pub fn handle_event(self: &Rc<Self>, name: &str, event: Event<dyn Any>, element: ElementId) { let _runtime = RuntimeGuard::new(self.clone()); let elements = self.elements.borrow(); if let Some(Some(parent_path)) = elements.get(element.0).copied() { if event.propagates() { self.handle_bubbling_event(parent_path, name, event); } else { self.handle_non_bubbling_event(parent_path, name, event); } } } /* ------------------------ The algorithm works by walking through the list of dynamic attributes, checking their paths, and breaking when we find the target path. With the target path, we try and move up to the parent until there is no parent. Due to how bubbling works, we call the listeners before walking to the parent. If we wanted to do capturing, then we would accumulate all the listeners and call them in reverse order. ---------------------- For a visual demonstration, here we present a tree on the left and whether or not a listener is collected on the right. | <-- yes (is ascendant) | | | <-- no (is not direct ascendant) | | <-- yes (is ascendant) | | | | | <--- target element, break early, don't check other listeners | | | <-- no, broke early | <-- no, broke early */ #[instrument( skip(self, uievent), level = "trace", name = "VirtualDom::handle_bubbling_event" )] fn handle_bubbling_event(&self, parent: ElementRef, name: &str, uievent: Event<dyn Any>) { let mounts = self.mounts.borrow(); // If the event bubbles, we traverse through the tree until we find the target element. // Loop through each dynamic attribute (in a depth first order) in this template before moving up to the template's parent. let mut parent = Some(parent); while let Some(path) = parent { let mut listeners = vec![]; let Some(mount) = mounts.get(path.mount.0) else { // If the node is suspended and not mounted, we can just ignore the event return; }; let el_ref = &mount.node; let node_template = el_ref.template; let target_path = path.path; // Accumulate listeners into the listener list bottom to top for (idx, this_path) in node_template.attr_paths.iter().enumerate() { let attrs = &*el_ref.dynamic_attrs[idx]; for attr in attrs.iter() { // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one if attr.name.get(2..) == Some(name) && target_path.is_descendant(this_path) { listeners.push(&attr.value); // Break if this is the exact target element. // This means we won't call two listeners with the same name on the same element. This should be // documented, or be rejected from the rsx! macro outright if target_path == this_path { break; } } } } // Now that we've accumulated all the parent attributes for the target element, call them in reverse order // We check the bubble state between each call to see if the event has been stopped from bubbling tracing::event!( tracing::Level::TRACE, "Calling {} listeners", listeners.len() ); for listener in listeners.into_iter().rev() { if let AttributeValue::Listener(listener) = listener { listener.call(uievent.clone()); let metadata = uievent.metadata.borrow(); if !metadata.propagates { return; } } } let mount = el_ref.mount.get().as_usize(); parent = mount.and_then(|id| mounts.get(id).and_then(|el| el.parent)); } } /// Call an event listener in the simplest way possible without bubbling upwards #[instrument( skip(self, uievent), level = "trace", name = "VirtualDom::handle_non_bubbling_event" )] fn handle_non_bubbling_event(&self, node: ElementRef, name: &str, uievent: Event<dyn Any>) { let mounts = self.mounts.borrow(); let Some(mount) = mounts.get(node.mount.0) else { // If the node is suspended and not mounted, we can just ignore the event return; }; let el_ref = &mount.node; let node_template = el_ref.template; let target_path = node.path; for (idx, this_path) in node_template.attr_paths.iter().enumerate() { let attrs = &*el_ref.dynamic_attrs[idx]; for attr in attrs.iter() { // Remove the "on" prefix if it exists, TODO, we should remove this and settle on one // Only call the listener if this is the exact target element. if attr.name.get(2..) == Some(name) && target_path == this_path { if let AttributeValue::Listener(listener) = &attr.value { listener.call(uievent.clone()); break; } } } } } /// Consume context from the current scope pub fn consume_context<T: 'static + Clone>(&self, id: ScopeId) -> Option<T> { self.get_state(id).consume_context::<T>() } /// Consume context from the current scope pub fn consume_context_from_scope<T: 'static + Clone>(&self, scope_id: ScopeId) -> Option<T> { self.get_state(scope_id).consume_context::<T>() } /// Check if the current scope has a context pub fn has_context<T: 'static + Clone>(&self, id: ScopeId) -> Option<T> { self.get_state(id).has_context::<T>() } /// Provide context to the current scope pub fn provide_context<T: 'static + Clone>(&self, id: ScopeId, value: T) -> T { self.get_state(id).provide_context(value) } /// Get the parent of the current scope if it exists pub fn parent_scope(&self, scope: ScopeId) -> Option<ScopeId> { self.get_state(scope).parent_id() } /// Check if the current scope is a descendant of the given scope pub fn is_descendant_of(&self, us: ScopeId, other: ScopeId) -> bool { let mut current = us; while let Some(parent) = self.parent_scope(current) { if parent == other { return true; } current = parent; } false } /// Mark the current scope as dirty, causing it to re-render pub fn needs_update(&self, scope: ScopeId) { self.get_state(scope).needs_update(); } /// Get the height of the current scope pub fn height(&self, id: ScopeId) -> u32 { self.get_state(id).height } /// Throw a [`CapturedError`] into a scope. The error will bubble up to the nearest [`ErrorBoundary`](crate::ErrorBoundary) or the root of the app. /// /// # Examples /// ```rust, no_run /// # use dioxus::prelude::*; /// fn Component() -> Element { /// let request = spawn(async move { /// match reqwest::get("https://api.example.com").await { /// Ok(_) => unimplemented!(), /// // You can explicitly throw an error into a scope with throw_error /// Err(err) => dioxus::core::Runtime::current().throw_error(ScopeId::APP, err), /// } /// }); /// /// unimplemented!() /// } /// ``` pub fn throw_error(&self, id: ScopeId, error: impl Into<CapturedError> + 'static) { let error = error.into(); if let Some(cx) = self.consume_context::<crate::ErrorContext>(id) { cx.insert_error(error) } else { tracing::error!( "Tried to throw an error into an error boundary, but failed to locate a boundary: {:?}", error ) } } /// Get the suspense context the current scope is in pub fn suspense_context(&self) -> Option<SuspenseContext> { self.get_state(self.current_scope_id()) .suspense_location() .suspense_context() .cloned() } /// Force every component to be dirty and require a re-render. Used by hot-reloading. /// /// This might need to change to a different flag in the event hooks order changes within components. /// What we really need is a way to mark components as needing a complete rebuild if they were hit by changes. pub fn force_all_dirty(&self) { self.scope_states.borrow_mut().iter().for_each(|state| { if let Some(scope) = state.as_ref() { scope.needs_update(); } }); } /// Check if the virtual dom is currently rendering pub fn vdom_is_rendering(&self) -> bool { self.rendering.get() } } /// A guard for a new runtime. This must be used to override the current runtime when importing components from a dynamic library that has it's own runtime. /// /// ```rust /// use dioxus::prelude::*; /// use dioxus_core::{Runtime, RuntimeGuard}; /// /// fn main() { /// let virtual_dom = VirtualDom::new(app); /// } /// /// fn app() -> Element { /// rsx! { Component { runtime: Runtime::current() } } /// } /// /// // In a dynamic library /// #[derive(Props, Clone)] /// struct ComponentProps { /// runtime: std::rc::Rc<Runtime>, /// } /// /// impl PartialEq for ComponentProps { /// fn eq(&self, _other: &Self) -> bool { /// true /// } /// } /// /// fn Component(cx: ComponentProps) -> Element { /// use_hook(|| { /// let _guard = RuntimeGuard::new(cx.runtime.clone()); /// }); /// /// rsx! { div {} } /// } /// ``` pub struct RuntimeGuard(()); impl RuntimeGuard { /// Create a new runtime guard that sets the current Dioxus runtime. The runtime will be reset when the guard is dropped pub fn new(runtime: Rc<Runtime>) -> Self { Runtime::push(runtime); Self(()) } } impl Drop for RuntimeGuard { fn drop(&mut self) { Runtime::pop(); } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/nodes.rs
packages/core/src/nodes.rs
use crate::{ any_props::BoxedAnyProps, arena::ElementId, events::ListenerCallback, innerlude::{ElementRef, MountId, ScopeState, VProps}, properties::ComponentFunction, Element, Event, Properties, ScopeId, VirtualDom, }; use dioxus_core_types::DioxusFormattable; use std::ops::Deref; use std::rc::Rc; use std::vec; use std::{ any::{Any, TypeId}, cell::Cell, fmt::{Arguments, Debug}, }; /// The information about the #[derive(Debug)] pub(crate) struct VNodeMount { /// The parent of this node pub parent: Option<ElementRef>, /// A back link to the original node pub node: VNode, /// The IDs for the roots of this template - to be used when moving the template around and removing it from /// the actual Dom pub root_ids: Box<[ElementId]>, /// The element in the DOM that each attribute is mounted to pub(crate) mounted_attributes: Box<[ElementId]>, /// For components: This is the ScopeId the component is mounted to /// For other dynamic nodes: This is element in the DOM that each dynamic node is mounted to pub(crate) mounted_dynamic_nodes: Box<[usize]>, } /// A reference to a template along with any context needed to hydrate it /// /// The dynamic parts of the template are stored separately from the static parts. This allows faster diffing by skipping /// static parts of the template. #[derive(Debug)] pub struct VNodeInner { /// The key given to the root of this template. /// /// In fragments, this is the key of the first child. In other cases, it is the key of the root. pub key: Option<String>, /// The static nodes and static descriptor of the template pub template: Template, /// The dynamic nodes in the template pub dynamic_nodes: Box<[DynamicNode]>, /// The dynamic attribute slots in the template /// /// This is a list of positions in the template where dynamic attributes can be inserted. /// /// The inner list *must* be in the format [static named attributes, remaining dynamically named attributes]. /// /// For example: /// ```rust /// # use dioxus::prelude::*; /// let class = "my-class"; /// let attrs = vec![]; /// let color = "red"; /// /// rsx! { /// div { /// class: "{class}", /// ..attrs, /// p { /// color: "{color}", /// } /// } /// }; /// ``` /// /// Would be represented as: /// ```text /// [ /// [class, every attribute in attrs sorted by name], // Slot 0 in the template /// [color], // Slot 1 in the template /// ] /// ``` pub dynamic_attrs: Box<[Box<[Attribute]>]>, } /// A reference to a template along with any context needed to hydrate it /// /// The dynamic parts of the template are stored separately from the static parts. This allows faster diffing by skipping /// static parts of the template. #[derive(Debug, Clone)] pub struct VNode { vnode: Rc<VNodeInner>, /// The mount information for this template pub(crate) mount: Cell<MountId>, } impl Default for VNode { fn default() -> Self { Self::placeholder() } } impl PartialEq for VNode { fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.vnode, &other.vnode) } } impl Deref for VNode { type Target = VNodeInner; fn deref(&self) -> &Self::Target { &self.vnode } } impl VNode { /// Create a template with no nodes that will be skipped over during diffing pub fn empty() -> Element { Ok(Self::default()) } /// Create a template with a single placeholder node pub fn placeholder() -> Self { use std::cell::OnceCell; // We can reuse all placeholders across the same thread to save memory thread_local! { static PLACEHOLDER_VNODE: OnceCell<Rc<VNodeInner>> = const { OnceCell::new() }; } let vnode = PLACEHOLDER_VNODE.with(|cell| { cell.get_or_init(move || { Rc::new(VNodeInner { key: None, dynamic_nodes: Box::new([DynamicNode::Placeholder(Default::default())]), dynamic_attrs: Box::new([]), template: Template { roots: &[TemplateNode::Dynamic { id: 0 }], node_paths: &[&[0]], attr_paths: &[], }, }) }) .clone() }); Self { vnode, mount: Default::default(), } } /// Create a new VNode pub fn new( key: Option<String>, template: Template, dynamic_nodes: Box<[DynamicNode]>, dynamic_attrs: Box<[Box<[Attribute]>]>, ) -> Self { Self { vnode: Rc::new(VNodeInner { key, template, dynamic_nodes, dynamic_attrs, }), mount: Default::default(), } } /// Load a dynamic root at the given index /// /// Returns [`None`] if the root is actually a static node (Element/Text) pub fn dynamic_root(&self, idx: usize) -> Option<&DynamicNode> { self.template.roots[idx] .dynamic_id() .map(|id| &self.dynamic_nodes[id]) } /// Get the mounted id for a dynamic node index pub fn mounted_dynamic_node( &self, dynamic_node_idx: usize, dom: &VirtualDom, ) -> Option<ElementId> { let mount = self.mount.get().as_usize()?; match &self.dynamic_nodes[dynamic_node_idx] { DynamicNode::Text(_) | DynamicNode::Placeholder(_) => { let mounts = dom.runtime.mounts.borrow(); mounts .get(mount)? .mounted_dynamic_nodes .get(dynamic_node_idx) .map(|id| ElementId(*id)) } _ => None, } } /// Get the mounted id for a root node index pub fn mounted_root(&self, root_idx: usize, dom: &VirtualDom) -> Option<ElementId> { let mount = self.mount.get().as_usize()?; let mounts = dom.runtime.mounts.borrow(); mounts.get(mount)?.root_ids.get(root_idx).copied() } /// Get the mounted id for a dynamic attribute index pub fn mounted_dynamic_attribute( &self, dynamic_attribute_idx: usize, dom: &VirtualDom, ) -> Option<ElementId> { let mount = self.mount.get().as_usize()?; let mounts = dom.runtime.mounts.borrow(); mounts .get(mount)? .mounted_attributes .get(dynamic_attribute_idx) .copied() } /// Create a deep clone of this VNode pub(crate) fn deep_clone(&self) -> Self { Self { vnode: Rc::new(VNodeInner { key: self.vnode.key.clone(), template: self.vnode.template, dynamic_nodes: self .vnode .dynamic_nodes .iter() .map(|node| match node { DynamicNode::Fragment(nodes) => DynamicNode::Fragment( nodes.iter().map(|node| node.deep_clone()).collect(), ), other => other.clone(), }) .collect(), dynamic_attrs: self .vnode .dynamic_attrs .iter() .map(|attr| { attr.iter() .map(|attribute| attribute.deep_clone()) .collect() }) .collect(), }), mount: Default::default(), } } } type StaticStr = &'static str; type StaticPathArray = &'static [&'static [u8]]; type StaticTemplateArray = &'static [TemplateNode]; type StaticTemplateAttributeArray = &'static [TemplateAttribute]; /// A static layout of a UI tree that describes a set of dynamic and static nodes. /// /// This is the core innovation in Dioxus. Most UIs are made of static nodes, yet participate in diffing like any /// dynamic node. This struct can be created at compile time. It promises that its pointer is unique, allow Dioxus to use /// its static description of the UI to skip immediately to the dynamic nodes during diffing. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[derive(Debug, Clone, Copy, Eq, PartialOrd, Ord)] pub struct Template { /// The list of template nodes that make up the template /// /// Unlike react, calls to `rsx!` can have multiple roots. This list supports that paradigm. #[cfg_attr(feature = "serialize", serde(deserialize_with = "deserialize_leaky"))] pub roots: StaticTemplateArray, /// The paths of each node relative to the root of the template. /// /// These will be one segment shorter than the path sent to the renderer since those paths are relative to the /// topmost element, not the `roots` field. #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_bytes_leaky") )] pub node_paths: StaticPathArray, /// The paths of each dynamic attribute relative to the root of the template /// /// These will be one segment shorter than the path sent to the renderer since those paths are relative to the /// topmost element, not the `roots` field. #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_bytes_leaky", bound = "") )] pub attr_paths: StaticPathArray, } // Are identical static items merged in the current build. Rust doesn't have a cfg(merge_statics) attribute // so we have to check this manually #[allow(unpredictable_function_pointer_comparisons)] // This attribute should be removed once MSRV is 1.85 or greater and the below change is made fn static_items_merged() -> bool { fn a() {} fn b() {} a as fn() == b as fn() // std::ptr::fn_addr_eq(a as fn(), b as fn()) <<<<---- This should replace the a as fn() === b as fn() once the MSRV is 1.85 or greater } impl std::hash::Hash for Template { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { // If identical static items are merged, we can compare templates by pointer if static_items_merged() { std::ptr::hash(self.roots as *const _, state); std::ptr::hash(self.node_paths as *const _, state); std::ptr::hash(self.attr_paths as *const _, state); } // Otherwise, we hash by value else { self.roots.hash(state); self.node_paths.hash(state); self.attr_paths.hash(state); } } } impl PartialEq for Template { fn eq(&self, other: &Self) -> bool { // If identical static items are merged, we can compare templates by pointer if static_items_merged() { std::ptr::eq(self.roots as *const _, other.roots as *const _) && std::ptr::eq(self.node_paths as *const _, other.node_paths as *const _) && std::ptr::eq(self.attr_paths as *const _, other.attr_paths as *const _) } // Otherwise, we compare by value else { self.roots == other.roots && self.node_paths == other.node_paths && self.attr_paths == other.attr_paths } } } #[cfg(feature = "serialize")] pub(crate) fn deserialize_string_leaky<'a, 'de, D>( deserializer: D, ) -> Result<&'static str, D::Error> where D: serde::Deserializer<'de>, { use serde::Deserialize; let deserialized = String::deserialize(deserializer)?; Ok(&*Box::leak(deserialized.into_boxed_str())) } #[cfg(feature = "serialize")] fn deserialize_bytes_leaky<'a, 'de, D>( deserializer: D, ) -> Result<&'static [&'static [u8]], D::Error> where D: serde::Deserializer<'de>, { use serde::Deserialize; let deserialized = Vec::<Vec<u8>>::deserialize(deserializer)?; let deserialized = deserialized .into_iter() .map(|v| &*Box::leak(v.into_boxed_slice())) .collect::<Vec<_>>(); Ok(&*Box::leak(deserialized.into_boxed_slice())) } #[cfg(feature = "serialize")] pub(crate) fn deserialize_leaky<'a, 'de, T, D>(deserializer: D) -> Result<&'static [T], D::Error> where T: serde::Deserialize<'de>, D: serde::Deserializer<'de>, { use serde::Deserialize; let deserialized = Box::<[T]>::deserialize(deserializer)?; Ok(&*Box::leak(deserialized)) } #[cfg(feature = "serialize")] pub(crate) fn deserialize_option_leaky<'a, 'de, D>( deserializer: D, ) -> Result<Option<&'static str>, D::Error> where D: serde::Deserializer<'de>, { use serde::Deserialize; let deserialized = Option::<String>::deserialize(deserializer)?; Ok(deserialized.map(|deserialized| &*Box::leak(deserialized.into_boxed_str()))) } impl Template { /// Is this template worth caching at all, since it's completely runtime? /// /// There's no point in saving templates that are completely dynamic, since they'll be recreated every time anyway. pub fn is_completely_dynamic(&self) -> bool { use TemplateNode::*; self.roots.iter().all(|root| matches!(root, Dynamic { .. })) } } /// A statically known node in a layout. /// /// This can be created at compile time, saving the VirtualDom time when diffing the tree #[derive(Debug, Clone, Copy, PartialEq, Hash, Eq, PartialOrd, Ord)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), serde(tag = "type") )] pub enum TemplateNode { /// An statically known element in the dom. /// /// In HTML this would be something like `<div id="123"> </div>` Element { /// The name of the element /// /// IE for a div, it would be the string "div" #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_string_leaky") )] tag: StaticStr, /// The namespace of the element /// /// In HTML, this would be a valid URI that defines a namespace for all elements below it /// SVG is an example of this namespace #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_option_leaky") )] namespace: Option<StaticStr>, /// A list of possibly dynamic attributes for this element /// /// An attribute on a DOM node, such as `id="my-thing"` or `href="https://example.com"`. #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_leaky", bound = "") )] attrs: StaticTemplateAttributeArray, /// A list of template nodes that define another set of template nodes #[cfg_attr(feature = "serialize", serde(deserialize_with = "deserialize_leaky"))] children: StaticTemplateArray, }, /// This template node is just a piece of static text Text { /// The actual text #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_string_leaky", bound = "") )] text: StaticStr, }, /// This template node is unknown, and needs to be created at runtime. Dynamic { /// The index of the dynamic node in the VNode's dynamic_nodes list id: usize, }, } impl TemplateNode { /// Try to load the dynamic node at the given index pub fn dynamic_id(&self) -> Option<usize> { use TemplateNode::*; match self { Dynamic { id } => Some(*id), _ => None, } } } /// A node created at runtime /// /// This node's index in the DynamicNode list on VNode should match its respective `Dynamic` index #[derive(Debug, Clone)] pub enum DynamicNode { /// A component node /// /// Most of the time, Dioxus will actually know which component this is as compile time, but the props and /// assigned scope are dynamic. /// /// The actual VComponent can be dynamic between two VNodes, though, allowing implementations to swap /// the render function at runtime Component(VComponent), /// A text node Text(VText), /// A placeholder /// /// Used by suspense when a node isn't ready and by fragments that don't render anything /// /// In code, this is just an ElementId whose initial value is set to 0 upon creation Placeholder(VPlaceholder), /// A list of VNodes. /// /// Note that this is not a list of dynamic nodes. These must be VNodes and created through conditional rendering /// or iterators. Fragment(Vec<VNode>), } impl DynamicNode { /// Convert any item that implements [`IntoDynNode`] into a [`DynamicNode`] pub fn make_node<'c, I>(into: impl IntoDynNode<I> + 'c) -> DynamicNode { into.into_dyn_node() } } impl Default for DynamicNode { fn default() -> Self { Self::Placeholder(Default::default()) } } /// An instance of a child component pub struct VComponent { /// The name of this component pub name: &'static str, /// The raw pointer to the render function pub(crate) render_fn: usize, /// The props for this component pub(crate) props: BoxedAnyProps, } impl Clone for VComponent { fn clone(&self) -> Self { Self { name: self.name, props: self.props.duplicate(), render_fn: self.render_fn, } } } impl VComponent { /// Create a new [`VComponent`] variant pub fn new<P, M: 'static>( component: impl ComponentFunction<P, M>, props: P, fn_name: &'static str, ) -> Self where P: Properties + 'static, { let render_fn = component.fn_ptr(); let props = Box::new(VProps::new( component, <P as Properties>::memoize, props, fn_name, )); VComponent { render_fn, name: fn_name, props, } } /// Get the [`ScopeId`] this node is mounted to if it's mounted /// /// This is useful for rendering nodes outside of the VirtualDom, such as in SSR /// /// Returns [`None`] if the node is not mounted pub fn mounted_scope_id( &self, dynamic_node_index: usize, vnode: &VNode, dom: &VirtualDom, ) -> Option<ScopeId> { let mount = vnode.mount.get().as_usize()?; let mounts = dom.runtime.mounts.borrow(); let scope_id = mounts.get(mount)?.mounted_dynamic_nodes[dynamic_node_index]; Some(ScopeId(scope_id)) } /// Get the scope this node is mounted to if it's mounted /// /// This is useful for rendering nodes outside of the VirtualDom, such as in SSR /// /// Returns [`None`] if the node is not mounted pub fn mounted_scope<'a>( &self, dynamic_node_index: usize, vnode: &VNode, dom: &'a VirtualDom, ) -> Option<&'a ScopeState> { let mount = vnode.mount.get().as_usize()?; let mounts = dom.runtime.mounts.borrow(); let scope_id = mounts.get(mount)?.mounted_dynamic_nodes[dynamic_node_index]; dom.scopes.get(scope_id) } } impl std::fmt::Debug for VComponent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("VComponent") .field("name", &self.name) .finish() } } /// A text node #[derive(Clone, Debug)] pub struct VText { /// The actual text itself pub value: String, } impl VText { /// Create a new VText pub fn new(value: impl ToString) -> Self { Self { value: value.to_string(), } } } impl From<Arguments<'_>> for VText { fn from(args: Arguments) -> Self { Self::new(args.to_string()) } } /// A placeholder node, used by suspense and fragments #[derive(Clone, Debug, Default)] #[non_exhaustive] pub struct VPlaceholder {} /// An attribute of the TemplateNode, created at compile time #[derive(Debug, PartialEq, Hash, Eq, PartialOrd, Ord)] #[cfg_attr( feature = "serialize", derive(serde::Serialize, serde::Deserialize), serde(tag = "type") )] pub enum TemplateAttribute { /// This attribute is entirely known at compile time, enabling Static { /// The name of this attribute. /// /// For example, the `href` attribute in `href="https://example.com"`, would have the name "href" #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_string_leaky", bound = "") )] name: StaticStr, /// The value of this attribute, known at compile time /// /// Currently this only accepts &str, so values, even if they're known at compile time, are not known #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_string_leaky", bound = "") )] value: StaticStr, /// The namespace of this attribute. Does not exist in the HTML spec #[cfg_attr( feature = "serialize", serde(deserialize_with = "deserialize_option_leaky", bound = "") )] namespace: Option<StaticStr>, }, /// The attribute in this position is actually determined dynamically at runtime /// /// This is the index into the dynamic_attributes field on the container VNode Dynamic { /// The index id: usize, }, } /// An attribute on a DOM node, such as `id="my-thing"` or `href="https://example.com"` #[derive(Debug, Clone, PartialEq)] pub struct Attribute { /// The name of the attribute. pub name: &'static str, /// The value of the attribute pub value: AttributeValue, /// The namespace of the attribute. /// /// Doesn’t exist in the html spec. Used in Dioxus to denote “style” tags and other attribute groups. pub namespace: Option<&'static str>, /// An indication of we should always try and set the attribute. Used in controlled components to ensure changes are propagated pub volatile: bool, } impl Attribute { /// Create a new [`Attribute`] from a name, value, namespace, and volatile bool /// /// "Volatile" refers to whether or not Dioxus should always override the value. This helps prevent the UI in /// some renderers stay in sync with the VirtualDom's understanding of the world pub fn new<T>( name: &'static str, value: impl IntoAttributeValue<T>, namespace: Option<&'static str>, volatile: bool, ) -> Attribute { Attribute { name, namespace, volatile, value: value.into_value(), } } /// Create a new deep clone of this attribute pub(crate) fn deep_clone(&self) -> Self { Attribute { name: self.name, namespace: self.namespace, volatile: self.volatile, value: self.value.clone(), } } } /// Any of the built-in values that the Dioxus VirtualDom supports as dynamic attributes on elements /// /// These are built-in to be faster during the diffing process. To use a custom value, use the [`AttributeValue::Any`] /// variant. #[derive(Clone)] pub enum AttributeValue { /// Text attribute Text(String), /// A float Float(f64), /// Signed integer Int(i64), /// Boolean Bool(bool), /// A listener, like "onclick" Listener(ListenerCallback), /// An arbitrary value that implements PartialEq and is static Any(Rc<dyn AnyValue>), /// A "none" value, resulting in the removal of an attribute from the dom None, } impl AttributeValue { /// Create a new [`AttributeValue`] with the listener variant from a callback /// /// The callback must be confined to the lifetime of the ScopeState pub fn listener<T: 'static>(callback: impl FnMut(Event<T>) + 'static) -> AttributeValue { AttributeValue::Listener(ListenerCallback::new(callback).erase()) } /// Create a new [`AttributeValue`] with a value that implements [`AnyValue`] pub fn any_value<T: AnyValue>(value: T) -> AttributeValue { AttributeValue::Any(Rc::new(value)) } } impl std::fmt::Debug for AttributeValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Text(arg0) => f.debug_tuple("Text").field(arg0).finish(), Self::Float(arg0) => f.debug_tuple("Float").field(arg0).finish(), Self::Int(arg0) => f.debug_tuple("Int").field(arg0).finish(), Self::Bool(arg0) => f.debug_tuple("Bool").field(arg0).finish(), Self::Listener(_) => f.debug_tuple("Listener").finish(), Self::Any(_) => f.debug_tuple("Any").finish(), Self::None => write!(f, "None"), } } } impl PartialEq for AttributeValue { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Text(l0), Self::Text(r0)) => l0 == r0, (Self::Float(l0), Self::Float(r0)) => l0 == r0, (Self::Int(l0), Self::Int(r0)) => l0 == r0, (Self::Bool(l0), Self::Bool(r0)) => l0 == r0, (Self::Listener(l0), Self::Listener(r0)) => l0 == r0, (Self::Any(l0), Self::Any(r0)) => l0.as_ref().any_cmp(r0.as_ref()), (Self::None, Self::None) => true, _ => false, } } } #[doc(hidden)] pub trait AnyValue: 'static { fn any_cmp(&self, other: &dyn AnyValue) -> bool; fn as_any(&self) -> &dyn Any; fn type_id(&self) -> TypeId { self.as_any().type_id() } } impl<T: Any + PartialEq + 'static> AnyValue for T { fn any_cmp(&self, other: &dyn AnyValue) -> bool { if let Some(other) = other.as_any().downcast_ref() { self == other } else { false } } fn as_any(&self) -> &dyn Any { self } } /// A trait that allows various items to be converted into a dynamic node for the rsx macro pub trait IntoDynNode<A = ()> { /// Consume this item and produce a DynamicNode fn into_dyn_node(self) -> DynamicNode; } impl IntoDynNode for () { fn into_dyn_node(self) -> DynamicNode { DynamicNode::default() } } impl IntoDynNode for VNode { fn into_dyn_node(self) -> DynamicNode { DynamicNode::Fragment(vec![self]) } } impl IntoDynNode for DynamicNode { fn into_dyn_node(self) -> DynamicNode { self } } impl<T: IntoDynNode> IntoDynNode for Option<T> { fn into_dyn_node(self) -> DynamicNode { match self { Some(val) => val.into_dyn_node(), None => DynamicNode::default(), } } } impl IntoDynNode for &Element { fn into_dyn_node(self) -> DynamicNode { match self.as_ref() { Ok(val) => val.into_dyn_node(), _ => DynamicNode::default(), } } } impl IntoDynNode for Element { fn into_dyn_node(self) -> DynamicNode { match self { Ok(val) => val.into_dyn_node(), _ => DynamicNode::default(), } } } impl IntoDynNode for &Option<VNode> { fn into_dyn_node(self) -> DynamicNode { match self.as_ref() { Some(val) => val.clone().into_dyn_node(), _ => DynamicNode::default(), } } } impl IntoDynNode for &str { fn into_dyn_node(self) -> DynamicNode { DynamicNode::Text(VText { value: self.to_string(), }) } } impl IntoDynNode for String { fn into_dyn_node(self) -> DynamicNode { DynamicNode::Text(VText { value: self }) } } impl IntoDynNode for Arguments<'_> { fn into_dyn_node(self) -> DynamicNode { DynamicNode::Text(VText { value: self.to_string(), }) } } impl IntoDynNode for &VNode { fn into_dyn_node(self) -> DynamicNode { DynamicNode::Fragment(vec![self.clone()]) } } pub trait IntoVNode { fn into_vnode(self) -> VNode; } impl IntoVNode for VNode { fn into_vnode(self) -> VNode { self } } impl IntoVNode for &VNode { fn into_vnode(self) -> VNode { self.clone() } } impl IntoVNode for Element { fn into_vnode(self) -> VNode { match self { Ok(val) => val.into_vnode(), _ => VNode::default(), } } } impl IntoVNode for &Element { fn into_vnode(self) -> VNode { match self { Ok(val) => val.into_vnode(), _ => VNode::default(), } } } impl IntoVNode for Option<VNode> { fn into_vnode(self) -> VNode { match self { Some(val) => val.into_vnode(), _ => VNode::default(), } } } impl IntoVNode for &Option<VNode> { fn into_vnode(self) -> VNode { match self.as_ref() { Some(val) => val.clone().into_vnode(), _ => VNode::default(), } } } impl IntoVNode for Option<Element> { fn into_vnode(self) -> VNode { match self { Some(val) => val.into_vnode(), _ => VNode::default(), } } } impl IntoVNode for &Option<Element> { fn into_vnode(self) -> VNode { match self.as_ref() { Some(val) => val.clone().into_vnode(), _ => VNode::default(), } } } // Note that we're using the E as a generic but this is never crafted anyways. pub struct FromNodeIterator; impl<T, I> IntoDynNode<FromNodeIterator> for T where T: Iterator<Item = I>, I: IntoVNode, { fn into_dyn_node(self) -> DynamicNode { let children: Vec<_> = self.into_iter().map(|node| node.into_vnode()).collect(); if children.is_empty() { DynamicNode::default() } else { DynamicNode::Fragment(children) } } } /// A value that can be converted into an attribute value pub trait IntoAttributeValue<T = ()> { /// Convert into an attribute value fn into_value(self) -> AttributeValue; } impl IntoAttributeValue for AttributeValue { fn into_value(self) -> AttributeValue { self } } impl IntoAttributeValue for &str { fn into_value(self) -> AttributeValue { AttributeValue::Text(self.to_string()) } } impl IntoAttributeValue for String { fn into_value(self) -> AttributeValue { AttributeValue::Text(self) } } impl IntoAttributeValue for f32 { fn into_value(self) -> AttributeValue { AttributeValue::Float(self as _) } } impl IntoAttributeValue for f64 { fn into_value(self) -> AttributeValue { AttributeValue::Float(self) } } impl IntoAttributeValue for i8 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for i16 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for i32 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for i64 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self) } } impl IntoAttributeValue for isize { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for i128 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for u8 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for u16 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for u32 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for u64 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for usize { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for u128 { fn into_value(self) -> AttributeValue { AttributeValue::Int(self as _) } } impl IntoAttributeValue for bool { fn into_value(self) -> AttributeValue { AttributeValue::Bool(self) } } impl IntoAttributeValue for Arguments<'_> { fn into_value(self) -> AttributeValue { AttributeValue::Text(self.to_string()) } } impl IntoAttributeValue for Rc<dyn AnyValue> {
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
true
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/virtual_dom.rs
packages/core/src/virtual_dom.rs
//! # Virtual DOM Implementation for Rust //! //! This module provides the primary mechanics to create a hook-based, concurrent VDOM for Rust. use crate::properties::RootProps; use crate::root_wrapper::RootScopeWrapper; use crate::{ arena::ElementId, innerlude::{NoOpMutations, SchedulerMsg, ScopeOrder, ScopeState, VProps, WriteMutations}, runtime::{Runtime, RuntimeGuard}, scopes::ScopeId, ComponentFunction, Element, Mutations, }; use crate::{innerlude::Work, scopes::LastRenderedNode}; use crate::{Task, VComponent}; use futures_util::StreamExt; use slab::Slab; use std::collections::BTreeSet; use std::{any::Any, rc::Rc}; use tracing::instrument; /// A virtual node system that progresses user events and diffs UI trees. /// /// ## Guide /// /// Components are defined as simple functions that take [`crate::properties::Properties`] and return an [`Element`]. /// /// ```rust /// # use dioxus::prelude::*; /// /// #[derive(Props, PartialEq, Clone)] /// struct AppProps { /// title: String /// } /// /// fn app(cx: AppProps) -> Element { /// rsx!( /// div {"hello, {cx.title}"} /// ) /// } /// ``` /// /// Components may be composed to make complex apps. /// /// ```rust /// # #![allow(unused)] /// # use dioxus::prelude::*; /// /// # #[derive(Props, PartialEq, Clone)] /// # struct AppProps { /// # title: String /// # } /// /// static ROUTES: &str = ""; /// /// #[component] /// fn app(cx: AppProps) -> Element { /// rsx!( /// NavBar { routes: ROUTES } /// Title { "{cx.title}" } /// Footer {} /// ) /// } /// /// #[component] /// fn NavBar( routes: &'static str) -> Element { /// rsx! { /// div { "Routes: {routes}" } /// } /// } /// /// #[component] /// fn Footer() -> Element { /// rsx! { div { "Footer" } } /// } /// /// #[component] /// fn Title( children: Element) -> Element { /// rsx! { /// div { id: "title", {children} } /// } /// } /// ``` /// /// To start an app, create a [`VirtualDom`] and call [`VirtualDom::rebuild`] to get the list of edits required to /// draw the UI. /// /// ```rust /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// # fn app() -> Element { rsx! { div {} } } /// /// let mut vdom = VirtualDom::new(app); /// let edits = vdom.rebuild_to_vec(); /// ``` /// /// To call listeners inside the VirtualDom, call [`Runtime::handle_event`] with the appropriate event data. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// # fn app() -> Element { rsx! { div {} } } /// # let mut vdom = VirtualDom::new(app); /// # let runtime = vdom.runtime(); /// let event = Event::new(std::rc::Rc::new(0) as std::rc::Rc<dyn std::any::Any>, true); /// runtime.handle_event("onclick", event, ElementId(0)); /// ``` /// /// While no events are ready, call [`VirtualDom::wait_for_work`] to poll any futures inside the VirtualDom. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// # fn app() -> Element { rsx! { div {} } } /// # let mut vdom = VirtualDom::new(app); /// tokio::runtime::Runtime::new().unwrap().block_on(async { /// vdom.wait_for_work().await; /// }); /// ``` /// /// Once work is ready, call [`VirtualDom::render_immediate`] to compute the differences between the previous and /// current UI trees. This will write edits to a [`WriteMutations`] object you pass in that contains with edits that need to be /// handled by the renderer. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// # fn app() -> Element { rsx! { div {} } } /// # let mut vdom = VirtualDom::new(app); /// let mut mutations = Mutations::default(); /// /// vdom.render_immediate(&mut mutations); /// ``` /// /// To not wait for suspense while diffing the VirtualDom, call [`VirtualDom::render_immediate`]. /// /// /// ## Building an event loop around Dioxus: /// /// Putting everything together, you can build an event loop around Dioxus by using the methods outlined above. /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// # struct RealDom; /// # struct Event {} /// # impl RealDom { /// # fn new() -> Self { /// # Self {} /// # } /// # fn apply(&mut self) -> Mutations { /// # unimplemented!() /// # } /// # async fn wait_for_event(&mut self) -> std::rc::Rc<dyn std::any::Any> { /// # unimplemented!() /// # } /// # } /// # /// # tokio::runtime::Runtime::new().unwrap().block_on(async { /// let mut real_dom = RealDom::new(); /// /// #[component] /// fn app() -> Element { /// rsx! { /// div { "Hello World" } /// } /// } /// /// let mut dom = VirtualDom::new(app); /// /// dom.rebuild(&mut real_dom.apply()); /// /// loop { /// tokio::select! { /// _ = dom.wait_for_work() => {} /// evt = real_dom.wait_for_event() => { /// let evt = dioxus_core::Event::new(evt, true); /// dom.runtime().handle_event("onclick", evt, ElementId(0)) /// }, /// } /// /// dom.render_immediate(&mut real_dom.apply()); /// } /// # }); /// ``` /// /// ## Waiting for suspense /// /// Because Dioxus supports suspense, you can use it for server-side rendering, static site generation, and other use cases /// where waiting on portions of the UI to finish rendering is important. To wait for suspense, use the /// [`VirtualDom::wait_for_suspense`] method: /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// # fn app() -> Element { rsx! { div {} } } /// tokio::runtime::Runtime::new().unwrap().block_on(async { /// let mut dom = VirtualDom::new(app); /// /// dom.rebuild_in_place(); /// dom.wait_for_suspense().await; /// }); /// /// // Render the virtual dom /// ``` pub struct VirtualDom { pub(crate) scopes: Slab<ScopeState>, pub(crate) dirty_scopes: BTreeSet<ScopeOrder>, pub(crate) runtime: Rc<Runtime>, // The scopes that have been resolved since the last render pub(crate) resolved_scopes: Vec<ScopeId>, rx: futures_channel::mpsc::UnboundedReceiver<SchedulerMsg>, } impl VirtualDom { /// Create a new VirtualDom with a component that does not have special props. /// /// # Description /// /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders. /// /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive /// to toss out the entire tree. /// /// /// # Example /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// fn Example() -> Element { /// rsx!( div { "hello world" } ) /// } /// /// let dom = VirtualDom::new(Example); /// ``` /// /// Note: the VirtualDom is not progressed, you must either "run_with_deadline" or use "rebuild" to progress it. pub fn new(app: fn() -> Element) -> Self { Self::new_with_props(app, ()) } /// Create a new VirtualDom with the given properties for the root component. /// /// # Description /// /// Later, the props can be updated by calling "update" with a new set of props, causing a set of re-renders. /// /// This is useful when a component tree can be driven by external state (IE SSR) but it would be too expensive /// to toss out the entire tree. /// /// /// # Example /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// #[derive(PartialEq, Props, Clone)] /// struct SomeProps { /// name: &'static str /// } /// /// fn Example(cx: SomeProps) -> Element { /// rsx! { div { "hello {cx.name}" } } /// } /// /// let dom = VirtualDom::new_with_props(Example, SomeProps { name: "world" }); /// ``` /// /// Note: the VirtualDom is not progressed on creation. You must either "run_with_deadline" or use "rebuild" to progress it. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// # #[derive(PartialEq, Props, Clone)] /// # struct SomeProps { /// # name: &'static str /// # } /// # fn Example(cx: SomeProps) -> Element { /// # rsx! { div { "hello {cx.name}" } } /// # } /// let mut dom = VirtualDom::new_with_props(Example, SomeProps { name: "jane" }); /// dom.rebuild_in_place(); /// ``` pub fn new_with_props<P: Clone + 'static, M: 'static>( root: impl ComponentFunction<P, M>, root_props: P, ) -> Self { let render_fn = root.fn_ptr(); let props = VProps::new(root, |_, _| true, root_props, "Root"); Self::new_with_component(VComponent { name: "root", render_fn, props: Box::new(props), }) } /// Create a new virtualdom and build it immediately pub fn prebuilt(app: fn() -> Element) -> Self { let mut dom = Self::new(app); dom.rebuild_in_place(); dom } /// Create a new VirtualDom from a VComponent #[instrument(skip(root), level = "trace", name = "VirtualDom::new")] pub(crate) fn new_with_component(root: VComponent) -> Self { let (tx, rx) = futures_channel::mpsc::unbounded(); let mut dom = Self { rx, runtime: Runtime::new(tx), scopes: Default::default(), dirty_scopes: Default::default(), resolved_scopes: Default::default(), }; let root = VProps::new( RootScopeWrapper, |_, _| true, RootProps(root), "RootWrapper", ); dom.new_scope(Box::new(root), "app"); #[cfg(debug_assertions)] dom.register_subsecond_handler(); dom } /// Get the state for any scope given its ID /// /// This is useful for inserting or removing contexts from a scope, or rendering out its root node pub fn get_scope(&self, id: ScopeId) -> Option<&ScopeState> { self.scopes.get(id.0) } /// Get the single scope at the top of the VirtualDom tree that will always be around /// /// This scope has a ScopeId of 0 and is the root of the tree pub fn base_scope(&self) -> &ScopeState { self.get_scope(ScopeId::ROOT).unwrap() } /// Run a closure inside the dioxus runtime #[instrument(skip(self, f), level = "trace", name = "VirtualDom::in_runtime")] pub fn in_runtime<O>(&self, f: impl FnOnce() -> O) -> O { let _runtime = RuntimeGuard::new(self.runtime.clone()); f() } /// Run a closure inside a specific scope pub fn in_scope<T>(&self, scope: ScopeId, f: impl FnOnce() -> T) -> T { self.runtime.in_scope(scope, f) } /// Build the virtualdom with a global context inserted into the base scope /// /// This is useful for what is essentially dependency injection when building the app pub fn with_root_context<T: Clone + 'static>(self, context: T) -> Self { self.base_scope().state().provide_context(context); self } /// Provide a context to the root scope pub fn provide_root_context<T: Clone + 'static>(&self, context: T) { self.base_scope().state().provide_context(context); } /// Build the virtualdom with a global context inserted into the base scope /// /// This method is useful for when you want to provide a context in your app without knowing its type pub fn insert_any_root_context(&mut self, context: Box<dyn Any>) { self.base_scope().state().provide_any_context(context); } /// Mark all scopes as dirty. Each scope will be re-rendered. pub fn mark_all_dirty(&mut self) { let mut orders = vec![]; for (_idx, scope) in self.scopes.iter() { orders.push(ScopeOrder::new(scope.state().height(), scope.id())); } for order in orders { self.queue_scope(order); } } /// Manually mark a scope as requiring a re-render /// /// Whenever the Runtime "works", it will re-render this scope pub fn mark_dirty(&mut self, id: ScopeId) { let Some(scope) = self.runtime.try_get_state(id) else { return; }; tracing::event!(tracing::Level::TRACE, "Marking scope {:?} as dirty", id); let order = ScopeOrder::new(scope.height(), id); drop(scope); self.queue_scope(order); } /// Mark a task as dirty fn mark_task_dirty(&mut self, task: Task) { let Some(scope) = self.runtime.task_scope(task) else { return; }; let Some(scope) = self.runtime.try_get_state(scope) else { return; }; tracing::event!( tracing::Level::TRACE, "Marking task {:?} (spawned in {:?}) as dirty", task, scope.id, ); let order = ScopeOrder::new(scope.height(), scope.id); drop(scope); self.queue_task(task, order); } /// Wait for the scheduler to have any work. /// /// This method polls the internal future queue, waiting for suspense nodes, tasks, or other work. This completes when /// any work is ready. If multiple scopes are marked dirty from a task or a suspense tree is finished, this method /// will exit. /// /// This method is cancel-safe, so you're fine to discard the future in a select block. /// /// This lets us poll async tasks and suspended trees during idle periods without blocking the main thread. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # fn app() -> Element { rsx! { div {} } } /// let dom = VirtualDom::new(app); /// ``` #[instrument(skip(self), level = "trace", name = "VirtualDom::wait_for_work")] pub async fn wait_for_work(&mut self) { loop { // Process all events - Scopes are marked dirty, etc // Sometimes when wakers fire we get a slew of updates at once, so its important that we drain this completely self.process_events(); // Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures if self.has_dirty_scopes() { return; } // Make sure we set the runtime since we're running user code let _runtime = RuntimeGuard::new(self.runtime.clone()); // There isn't any more work we can do synchronously. Wait for any new work to be ready self.wait_for_event().await; } } /// Wait for the next event to trigger and add it to the queue #[instrument(skip(self), level = "trace", name = "VirtualDom::wait_for_event")] async fn wait_for_event(&mut self) { match self.rx.next().await.expect("channel should never close") { SchedulerMsg::Immediate(id) => self.mark_dirty(id), SchedulerMsg::TaskNotified(id) => { // Instead of running the task immediately, we insert it into the runtime's task queue. // The task may be marked dirty at the same time as the scope that owns the task is dropped. self.mark_task_dirty(Task::from_id(id)); } SchedulerMsg::EffectQueued => {} SchedulerMsg::AllDirty => self.mark_all_dirty(), }; } /// Queue any pending events fn queue_events(&mut self) { // Prevent a task from deadlocking the runtime by repeatedly queueing itself while let Ok(Some(msg)) = self.rx.try_next() { match msg { SchedulerMsg::Immediate(id) => self.mark_dirty(id), SchedulerMsg::TaskNotified(task) => self.mark_task_dirty(Task::from_id(task)), SchedulerMsg::EffectQueued => {} SchedulerMsg::AllDirty => self.mark_all_dirty(), } } } /// Process all events in the queue until there are no more left #[instrument(skip(self), level = "trace", name = "VirtualDom::process_events")] pub fn process_events(&mut self) { self.queue_events(); // Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures if self.has_dirty_scopes() { return; } self.poll_tasks() } /// Poll any queued tasks #[instrument(skip(self), level = "trace", name = "VirtualDom::poll_tasks")] fn poll_tasks(&mut self) { // Make sure we set the runtime since we're running user code let _runtime = RuntimeGuard::new(self.runtime.clone()); // Keep polling tasks until there are no more effects or tasks to run // Or until we have no more dirty scopes while !self.runtime.dirty_tasks.borrow().is_empty() || !self.runtime.pending_effects.borrow().is_empty() { // Next, run any queued tasks // We choose not to poll the deadline since we complete pretty quickly anyways while let Some(task) = self.pop_task() { let _ = self.runtime.handle_task_wakeup(task); // Running that task, may mark a scope higher up as dirty. If it does, return from the function early self.queue_events(); if self.has_dirty_scopes() { return; } } // At this point, we have finished running all tasks that are pending and we haven't found any scopes to rerun. This means it is safe to run our lowest priority work: effects while let Some(effect) = self.pop_effect() { effect.run(); // Check if any new scopes are queued for rerun self.queue_events(); if self.has_dirty_scopes() { return; } } } } /// Rebuild the virtualdom without handling any of the mutations /// /// This is useful for testing purposes and in cases where you render the output of the virtualdom without /// handling any of its mutations. pub fn rebuild_in_place(&mut self) { self.rebuild(&mut NoOpMutations); } /// [`VirtualDom::rebuild`] to a vector of mutations for testing purposes pub fn rebuild_to_vec(&mut self) -> Mutations { let mut mutations = Mutations::default(); self.rebuild(&mut mutations); mutations } /// Performs a *full* rebuild of the virtual dom, returning every edit required to generate the actual dom from scratch. /// /// The mutations item expects the RealDom's stack to be the root of the application. /// /// Tasks will not be polled with this method, nor will any events be processed from the event queue. Instead, the /// root component will be run once and then diffed. All updates will flow out as mutations. /// /// All state stored in components will be completely wiped away. /// /// Any templates previously registered will remain. /// /// # Example /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::*; /// fn app() -> Element { /// rsx! { "hello world" } /// } /// /// let mut dom = VirtualDom::new(app); /// let mut mutations = Mutations::default(); /// dom.rebuild(&mut mutations); /// ``` #[instrument(skip(self, to), level = "trace", name = "VirtualDom::rebuild")] pub fn rebuild(&mut self, to: &mut impl WriteMutations) { let _runtime = RuntimeGuard::new(self.runtime.clone()); let new_nodes = self .runtime .clone() .while_rendering(|| self.run_scope(ScopeId::ROOT)); let new_nodes = LastRenderedNode::new(new_nodes); self.scopes[ScopeId::ROOT.0].last_rendered_node = Some(new_nodes.clone()); // Rebuilding implies we append the created elements to the root let m = self.create_scope(Some(to), ScopeId::ROOT, new_nodes, None); to.append_children(ElementId(0), m); } /// Render whatever the VirtualDom has ready as fast as possible without requiring an executor to progress /// suspended subtrees. #[instrument(skip(self, to), level = "trace", name = "VirtualDom::render_immediate")] pub fn render_immediate(&mut self, to: &mut impl WriteMutations) { // Process any events that might be pending in the queue // Signals marked with .write() need a chance to be handled by the effect driver // This also processes futures which might progress into immediately rerunning a scope self.process_events(); // Next, diff any dirty scopes // We choose not to poll the deadline since we complete pretty quickly anyways let _runtime = RuntimeGuard::new(self.runtime.clone()); while let Some(work) = self.pop_work() { match work { Work::PollTask(task) => { _ = self.runtime.handle_task_wakeup(task); // Make sure we process any new events self.queue_events(); } Work::RerunScope(scope) => { // If the scope is dirty, run the scope and get the mutations self.runtime.clone().while_rendering(|| { self.run_and_diff_scope(Some(to), scope.id); }); } } } self.runtime.finish_render(); } /// [`Self::render_immediate`] to a vector of mutations for testing purposes pub fn render_immediate_to_vec(&mut self) -> Mutations { let mut mutations = Mutations::default(); self.render_immediate(&mut mutations); mutations } /// Render the virtual dom, waiting for all suspense to be finished /// /// The mutations will be thrown out, so it's best to use this method for things like SSR that have async content /// /// We don't call "flush_sync" here since there's no sync work to be done. Futures will be progressed like usual, /// however any futures waiting on flush_sync will remain pending #[instrument(skip(self), level = "trace", name = "VirtualDom::wait_for_suspense")] pub async fn wait_for_suspense(&mut self) { loop { self.queue_events(); if !self.suspended_tasks_remaining() && !self.has_dirty_scopes() { break; } self.wait_for_suspense_work().await; self.render_suspense_immediate().await; } } /// Check if there are any suspended tasks remaining pub fn suspended_tasks_remaining(&self) -> bool { self.runtime.suspended_tasks.get() > 0 } /// Wait for the scheduler to have any work that should be run during suspense. pub async fn wait_for_suspense_work(&mut self) { // Wait for a work to be ready (IE new suspense leaves to pop up) loop { // Process all events - Scopes are marked dirty, etc // Sometimes when wakers fire we get a slew of updates at once, so its important that we drain this completely self.queue_events(); // Now that we have collected all queued work, we should check if we have any dirty scopes. If there are not, then we can poll any queued futures if self.has_dirty_scopes() { break; } { // Make sure we set the runtime since we're running user code let _runtime = RuntimeGuard::new(self.runtime.clone()); // Next, run any queued tasks // We choose not to poll the deadline since we complete pretty quickly anyways let mut tasks_polled = 0; while let Some(task) = self.pop_task() { if self.runtime.task_runs_during_suspense(task) { let _ = self.runtime.handle_task_wakeup(task); // Running that task, may mark a scope higher up as dirty. If it does, return from the function early self.queue_events(); if self.has_dirty_scopes() { return; } } tasks_polled += 1; // Once we have polled a few tasks, we manually yield to the scheduler to give it a chance to run other pending work if tasks_polled > 32 { yield_now().await; tasks_polled = 0; } } } self.wait_for_event().await; } } /// Render any dirty scopes immediately, but don't poll any futures that are client only on that scope /// Returns a list of suspense boundaries that were resolved pub async fn render_suspense_immediate(&mut self) -> Vec<ScopeId> { // Queue any new events before we start working self.queue_events(); // Render whatever work needs to be rendered, unlocking new futures and suspense leaves let _runtime = RuntimeGuard::new(self.runtime.clone()); let mut work_done = 0; while let Some(work) = self.pop_work() { match work { Work::PollTask(task) => { // During suspense, we only want to run tasks that are suspended if self.runtime.task_runs_during_suspense(task) { let _ = self.runtime.handle_task_wakeup(task); } } Work::RerunScope(scope) => { let scope_id: ScopeId = scope.id; let run_scope = self .runtime .try_get_state(scope.id) .filter(|scope| scope.should_run_during_suspense()) .is_some(); if run_scope { // If the scope is dirty, run the scope and get the mutations self.runtime.clone().while_rendering(|| { self.run_and_diff_scope(None::<&mut NoOpMutations>, scope_id); }); tracing::trace!("Ran scope {:?} during suspense", scope_id); } else { tracing::warn!( "Scope {:?} was marked as dirty, but will not rerun during suspense. Only nodes that are under a suspense boundary rerun during suspense", scope_id ); } } } // Queue any new events self.queue_events(); work_done += 1; // Once we have polled a few tasks, we manually yield to the scheduler to give it a chance to run other pending work if work_done > 32 { yield_now().await; work_done = 0; } } self.resolved_scopes .sort_by_key(|&id| self.runtime.get_state(id).height); std::mem::take(&mut self.resolved_scopes) } /// Get the current runtime pub fn runtime(&self) -> Rc<Runtime> { self.runtime.clone() } /// Handle an event with the Virtual Dom. This method is deprecated in favor of [VirtualDom::runtime().handle_event] and will be removed in a future release. #[deprecated = "Use [VirtualDom::runtime().handle_event] instead"] pub fn handle_event(&self, name: &str, event: Rc<dyn Any>, element: ElementId, bubbling: bool) { let event = crate::Event::new(event, bubbling); self.runtime().handle_event(name, event, element); } #[cfg(debug_assertions)] fn register_subsecond_handler(&self) { let sender = self.runtime().sender.clone(); subsecond::register_handler(std::sync::Arc::new(move || { _ = sender.unbounded_send(SchedulerMsg::AllDirty); })); } } impl Drop for VirtualDom { fn drop(&mut self) { // Drop all scopes in order of height let mut scopes = self.scopes.drain().collect::<Vec<_>>(); scopes.sort_by_key(|scope| scope.state().height); for scope in scopes.into_iter().rev() { drop(scope); } // Drop the mounts, tasks, and effects, releasing any `Rc<Runtime>` references self.runtime.pending_effects.borrow_mut().clear(); self.runtime.tasks.borrow_mut().clear(); self.runtime.mounts.borrow_mut().clear(); } } /// Yield control back to the async scheduler. This is used to give the scheduler a chance to run other pending work. Or cancel the task if the client has disconnected. async fn yield_now() { let mut yielded = false; std::future::poll_fn::<(), _>(move |cx| { if !yielded { cx.waker().wake_by_ref(); yielded = true; std::task::Poll::Pending } else { std::task::Poll::Ready(()) } }) .await; }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/generational_box.rs
packages/core/src/generational_box.rs
//! Integration with the generational-box crate for copy state management. //! //! Each scope in dioxus has a single [Owner] use generational_box::{AnyStorage, Owner, SyncStorage, UnsyncStorage}; use std::{ any::{Any, TypeId}, cell::RefCell, }; /// Run a closure with the given owner. /// /// This will override the default owner for the current component. pub fn with_owner<S: AnyStorage, F: FnOnce() -> R, R>(owner: Owner<S>, f: F) -> R { let old_owner = set_owner(Some(owner)); let result = f(); set_owner(old_owner); result } /// Set the owner for the current thread. fn set_owner<S: AnyStorage>(owner: Option<Owner<S>>) -> Option<Owner<S>> { let id = TypeId::of::<S>(); if id == TypeId::of::<SyncStorage>() { SYNC_OWNER.with(|cell| { std::mem::replace( &mut *cell.borrow_mut(), owner.map(|owner| { *(Box::new(owner) as Box<dyn Any>) .downcast::<Owner<SyncStorage>>() .unwrap() }), ) .map(|owner| *(Box::new(owner) as Box<dyn Any>).downcast().unwrap()) }) } else { UNSYNC_OWNER.with(|cell| { std::mem::replace( &mut *cell.borrow_mut(), owner.map(|owner| { *(Box::new(owner) as Box<dyn Any>) .downcast::<Owner<UnsyncStorage>>() .unwrap() }), ) .map(|owner| *(Box::new(owner) as Box<dyn Any>).downcast().unwrap()) }) } } thread_local! { static SYNC_OWNER: RefCell<Option<Owner<SyncStorage>>> = const { RefCell::new(None) }; static UNSYNC_OWNER: RefCell<Option<Owner<UnsyncStorage>>> = const { RefCell::new(None) }; } /// Returns the current owner. This owner will be used to drop any `Copy` state that is created by the `generational-box` crate. /// /// If an owner has been set with `with_owner`, that owner will be returned. Otherwise, the owner from the current scope will be returned. pub fn current_owner<S: AnyStorage>() -> Owner<S> { let id = TypeId::of::<S>(); let override_owner = if id == TypeId::of::<SyncStorage>() { SYNC_OWNER.with(|cell| { let owner = cell.borrow(); owner.clone().map(|owner| { *(Box::new(owner) as Box<dyn Any>) .downcast::<Owner<S>>() .unwrap() }) }) } else { UNSYNC_OWNER.with(|cell| { cell.borrow().clone().map(|owner| { *(Box::new(owner) as Box<dyn Any>) .downcast::<Owner<S>>() .unwrap() }) }) }; if let Some(owner) = override_owner { return owner; } crate::Runtime::current().current_owner() }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/reactive_context.rs
packages/core/src/reactive_context.rs
use crate::{current_scope_id, scope_context::Scope, tasks::SchedulerMsg, Runtime, ScopeId}; use futures_channel::mpsc::UnboundedReceiver; use generational_box::{BorrowMutError, GenerationalBox, SyncStorage}; use std::{ cell::RefCell, collections::HashSet, hash::Hash, sync::{Arc, Mutex}, }; #[doc = include_str!("../docs/reactivity.md")] #[derive(Clone, Copy)] pub struct ReactiveContext { scope: ScopeId, inner: GenerationalBox<Inner, SyncStorage>, } impl PartialEq for ReactiveContext { fn eq(&self, other: &Self) -> bool { self.inner.ptr_eq(&other.inner) } } impl Eq for ReactiveContext {} thread_local! { static CURRENT: RefCell<Vec<ReactiveContext>> = const { RefCell::new(vec![]) }; } impl std::fmt::Display for ReactiveContext { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { #[cfg(debug_assertions)] { if let Ok(read) = self.inner.try_read() { if let Some(scope) = read.scope { return write!(f, "ReactiveContext(for scope: {:?})", scope); } return write!(f, "ReactiveContext created at {}", read.origin); } } write!(f, "ReactiveContext") } } impl ReactiveContext { /// Create a new reactive context #[track_caller] pub fn new() -> (Self, UnboundedReceiver<()>) { Self::new_with_origin(std::panic::Location::caller()) } /// Create a new reactive context with a location for debugging purposes /// This is useful for reactive contexts created within closures pub fn new_with_origin( origin: &'static std::panic::Location<'static>, ) -> (Self, UnboundedReceiver<()>) { let (tx, rx) = futures_channel::mpsc::unbounded(); let callback = move || { // If there is already an update queued, we don't need to queue another if !tx.is_empty() { return; } let _ = tx.unbounded_send(()); }; let _self = Self::new_with_callback(callback, current_scope_id(), origin); (_self, rx) } /// Create a new reactive context that may update a scope. When any signal that this context subscribes to changes, the callback will be run pub fn new_with_callback( callback: impl FnMut() + Send + Sync + 'static, scope: ScopeId, #[allow(unused)] origin: &'static std::panic::Location<'static>, ) -> Self { let inner = Inner { self_: None, update: Box::new(callback), subscribers: Default::default(), #[cfg(debug_assertions)] origin, #[cfg(debug_assertions)] scope: None, }; let owner = Runtime::current().scope_owner(scope); let self_ = Self { scope, inner: owner.insert(inner), }; self_.inner.write().self_ = Some(self_); self_ } /// Get the current reactive context from the nearest reactive hook or scope pub fn current() -> Option<Self> { CURRENT.with(|current| current.borrow().last().cloned()) } /// Create a reactive context for a scope id pub(crate) fn new_for_scope(scope: &Scope, runtime: &Runtime) -> Self { let id = scope.id; let sender = runtime.sender.clone(); let update_scope = move || { _ = sender.unbounded_send(SchedulerMsg::Immediate(id)); }; // Otherwise, create a new context at the current scope let inner = Inner { self_: None, update: Box::new(update_scope), subscribers: Default::default(), #[cfg(debug_assertions)] origin: std::panic::Location::caller(), #[cfg(debug_assertions)] scope: Some(id), }; let owner = scope.owner(); let self_ = Self { scope: id, inner: owner.insert(inner), }; self_.inner.write().self_ = Some(self_); self_ } /// Clear all subscribers to this context pub fn clear_subscribers(&self) { // The key type is mutable, but the hash is stable through mutations because we hash by pointer #[allow(clippy::mutable_key_type)] let old_subscribers = std::mem::take(&mut self.inner.write().subscribers); for subscriber in old_subscribers { subscriber.0.remove(self); } } /// Update the subscribers pub(crate) fn update_subscribers(&self) { #[allow(clippy::mutable_key_type)] let subscribers = &self.inner.read().subscribers; for subscriber in subscribers.iter() { subscriber.0.add(*self); } } /// Reset the reactive context and then run the callback in the context. This can be used to create custom reactive hooks like `use_memo`. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::ReactiveContext; /// # use futures_util::StreamExt; /// fn use_simplified_memo(mut closure: impl FnMut() -> i32 + 'static) -> Signal<i32> { /// use_hook(|| { /// // Create a new reactive context and channel that will receive a value every time a value the reactive context subscribes to changes /// let (reactive_context, mut changed) = ReactiveContext::new(); /// // Compute the value of the memo inside the reactive context. This will subscribe the reactive context to any values you read inside the closure /// let value = reactive_context.reset_and_run_in(&mut closure); /// // Create a new signal with the value of the memo /// let mut signal = Signal::new(value); /// // Create a task that reruns the closure when the reactive context changes /// spawn(async move { /// while changed.next().await.is_some() { /// // Since we reset the reactive context as we run the closure, our memo will only subscribe to the new values that are read in the closure /// let new_value = reactive_context.run_in(&mut closure); /// if new_value != value { /// signal.set(new_value); /// } /// } /// }); /// signal /// }) /// } /// /// let mut boolean = use_signal(|| false); /// let mut count = use_signal(|| 0); /// // Because we use `reset_and_run_in` instead of just `run_in`, our memo will only subscribe to the signals that are read this run of the closure (initially just the boolean) /// let memo = use_simplified_memo(move || if boolean() { count() } else { 0 }); /// println!("{memo}"); /// // Because the count signal is not read in this run of the closure, the memo will not rerun /// count += 1; /// println!("{memo}"); /// // Because the boolean signal is read in this run of the closure, the memo will rerun /// boolean.toggle(); /// println!("{memo}"); /// // If we toggle the boolean again, and the memo unsubscribes from the count signal /// boolean.toggle(); /// println!("{memo}"); /// ``` pub fn reset_and_run_in<O>(&self, f: impl FnOnce() -> O) -> O { self.clear_subscribers(); self.run_in(f) } /// Run this function in the context of this reactive context /// /// This will set the current reactive context to this context for the duration of the function. /// You can then get information about the current subscriptions. pub fn run_in<O>(&self, f: impl FnOnce() -> O) -> O { CURRENT.with(|current| current.borrow_mut().push(*self)); let out = f(); CURRENT.with(|current| current.borrow_mut().pop()); self.update_subscribers(); out } /// Marks this reactive context as dirty /// /// If there's a scope associated with this context, then it will be marked as dirty too /// /// Returns true if the context was marked as dirty, or false if the context has been dropped pub fn mark_dirty(&self) -> bool { if let Ok(mut self_write) = self.inner.try_write() { #[cfg(debug_assertions)] { tracing::trace!( "Marking reactive context created at {} as dirty", self_write.origin ); } (self_write.update)(); true } else { false } } /// Subscribe to this context. The reactive context will automatically remove itself from the subscriptions when it is reset. pub fn subscribe(&self, subscriptions: impl Into<Subscribers>) { match self.inner.try_write() { Ok(mut inner) => { let subscriptions = subscriptions.into(); subscriptions.add(*self); inner .subscribers .insert(PointerHash(subscriptions.inner.clone())); } // If the context was dropped, we don't need to subscribe to it anymore Err(BorrowMutError::Dropped(_)) => {} Err(expect) => { panic!( "Expected to be able to write to reactive context to subscribe, but it failed with: {expect:?}" ); } } } /// Get the scope that inner CopyValue is associated with pub fn origin_scope(&self) -> ScopeId { self.scope } } impl Hash for ReactiveContext { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.inner.id().hash(state); } } struct PointerHash<T: ?Sized>(Arc<T>); impl<T: ?Sized> Hash for PointerHash<T> { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { std::sync::Arc::<T>::as_ptr(&self.0).hash(state); } } impl<T: ?Sized> PartialEq for PointerHash<T> { fn eq(&self, other: &Self) -> bool { std::sync::Arc::ptr_eq(&self.0, &other.0) } } impl<T: ?Sized> Eq for PointerHash<T> {} impl<T: ?Sized> Clone for PointerHash<T> { fn clone(&self) -> Self { Self(self.0.clone()) } } struct Inner { self_: Option<ReactiveContext>, // Futures will call .changed().await update: Box<dyn FnMut() + Send + Sync>, // Subscribers to this context subscribers: HashSet<PointerHash<dyn SubscriberList + Send + Sync>>, // Debug information for signal subscriptions #[cfg(debug_assertions)] origin: &'static std::panic::Location<'static>, #[cfg(debug_assertions)] // The scope that this reactive context is associated with scope: Option<ScopeId>, } impl Drop for Inner { fn drop(&mut self) { let Some(self_) = self.self_.take() else { return; }; for subscriber in std::mem::take(&mut self.subscribers) { subscriber.0.remove(&self_); } } } /// A list of [ReactiveContext]s that are subscribed. This is used to notify subscribers when the value changes. #[derive(Clone)] pub struct Subscribers { /// The list of subscribers. pub(crate) inner: Arc<dyn SubscriberList + Send + Sync>, } impl Default for Subscribers { fn default() -> Self { Self::new() } } impl Subscribers { /// Create a new no-op list of subscribers. pub fn new_noop() -> Self { struct NoopSubscribers; impl SubscriberList for NoopSubscribers { fn add(&self, _subscriber: ReactiveContext) {} fn remove(&self, _subscriber: &ReactiveContext) {} fn visit(&self, _f: &mut dyn FnMut(&ReactiveContext)) {} } Subscribers { inner: Arc::new(NoopSubscribers), } } /// Create a new list of subscribers. pub fn new() -> Self { Subscribers { inner: Arc::new(Mutex::new(HashSet::new())), } } /// Add a subscriber to the list. pub fn add(&self, subscriber: ReactiveContext) { self.inner.add(subscriber); } /// Remove a subscriber from the list. pub fn remove(&self, subscriber: &ReactiveContext) { self.inner.remove(subscriber); } /// Visit all subscribers in the list. pub fn visit(&self, mut f: impl FnMut(&ReactiveContext)) { self.inner.visit(&mut f); } } impl<S: SubscriberList + Send + Sync + 'static> From<Arc<S>> for Subscribers { fn from(inner: Arc<S>) -> Self { Subscribers { inner } } } /// A list of subscribers that can be notified when the value changes. This is used to track when the value changes and notify subscribers. pub trait SubscriberList: Send + Sync { /// Add a subscriber to the list. fn add(&self, subscriber: ReactiveContext); /// Remove a subscriber from the list. fn remove(&self, subscriber: &ReactiveContext); /// Visit all subscribers in the list. fn visit(&self, f: &mut dyn FnMut(&ReactiveContext)); } impl SubscriberList for Mutex<HashSet<ReactiveContext>> { fn add(&self, subscriber: ReactiveContext) { if let Ok(mut lock) = self.lock() { lock.insert(subscriber); } else { tracing::warn!("Failed to lock subscriber list to add subscriber: {subscriber}"); } } fn remove(&self, subscriber: &ReactiveContext) { if let Ok(mut lock) = self.lock() { lock.remove(subscriber); } else { tracing::warn!("Failed to lock subscriber list to remove subscriber: {subscriber}"); } } fn visit(&self, f: &mut dyn FnMut(&ReactiveContext)) { if let Ok(lock) = self.lock() { lock.iter().for_each(f); } else { tracing::warn!("Failed to lock subscriber list to visit subscribers"); } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/events.rs
packages/core/src/events.rs
use crate::{current_scope_id, properties::SuperFrom, runtime::RuntimeGuard, Runtime, ScopeId}; use futures_util::FutureExt; use generational_box::GenerationalBox; use std::{any::Any, cell::RefCell, marker::PhantomData, panic::Location, rc::Rc}; /// A wrapper around some generic data that handles the event's state /// /// /// Prevent this event from continuing to bubble up the tree to parent elements. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event<MouseData>| { /// evt.stop_propagation(); /// } /// } /// }; /// ``` pub struct Event<T: 'static + ?Sized> { /// The data associated with this event pub data: Rc<T>, pub(crate) metadata: Rc<RefCell<EventMetadata>>, } #[derive(Clone, Copy)] pub(crate) struct EventMetadata { pub(crate) propagates: bool, pub(crate) prevent_default: bool, } impl<T: ?Sized + 'static> Event<T> { /// Create a new event from the inner data pub fn new(data: Rc<T>, propagates: bool) -> Self { Self { data, metadata: Rc::new(RefCell::new(EventMetadata { propagates, prevent_default: false, })), } } } impl<T: ?Sized> Event<T> { /// Map the event data to a new type /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: MouseEvent| { /// let data = evt.map(|data| data.client_coordinates()); /// println!("{:?}", data.data()); /// } /// } /// }; /// ``` pub fn map<U: 'static, F: FnOnce(&T) -> U>(&self, f: F) -> Event<U> { Event { data: Rc::new(f(&self.data)), metadata: self.metadata.clone(), } } /// Convert this event into a boxed event with a dynamic type pub fn into_any(self) -> Event<dyn Any> where T: Sized, { Event { data: self.data as Rc<dyn Any>, metadata: self.metadata, } } /// Prevent this event from continuing to bubble up the tree to parent elements. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event<MouseData>| { /// # #[allow(deprecated)] /// evt.cancel_bubble(); /// } /// } /// }; /// ``` #[deprecated = "use stop_propagation instead"] pub fn cancel_bubble(&self) { self.metadata.borrow_mut().propagates = false; } /// Check if the event propagates up the tree to parent elements pub fn propagates(&self) -> bool { self.metadata.borrow().propagates } /// Prevent this event from continuing to bubble up the tree to parent elements. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event<MouseData>| { /// evt.stop_propagation(); /// } /// } /// }; /// ``` pub fn stop_propagation(&self) { self.metadata.borrow_mut().propagates = false; } /// Get a reference to the inner data from this event /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// button { /// onclick: move |evt: Event<MouseData>| { /// let data = evt.data(); /// async move { /// println!("{:?}", data); /// } /// } /// } /// }; /// ``` pub fn data(&self) -> Rc<T> { self.data.clone() } /// Prevent the default action of the event. /// /// # Example /// /// ```rust /// # use dioxus::prelude::*; /// fn App() -> Element { /// rsx! { /// a { /// // You can prevent the default action of the event with `prevent_default` /// onclick: move |event| { /// event.prevent_default(); /// }, /// href: "https://dioxuslabs.com", /// "don't go to the link" /// } /// } /// } /// ``` /// /// Note: This must be called synchronously when handling the event. Calling it after the event has been handled will have no effect. /// /// <div class="warning"> /// /// This method is not available on the LiveView renderer because LiveView handles all events over a websocket which cannot block. /// /// </div> #[track_caller] pub fn prevent_default(&self) { self.metadata.borrow_mut().prevent_default = true; } /// Check if the default action of the event is enabled. pub fn default_action_enabled(&self) -> bool { !self.metadata.borrow().prevent_default } } impl<T: ?Sized> Clone for Event<T> { fn clone(&self) -> Self { Self { metadata: self.metadata.clone(), data: self.data.clone(), } } } impl<T> std::ops::Deref for Event<T> { type Target = Rc<T>; fn deref(&self) -> &Self::Target { &self.data } } impl<T: std::fmt::Debug> std::fmt::Debug for Event<T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("UiEvent") .field("bubble_state", &self.propagates()) .field("prevent_default", &!self.default_action_enabled()) .field("data", &self.data) .finish() } } /// The callback type generated by the `rsx!` macro when an `on` field is specified for components. /// /// This makes it possible to pass `move |evt| {}` style closures into components as property fields. /// /// # Example /// /// ```rust, no_run /// # use dioxus::prelude::*; /// rsx! { /// MyComponent { onclick: move |evt| tracing::debug!("clicked") } /// }; /// /// #[derive(Props, Clone, PartialEq)] /// struct MyProps { /// onclick: EventHandler<MouseEvent>, /// } /// /// fn MyComponent(cx: MyProps) -> Element { /// rsx! { /// button { /// onclick: move |evt| cx.onclick.call(evt), /// } /// } /// } /// ``` pub type EventHandler<T = ()> = Callback<T>; /// The callback type generated by the `rsx!` macro when an `on` field is specified for components. /// /// This makes it possible to pass `move |evt| {}` style closures into components as property fields. /// /// /// # Example /// /// ```rust, ignore /// rsx! { /// MyComponent { onclick: move |evt| { /// tracing::debug!("clicked"); /// 42 /// } } /// } /// /// #[derive(Props)] /// struct MyProps { /// onclick: Callback<MouseEvent, i32>, /// } /// /// fn MyComponent(cx: MyProps) -> Element { /// rsx! { /// button { /// onclick: move |evt| println!("number: {}", cx.onclick.call(evt)), /// } /// } /// } /// ``` pub struct Callback<Args = (), Ret = ()> { pub(crate) origin: ScopeId, /// During diffing components with EventHandler, we move the EventHandler over in place instead of rerunning the child component. /// /// ```rust /// # use dioxus::prelude::*; /// #[component] /// fn Child(onclick: EventHandler<MouseEvent>) -> Element { /// rsx! { /// button { /// // Diffing Child will not rerun this component, it will just update the callback in place so that if this callback is called, it will run the latest version of the callback /// onclick: move |evt| onclick(evt), /// } /// } /// } /// ``` /// /// This is both more efficient and allows us to avoid out of date EventHandlers. /// /// We double box here because we want the data to be copy (GenerationalBox) and still update in place (ExternalListenerCallback) /// This isn't an ideal solution for performance, but it is non-breaking and fixes the issues described in <https://github.com/DioxusLabs/dioxus/pull/2298> pub(super) callback: GenerationalBox<Option<ExternalListenerCallback<Args, Ret>>>, } impl<Args, Ret> std::fmt::Debug for Callback<Args, Ret> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Callback") .field("origin", &self.origin) .field("callback", &self.callback) .finish() } } impl<T: 'static, Ret: Default + 'static> Default for Callback<T, Ret> { fn default() -> Self { Callback::new(|_| Ret::default()) } } /// A helper trait for [`Callback`]s that allows functions to accept a [`Callback`] that may return an async block which will automatically be spawned. /// /// ```rust, no_run /// use dioxus::prelude::*; /// fn accepts_fn<Ret: dioxus_core::SpawnIfAsync<Marker>, Marker>(callback: impl FnMut(u32) -> Ret + 'static) { /// let callback = Callback::new(callback); /// } /// // You can accept both async and non-async functions /// accepts_fn(|x| async move { println!("{}", x) }); /// accepts_fn(|x| println!("{}", x)); /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`SpawnIfAsync` is not implemented for `{Self}`", label = "Return Value", note = "Closures (or event handlers) in dioxus need to return either: nothing (the unit type `()`), or an async block that dioxus will automatically spawn", note = "You likely need to add a semicolon to the end of the event handler to make it return nothing", ) )] pub trait SpawnIfAsync<Marker, Ret = ()>: Sized { /// Spawn the value into the dioxus runtime if it is an async block fn spawn(self) -> Ret; } // Support for FnMut -> Ret for any return type impl<Ret> SpawnIfAsync<(), Ret> for Ret { fn spawn(self) -> Ret { self } } // Support for FnMut -> async { unit } for the unit return type #[doc(hidden)] pub struct AsyncMarker; impl<F: std::future::Future<Output = ()> + 'static> SpawnIfAsync<AsyncMarker> for F { fn spawn(self) { // Quick poll once to deal with things like prevent_default in the same tick let mut fut = Box::pin(self); let res = fut.as_mut().now_or_never(); if res.is_none() { crate::spawn(async move { fut.await; }); } } } // Support for FnMut -> async { Result(()) } for the unit return type #[doc(hidden)] pub struct AsyncResultMarker; impl<T> SpawnIfAsync<AsyncResultMarker> for T where T: std::future::Future<Output = crate::Result<()>> + 'static, { #[inline] fn spawn(self) { // Quick poll once to deal with things like prevent_default in the same tick let mut fut = Box::pin(self); let res = fut.as_mut().now_or_never(); if res.is_none() { crate::spawn(async move { if let Err(err) = fut.await { crate::throw_error(err) } }); } } } // Support for FnMut -> Result(()) for the unit return type impl SpawnIfAsync<()> for crate::Result<()> { #[inline] fn spawn(self) { if let Err(err) = self { crate::throw_error(err) } } } // We can't directly forward the marker because it would overlap with a bunch of other impls, so we wrap it in another type instead #[doc(hidden)] pub struct MarkerWrapper<T>(PhantomData<T>); // Closure can be created from FnMut -> async { anything } or FnMut -> Ret impl< Function: FnMut(Args) -> Spawn + 'static, Args: 'static, Spawn: SpawnIfAsync<Marker, Ret> + 'static, Ret: 'static, Marker, > SuperFrom<Function, MarkerWrapper<Marker>> for Callback<Args, Ret> { fn super_from(input: Function) -> Self { Callback::new(input) } } impl< Function: FnMut(Event<T>) -> Spawn + 'static, T: 'static, Spawn: SpawnIfAsync<Marker> + 'static, Marker, > SuperFrom<Function, MarkerWrapper<Marker>> for ListenerCallback<T> { fn super_from(input: Function) -> Self { ListenerCallback::new(input) } } // ListenerCallback<T> can be created from Callback<Event<T>> impl<T: 'static> SuperFrom<Callback<Event<T>>> for ListenerCallback<T> { fn super_from(input: Callback<Event<T>>) -> Self { // https://github.com/rust-lang/rust-clippy/issues/15072 #[allow(clippy::redundant_closure)] ListenerCallback::new(move |event| input(event)) } } #[doc(hidden)] pub struct UnitClosure<Marker>(PhantomData<Marker>); // Closure can be created from FnMut -> async { () } or FnMut -> Ret impl< Function: FnMut() -> Spawn + 'static, Spawn: SpawnIfAsync<Marker, Ret> + 'static, Ret: 'static, Marker, > SuperFrom<Function, UnitClosure<Marker>> for Callback<(), Ret> { fn super_from(mut input: Function) -> Self { Callback::new(move |()| input()) } } #[test] fn closure_types_infer() { #[allow(unused)] fn compile_checks() { // You should be able to use a closure as a callback let callback: Callback<(), ()> = Callback::new(|_| {}); // Or an async closure let callback: Callback<(), ()> = Callback::new(|_| async {}); // You can also pass in a closure that returns a value let callback: Callback<(), u32> = Callback::new(|_| 123); // Or pass in a value let callback: Callback<u32, ()> = Callback::new(|value: u32| async move { println!("{}", value); }); // Unit closures shouldn't require an argument let callback: Callback<(), ()> = Callback::super_from(|| async move { println!("hello world"); }); } } impl<Args, Ret> Copy for Callback<Args, Ret> {} impl<Args, Ret> Clone for Callback<Args, Ret> { fn clone(&self) -> Self { *self } } impl<Args: 'static, Ret: 'static> PartialEq for Callback<Args, Ret> { fn eq(&self, other: &Self) -> bool { self.callback.ptr_eq(&other.callback) && self.origin == other.origin } } pub(super) struct ExternalListenerCallback<Args, Ret> { callback: Box<dyn FnMut(Args) -> Ret>, runtime: std::rc::Weak<Runtime>, } impl<Args: 'static, Ret: 'static> Callback<Args, Ret> { /// Create a new [`Callback`] from an [`FnMut`]. The callback is owned by the current scope and will be dropped when the scope is dropped. /// This should not be called directly in the body of a component because it will not be dropped until the component is dropped. #[track_caller] pub fn new<MaybeAsync: SpawnIfAsync<Marker, Ret>, Marker>( mut f: impl FnMut(Args) -> MaybeAsync + 'static, ) -> Self { let runtime = Runtime::current(); let origin = runtime.current_scope_id(); let owner = crate::innerlude::current_owner::<generational_box::UnsyncStorage>(); let callback = owner.insert_rc(Some(ExternalListenerCallback { callback: Box::new(move |event: Args| f(event).spawn()), runtime: Rc::downgrade(&runtime), })); Self { callback, origin } } /// Leak a new [`Callback`] that will not be dropped unless it is manually dropped. #[track_caller] pub fn leak(mut f: impl FnMut(Args) -> Ret + 'static) -> Self { let runtime = Runtime::current(); let origin = runtime.current_scope_id(); let callback = GenerationalBox::leak_rc( Some(ExternalListenerCallback { callback: Box::new(move |event: Args| f(event).spawn()), runtime: Rc::downgrade(&runtime), }), Location::caller(), ); Self { callback, origin } } /// Call this callback with the appropriate argument type /// /// This borrows the callback using a RefCell. Recursively calling a callback will cause a panic. #[track_caller] pub fn call(&self, arguments: Args) -> Ret { if let Some(callback) = self.callback.write().as_mut() { let runtime = callback .runtime .upgrade() .expect("Callback was called after the runtime was dropped"); let _guard = RuntimeGuard::new(runtime.clone()); runtime.with_scope_on_stack(self.origin, || (callback.callback)(arguments)) } else { panic!("Callback was manually dropped") } } /// Create a `impl FnMut + Copy` closure from the Closure type pub fn into_closure(self) -> impl FnMut(Args) -> Ret + Copy + 'static { move |args| self.call(args) } /// Forcibly drop the internal handler callback, releasing memory /// /// This will force any future calls to "call" to not doing anything pub fn release(&self) { self.callback.set(None); } /// Replace the function in the callback with a new one pub fn replace(&mut self, callback: Box<dyn FnMut(Args) -> Ret>) { let runtime = Runtime::current(); self.callback.set(Some(ExternalListenerCallback { callback, runtime: Rc::downgrade(&runtime), })); } #[doc(hidden)] /// This should only be used by the `rsx!` macro. pub fn __point_to(&mut self, other: &Self) { self.callback.point_to(other.callback).unwrap(); } } impl<Args: 'static, Ret: 'static> std::ops::Deref for Callback<Args, Ret> { type Target = dyn Fn(Args) -> Ret + 'static; fn deref(&self) -> &Self::Target { // https://github.com/dtolnay/case-studies/tree/master/callable-types // First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>). let uninit_callable = std::mem::MaybeUninit::<Self>::uninit(); // Then move that value into the closure. We assume that the closure now has a in memory layout of Self. let uninit_closure = move |t| Self::call(unsafe { &*uninit_callable.as_ptr() }, t); // Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure. let size_of_closure = std::mem::size_of_val(&uninit_closure); assert_eq!(size_of_closure, std::mem::size_of::<Self>()); // Then cast the lifetime of the closure to the lifetime of &self. fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T { b } let reference_to_closure = cast_lifetime( { // The real closure that we will never use. &uninit_closure }, #[allow(clippy::missing_transmute_annotations)] // We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self. unsafe { std::mem::transmute(self) }, ); // Cast the closure to a trait object. reference_to_closure as &_ } } type AnyEventHandler = Rc<RefCell<dyn FnMut(Event<dyn Any>)>>; /// An owned callback type used in [`AttributeValue::Listener`](crate::AttributeValue::Listener). /// /// This is the type that powers the `on` attributes in the `rsx!` macro, allowing you to pass event /// handlers to elements. /// /// ```rust, ignore /// rsx! { /// button { /// onclick: AttributeValue::Listener(ListenerCallback::new(move |evt: Event<MouseData>| { /// // ... /// })) /// } /// } /// ``` pub struct ListenerCallback<T = ()> { pub(crate) origin: ScopeId, callback: AnyEventHandler, _marker: PhantomData<T>, } impl<T> Clone for ListenerCallback<T> { fn clone(&self) -> Self { Self { origin: self.origin, callback: self.callback.clone(), _marker: PhantomData, } } } impl<T> PartialEq for ListenerCallback<T> { fn eq(&self, other: &Self) -> bool { // We compare the pointers of the callbacks, since they are unique Rc::ptr_eq(&self.callback, &other.callback) && self.origin == other.origin } } impl<T> ListenerCallback<T> { /// Create a new [`ListenerCallback`] from a callback /// /// This is expected to be called within a runtime scope. Make sure a runtime is current before /// calling this method. pub fn new<MaybeAsync, Marker>(mut f: impl FnMut(Event<T>) -> MaybeAsync + 'static) -> Self where T: 'static, MaybeAsync: SpawnIfAsync<Marker>, { Self { origin: current_scope_id(), callback: Rc::new(RefCell::new(move |event: Event<dyn Any>| { let data = event.data.downcast::<T>().unwrap(); f(Event { metadata: event.metadata.clone(), data, }) .spawn(); })), _marker: PhantomData, } } /// Call the callback with an event /// /// This is expected to be called within a runtime scope. Make sure a runtime is current before /// calling this method. pub fn call(&self, event: Event<dyn Any>) { Runtime::current().with_scope_on_stack(self.origin, || { (self.callback.borrow_mut())(event); }); } /// Erase the type of the callback, allowing it to be used with any type of event pub fn erase(self) -> ListenerCallback { ListenerCallback { origin: self.origin, callback: self.callback, _marker: PhantomData, } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/scope_arena.rs
packages/core/src/scope_arena.rs
use crate::{ any_props::{AnyProps, BoxedAnyProps}, innerlude::{RenderError, ScopeOrder, ScopeState}, scope_context::{Scope, SuspenseLocation}, scopes::ScopeId, virtual_dom::VirtualDom, Element, ReactiveContext, }; impl VirtualDom { pub(super) fn new_scope( &mut self, props: BoxedAnyProps, name: &'static str, ) -> &mut ScopeState { let parent_id = self.runtime.try_current_scope_id(); let height = match parent_id.and_then(|id| self.runtime.try_get_state(id)) { Some(parent) => parent.height() + 1, None => 0, }; let suspense_boundary = self .runtime .current_suspense_location() .unwrap_or(SuspenseLocation::NotSuspended); let entry = self.scopes.vacant_entry(); let id = ScopeId(entry.key()); let scope_runtime = Scope::new(name, id, parent_id, height, suspense_boundary); let reactive_context = ReactiveContext::new_for_scope(&scope_runtime, &self.runtime); let scope = entry.insert(ScopeState { runtime: self.runtime.clone(), context_id: id, props, last_rendered_node: Default::default(), reactive_context, }); self.runtime.create_scope(scope_runtime); scope } /// Run a scope and return the rendered nodes. This will not modify the DOM or update the last rendered node of the scope. #[tracing::instrument(skip(self), level = "trace", name = "VirtualDom::run_scope")] #[track_caller] pub(crate) fn run_scope(&mut self, scope_id: ScopeId) -> Element { // Ensure we are currently inside a `Runtime`. crate::Runtime::current(); self.runtime.clone().with_scope_on_stack(scope_id, || { let scope = &self.scopes[scope_id.0]; let output = { let scope_state = scope.state(); scope_state.hook_index.set(0); // Run all pre-render hooks for pre_run in scope_state.before_render.borrow_mut().iter_mut() { pre_run(); } let props: &dyn AnyProps = &*scope.props; let span = tracing::trace_span!("render", scope = %scope.state().name); span.in_scope(|| { scope.reactive_context.reset_and_run_in(|| { let render_return = props.render(); // After the component is run, we need to do a deep clone of the VNode. This // breaks any references to mounted parts of the VNode from the component. // Without this, the component could store a mounted version of the VNode // which causes a lot of issues for diffing because we expect only the old // or new node to be mounted. // // For example, the dog app example returns rsx from a resource. Every time // the component runs, it returns a clone of the last rsx that was returned from // that resource. If we don't deep clone the VNode and the resource changes, then // we could end up diffing two different versions of the same mounted node let mut render_return = match render_return { Ok(node) => Ok(node.deep_clone()), Err(RenderError::Error(err)) => Err(RenderError::Error(err.clone())), Err(RenderError::Suspended(fut)) => { Err(RenderError::Suspended(fut.deep_clone())) } }; self.handle_element_return(&mut render_return, &scope.state()); render_return }) }) }; let scope_state = scope.state(); // Run all post-render hooks for post_run in scope_state.after_render.borrow_mut().iter_mut() { post_run(); } // remove this scope from dirty scopes self.dirty_scopes .remove(&ScopeOrder::new(scope_state.height, scope_id)); output }) } /// Insert any errors, or suspended tasks from an element return into the runtime fn handle_element_return(&self, node: &mut Element, scope: &Scope) { match node { Err(RenderError::Error(e)) => { tracing::error!("Error while rendering component `{}`: {e}", scope.name); self.runtime.throw_error(scope.id, e.clone()); } Err(RenderError::Suspended(e)) => { let task = e.task(); // Insert the task into the nearest suspense boundary if it exists let boundary = scope.suspense_location(); let already_suspended = self .runtime .tasks .borrow() .get(task.id) .expect("Suspended on a task that no longer exists") .suspend(boundary.clone()); if !already_suspended { tracing::trace!("Suspending {:?} on {:?}", scope.id, task); // Add this task to the suspended tasks list of the boundary if let SuspenseLocation::UnderSuspense(boundary) = &boundary { boundary.add_suspended_task(e.clone()); } self.runtime .suspended_tasks .set(self.runtime.suspended_tasks.get() + 1); } } Ok(_) => { // If the render was successful, we can move the render generation forward by one scope.render_count.set(scope.render_count.get() + 1); } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/scope_context.rs
packages/core/src/scope_context.rs
use crate::{ innerlude::{SchedulerMsg, SuspenseContext}, Runtime, ScopeId, Task, }; use generational_box::{AnyStorage, Owner}; use rustc_hash::FxHashSet; use std::{ any::Any, cell::{Cell, RefCell}, future::Future, sync::Arc, }; pub(crate) enum ScopeStatus { Mounted, Unmounted { // Before the component is mounted, we need to keep track of effects that need to be run once the scope is mounted effects_queued: Vec<Box<dyn FnOnce() + 'static>>, }, } #[derive(Debug, Clone, Default)] pub(crate) enum SuspenseLocation { #[default] NotSuspended, SuspenseBoundary(SuspenseContext), UnderSuspense(SuspenseContext), InSuspensePlaceholder(SuspenseContext), } impl SuspenseLocation { pub(crate) fn suspense_context(&self) -> Option<&SuspenseContext> { match self { SuspenseLocation::InSuspensePlaceholder(context) => Some(context), SuspenseLocation::UnderSuspense(context) => Some(context), SuspenseLocation::SuspenseBoundary(context) => Some(context), _ => None, } } } /// A component's state separate from its props. /// /// This struct exists to provide a common interface for all scopes without relying on generics. pub(crate) struct Scope { pub(crate) name: &'static str, pub(crate) id: ScopeId, pub(crate) parent_id: Option<ScopeId>, pub(crate) height: u32, pub(crate) render_count: Cell<usize>, // Note: the order of the hook and context fields is important. The hooks field must be dropped before the contexts field in case a hook drop implementation tries to access a context. pub(crate) hooks: RefCell<Vec<Box<dyn Any>>>, pub(crate) hook_index: Cell<usize>, pub(crate) shared_contexts: RefCell<Vec<Box<dyn Any>>>, pub(crate) spawned_tasks: RefCell<FxHashSet<Task>>, pub(crate) before_render: RefCell<Vec<Box<dyn FnMut()>>>, pub(crate) after_render: RefCell<Vec<Box<dyn FnMut()>>>, /// The suspense boundary that this scope is currently in (if any) suspense_boundary: SuspenseLocation, pub(crate) status: RefCell<ScopeStatus>, } impl Scope { pub(crate) fn new( name: &'static str, id: ScopeId, parent_id: Option<ScopeId>, height: u32, suspense_boundary: SuspenseLocation, ) -> Self { Self { name, id, parent_id, height, render_count: Cell::new(0), shared_contexts: RefCell::new(vec![]), spawned_tasks: RefCell::new(FxHashSet::default()), hooks: RefCell::new(vec![]), hook_index: Cell::new(0), before_render: RefCell::new(vec![]), after_render: RefCell::new(vec![]), status: RefCell::new(ScopeStatus::Unmounted { effects_queued: Vec::new(), }), suspense_boundary, } } pub fn parent_id(&self) -> Option<ScopeId> { self.parent_id } fn sender(&self) -> futures_channel::mpsc::UnboundedSender<SchedulerMsg> { Runtime::current().sender.clone() } /// Mount the scope and queue any pending effects if it is not already mounted pub(crate) fn mount(&self, runtime: &Runtime) { let mut status = self.status.borrow_mut(); if let ScopeStatus::Unmounted { effects_queued } = &mut *status { for f in effects_queued.drain(..) { runtime.queue_effect_on_mounted_scope(self.id, f); } *status = ScopeStatus::Mounted; } } /// Get the suspense location of this scope pub(crate) fn suspense_location(&self) -> SuspenseLocation { self.suspense_boundary.clone() } /// If this scope is a suspense boundary, return the suspense context pub(crate) fn suspense_boundary(&self) -> Option<SuspenseContext> { match self.suspense_location() { SuspenseLocation::SuspenseBoundary(context) => Some(context), _ => None, } } /// Check if a node should run during suspense pub(crate) fn should_run_during_suspense(&self) -> bool { let Some(context) = self.suspense_boundary.suspense_context() else { return false; }; !context.frozen() } /// Mark this scope as dirty, and schedule a render for it. pub(crate) fn needs_update(&self) { self.needs_update_any(self.id) } /// Mark this scope as dirty, and schedule a render for it. pub(crate) fn needs_update_any(&self, id: ScopeId) { self.sender() .unbounded_send(SchedulerMsg::Immediate(id)) .expect("Scheduler to exist if scope exists"); } /// Create a subscription that schedules a future render for the referenced component. /// /// Note: you should prefer using [`Self::schedule_update_any`] and [`Self::id`]. /// /// Note: The function returned by this method will schedule an update for the current component even if it has already updated between when `schedule_update` was called and when the returned function is called. /// If the desired behavior is to invalidate the current rendering of the current component (and no-op if already invalidated) /// [`subscribe`](crate::reactive_context::ReactiveContext::subscribe) to the [`current`](crate::reactive_context::ReactiveContext::current) [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead. pub(crate) fn schedule_update(&self) -> Arc<dyn Fn() + Send + Sync + 'static> { let (chan, id) = (self.sender(), self.id); Arc::new(move || drop(chan.unbounded_send(SchedulerMsg::Immediate(id)))) } /// Schedule an update for any component given its [`ScopeId`]. /// /// A component's [`ScopeId`] can be obtained from `use_hook` or the [`current_scope_id`](crate::current_scope_id) method. /// /// This method should be used when you want to schedule an update for a component. /// /// Note: It does not matter when `schedule_update_any` is called: the returned function will invalidate what ever generation of the specified component is current when returned function is called. /// If the desired behavior is to schedule invalidation of the current rendering of a component, use [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead. pub(crate) fn schedule_update_any(&self) -> Arc<dyn Fn(ScopeId) + Send + Sync> { let chan = self.sender(); Arc::new(move |id| { _ = chan.unbounded_send(SchedulerMsg::Immediate(id)); }) } /// Get the owner for the current scope. pub(crate) fn owner<S: AnyStorage>(&self) -> Owner<S> { match self.has_context() { Some(rt) => rt, None => { let owner = S::owner(); self.provide_context(owner) } } } /// Return any context of type T if it exists on this scope pub(crate) fn has_context<T: 'static + Clone>(&self) -> Option<T> { self.shared_contexts .borrow() .iter() .find_map(|any| any.downcast_ref::<T>()) .cloned() } /// Try to retrieve a shared state with type `T` from any parent scope. /// /// Clones the state if it exists. pub(crate) fn consume_context<T: 'static + Clone>(&self) -> Option<T> { if let Some(this_ctx) = self.has_context::<T>() { return Some(this_ctx); } let mut search_parent = self.parent_id; Runtime::with(|runtime| { while let Some(parent_id) = search_parent { let parent = runtime.try_get_state(parent_id)?; if let Some(shared) = parent.has_context::<T>() { return Some(shared); } search_parent = parent.parent_id; } None }) } /// Inject a `Box<dyn Any>` into the context of this scope pub(crate) fn provide_any_context(&self, mut value: Box<dyn Any>) { let mut contexts = self.shared_contexts.borrow_mut(); // If the context exists, swap it out for the new value for ctx in contexts.iter_mut() { // Swap the ptr directly if ctx.as_ref().type_id() == value.as_ref().type_id() { std::mem::swap(ctx, &mut value); return; } } // Else, just push it contexts.push(value); } /// Expose state to children further down the [`crate::VirtualDom`] Tree. Requires `Clone` on the context to allow getting values down the tree. /// /// This is a "fundamental" operation and should only be called during initialization of a hook. /// /// For a hook that provides the same functionality, use `use_provide_context` and `use_context` instead. /// /// # Example /// /// ```rust /// # use dioxus::prelude::*; /// #[derive(Clone)] /// struct SharedState(&'static str); /// /// // The parent provides context that is available in all children /// fn app() -> Element { /// use_hook(|| provide_context(SharedState("world"))); /// rsx!(Child {}) /// } /// /// // Any child elements can access the context with the `consume_context` function /// fn Child() -> Element { /// let state = use_context::<SharedState>(); /// rsx!(div { "hello {state.0}" }) /// } /// ``` pub(crate) fn provide_context<T: 'static + Clone>(&self, value: T) -> T { let mut contexts = self.shared_contexts.borrow_mut(); // If the context exists, swap it out for the new value for ctx in contexts.iter_mut() { // Swap the ptr directly if let Some(ctx) = ctx.downcast_mut::<T>() { *ctx = value.clone(); return value; } } // Else, just push it contexts.push(Box::new(value.clone())); value } /// Provide a context to the root and then consume it /// /// This is intended for "global" state management solutions that would rather be implicit for the entire app. /// Things like signal runtimes and routers are examples of "singletons" that would benefit from lazy initialization. /// /// Note that you should be checking if the context existed before trying to provide a new one. Providing a context /// when a context already exists will swap the context out for the new one, which may not be what you want. pub(crate) fn provide_root_context<T: 'static + Clone>(&self, context: T) -> T { Runtime::with(|runtime| runtime.get_state(ScopeId::ROOT).provide_context(context)) } /// Start a new future on the same thread as the rest of the VirtualDom. /// /// **You should generally use `spawn` instead of this method unless you specifically need to need to run a task during suspense** /// /// This future will not contribute to suspense resolving but it will run during suspense. /// /// Because this future runs during suspense, you need to be careful to work with hydration. It is not recommended to do any async IO work in this future, as it can easily cause hydration issues. However, you can use isomorphic tasks to do work that can be consistently replicated on the server and client like logging or responding to state changes. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::spawn_isomorphic; /// // ❌ Do not do requests in isomorphic tasks. It may resolve at a different time on the server and client, causing hydration issues. /// let mut state = use_signal(|| None); /// spawn_isomorphic(async move { /// state.set(Some(reqwest::get("https://api.example.com").await)); /// }); /// /// // ✅ You may wait for a signal to change and then log it /// let mut state = use_signal(|| 0); /// spawn_isomorphic(async move { /// loop { /// tokio::time::sleep(std::time::Duration::from_secs(1)).await; /// println!("State is {state}"); /// } /// }); /// ``` pub(crate) fn spawn_isomorphic(&self, fut: impl Future<Output = ()> + 'static) -> Task { let id = Runtime::with(|rt| rt.spawn_isomorphic(self.id, fut)); self.spawned_tasks.borrow_mut().insert(id); id } /// Spawns the future and returns the [`Task`] pub(crate) fn spawn(&self, fut: impl Future<Output = ()> + 'static) -> Task { let id = Runtime::with(|rt| rt.spawn(self.id, fut)); self.spawned_tasks.borrow_mut().insert(id); id } /// Queue an effect to run after the next render pub(crate) fn queue_effect(&self, f: impl FnOnce() + 'static) { Runtime::with(|rt| rt.queue_effect(self.id, f)); } /// Store a value in the hook list, returning the value. pub(crate) fn use_hook<State: Clone + 'static>( &self, initializer: impl FnOnce() -> State, ) -> State { let cur_hook = self.hook_index.get(); // The hook list works by keeping track of the current hook index and pushing the index forward // while retrieving the hook value. self.hook_index.set(cur_hook + 1); let mut hooks = self.hooks .try_borrow_mut() .expect("The hook list is already borrowed: This error is likely caused by trying to use hook inside a hook which violates the rules of hooks."); // Try and retrieve the hook value if it exists if let Some(existing) = self.use_hook_inner::<State>(&mut hooks, cur_hook) { return existing; } // Otherwise, initialize the hook value. In debug mode, we allow hook types to change after a hot patch self.push_hook_value(&mut hooks, cur_hook, initializer()) } // The interior version that gets monomorphized by the `State` type but not the `initializer` type. // This helps trim down binary sizes fn use_hook_inner<State: Clone + 'static>( &self, hooks: &mut Vec<Box<dyn std::any::Any>>, cur_hook: usize, ) -> Option<State> { hooks.get(cur_hook).and_then(|inn| { let raw_ref: &dyn Any = inn.as_ref(); raw_ref.downcast_ref::<State>().cloned() }) } /// Push a new hook value or insert the value into the existing slot, warning if this is not after a hot patch fn push_hook_value<State: Clone + 'static>( &self, hooks: &mut Vec<Box<dyn std::any::Any>>, cur_hook: usize, value: State, ) -> State { // If this is a new hook, push it if cur_hook >= hooks.len() { hooks.push(Box::new(value.clone())); return value; } // If we're in dev mode, we allow swapping hook values if the hook was initialized at this index if cfg!(debug_assertions) && unsafe { subsecond::get_jump_table().is_some() } { hooks[cur_hook] = Box::new(value.clone()); return value; } // Otherwise, panic panic!( r#"Unable to retrieve the hook that was initialized at this index. Consult the `rules of hooks` to understand how to use hooks properly. You likely used the hook in a conditional. Hooks rely on consistent ordering between renders. Functions prefixed with "use" should never be called conditionally. Help: Run `dx check` to look for check for some common hook errors."# ); } pub(crate) fn push_before_render(&self, f: impl FnMut() + 'static) { self.before_render.borrow_mut().push(Box::new(f)); } pub(crate) fn push_after_render(&self, f: impl FnMut() + 'static) { self.after_render.borrow_mut().push(Box::new(f)); } /// Get the current render since the inception of this component /// /// This can be used as a helpful diagnostic when debugging hooks/renders, etc pub(crate) fn generation(&self) -> usize { self.render_count.get() } /// Get the height of this scope pub(crate) fn height(&self) -> u32 { self.height } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/scopes.rs
packages/core/src/scopes.rs
use crate::{ any_props::BoxedAnyProps, reactive_context::ReactiveContext, scope_context::Scope, Element, RenderError, Runtime, VNode, }; use std::{cell::Ref, rc::Rc}; /// A component's unique identifier. /// /// `ScopeId` is a `usize` that acts a key for the internal slab of Scopes. This means that the key is not unique across /// time. We do try and guarantee that between calls to `wait_for_work`, no ScopeIds will be recycled in order to give /// time for any logic that relies on these IDs to properly update. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct ScopeId(pub usize); impl std::fmt::Debug for ScopeId { #[allow(unused_mut)] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut builder = f.debug_tuple("ScopeId"); let mut builder = builder.field(&self.0); #[cfg(debug_assertions)] { if let Some(scope) = Runtime::try_current() .as_ref() .and_then(|r| r.try_get_state(*self)) { builder = builder.field(&scope.name); } } builder.finish() } } impl ScopeId { /// The ScopeId of the main scope passed into [`crate::VirtualDom::new`]. /// /// This scope will last for the entire duration of your app, making it convenient for long-lived state /// that is created dynamically somewhere down the component tree. /// /// # Example /// /// ```rust, no_run /// use dioxus::prelude::*; /// let my_persistent_state = Signal::new_in_scope(String::new(), ScopeId::APP); /// ``` // ScopeId(0) is the root scope wrapper // ScopeId(1) is the default suspense boundary // ScopeId(2) is the default error boundary // ScopeId(3) is the users root scope pub const APP: ScopeId = ScopeId(3); /// The ScopeId of the topmost error boundary in the tree. pub const ROOT_ERROR_BOUNDARY: ScopeId = ScopeId(2); /// The ScopeId of the topmost suspense boundary in the tree. pub const ROOT_SUSPENSE_BOUNDARY: ScopeId = ScopeId(1); /// The ScopeId of the topmost scope in the tree. /// This will be higher up in the tree than [`ScopeId::APP`] because dioxus inserts a default [`crate::SuspenseBoundary`] and [`crate::ErrorBoundary`] at the root of the tree. // ScopeId(0) is the root scope wrapper pub const ROOT: ScopeId = ScopeId(0); pub(crate) const PLACEHOLDER: ScopeId = ScopeId(usize::MAX); pub(crate) fn is_placeholder(&self) -> bool { *self == Self::PLACEHOLDER } } /// A component's rendered state. /// /// This state erases the type of the component's props. It is used to store the state of a component in the runtime. pub struct ScopeState { pub(crate) runtime: Rc<Runtime>, pub(crate) context_id: ScopeId, /// The last node that has been rendered for this component. This node may not ben mounted /// During suspense, this component can be rendered in the background multiple times pub(crate) last_rendered_node: Option<LastRenderedNode>, pub(crate) props: BoxedAnyProps, pub(crate) reactive_context: ReactiveContext, } impl ScopeState { /// Get a handle to the currently active head node arena for this Scope /// /// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR. /// /// Panics if the tree has not been built yet. pub fn root_node(&self) -> &VNode { self.try_root_node() .expect("The tree has not been built yet. Make sure to call rebuild on the tree before accessing its nodes.") } /// Try to get a handle to the currently active head node arena for this Scope /// /// This is useful for traversing the tree outside of the VirtualDom, such as in a custom renderer or in SSR. /// /// Returns [`None`] if the tree has not been built yet. pub fn try_root_node(&self) -> Option<&VNode> { match &self.last_rendered_node { Some(LastRenderedNode::Real(vnode)) => Some(vnode), Some(LastRenderedNode::Placeholder(vnode, _)) => Some(vnode), None => None, } } /// Returns the scope id of this [`ScopeState`]. pub fn id(&self) -> ScopeId { self.context_id } pub(crate) fn state(&self) -> Ref<'_, Scope> { self.runtime.get_state(self.context_id) } /// Returns the height of this scope in the tree. pub fn height(&self) -> u32 { self.state().height() } } #[derive(Clone, PartialEq, Debug)] pub enum LastRenderedNode { Real(VNode), Placeholder(VNode, RenderError), } impl std::ops::Deref for LastRenderedNode { type Target = VNode; fn deref(&self) -> &Self::Target { match self { LastRenderedNode::Real(vnode) => vnode, LastRenderedNode::Placeholder(vnode, _err) => vnode, } } } impl LastRenderedNode { pub fn new(node: Element) -> Self { match node { Ok(vnode) => LastRenderedNode::Real(vnode), Err(err) => LastRenderedNode::Placeholder(VNode::placeholder(), err), } } pub fn as_vnode(&self) -> &VNode { match self { LastRenderedNode::Real(vnode) => vnode, LastRenderedNode::Placeholder(vnode, _err) => vnode, } } } impl Drop for ScopeState { fn drop(&mut self) { self.runtime.remove_scope(self.context_id); } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/scheduler.rs
packages/core/src/scheduler.rs
//! # Dioxus uses a scheduler to run queued work in the correct order. //! //! ## Goals //! We try to prevent three different situations: //! 1. Running queued work after it could be dropped. Related issues (<https://github.com/DioxusLabs/dioxus/pull/1993>) //! //! User code often assumes that this property is true. For example, if this code reruns the child component after signal is changed to None, it will panic //! ```rust, ignore //! fn ParentComponent() -> Element { //! let signal: Signal<Option<i32>> = use_signal(None); //! //! rsx! { //! if signal.read().is_some() { //! ChildComponent { signal } //! } //! } //! } //! //! #[component] //! fn ChildComponent(signal: WriteSignal<Option<i32>>) -> Element { //! // It feels safe to assume that signal is some because the parent component checked that it was some //! rsx! { "{signal.read().unwrap()}" } //! } //! ``` //! //! 2. Running effects before the dom is updated. Related issues (<https://github.com/DioxusLabs/dioxus/issues/2307>) //! //! Effects can be used to run code that accesses the DOM directly. They should only run when the DOM is in an updated state. If they are run with an out of date version of the DOM, unexpected behavior can occur. //! ```rust, ignore //! fn EffectComponent() -> Element { //! let id = use_signal(0); //! use_effect(move || { //! let id = id.read(); //! // This will panic if the id is not written to the DOM before the effect is run //! document::eval(format!(r#"document.getElementById("{id}").innerHTML = "Hello World";"#)); //! }); //! //! rsx! { //! div { id: "{id}" } //! } //! } //! ``` //! //! 3. Observing out of date state. Related issues (<https://github.com/DioxusLabs/dioxus/issues/1935>) //! //! Where ever possible, updates should happen in an order that makes it impossible to observe an out of date state. //! ```rust, ignore //! fn OutOfDateComponent() -> Element { //! let id = use_signal(0); //! // When you read memo, it should **always** be two times the value of id //! let memo = use_memo(move || id() * 2); //! assert_eq!(memo(), id() * 2); //! //! // This should be true even if you update the value of id in the middle of the component //! id += 1; //! assert_eq!(memo(), id() * 2); //! //! rsx! { //! div { id: "{id}" } //! } //! } //! ``` //! //! ## Implementation //! //! There are three different types of queued work that can be run by the virtualdom: //! 1. Dirty Scopes: //! Description: When a scope is marked dirty, a rerun of the scope will be scheduled. This will cause the scope to rerun and update the DOM if any changes are detected during the diffing phase. //! Priority: These are the highest priority tasks. Dirty scopes will be rerun in order from the scope closest to the root to the scope furthest from the root. We follow this order to ensure that if a higher component reruns and drops a lower component, the lower component will not be run after it should be dropped. //! //! 2. Tasks: //! Description: Futures spawned in the dioxus runtime each have an unique task id. When the waker for that future is called, the task is rerun. //! Priority: These are the second highest priority tasks. They are run after all other dirty scopes have been resolved because those dirty scopes may cause children (and the tasks those children own) to drop which should cancel the futures. //! //! 3. Effects: //! Description: Effects should always run after all changes to the DOM have been applied. //! Priority: These are the lowest priority tasks in the scheduler. They are run after all other dirty scopes and futures have been resolved. Other tasks may cause components to rerun, which would update the DOM. These effects should only run after the DOM has been updated. use crate::innerlude::Effect; use crate::ScopeId; use crate::Task; use crate::VirtualDom; use std::borrow::Borrow; use std::cell::RefCell; use std::collections::VecDeque; use std::hash::Hash; #[derive(Debug, Clone, Copy, Eq)] pub struct ScopeOrder { pub(crate) height: u32, pub(crate) id: ScopeId, } impl ScopeOrder { pub fn new(height: u32, id: ScopeId) -> Self { Self { height, id } } } impl PartialEq for ScopeOrder { fn eq(&self, other: &Self) -> bool { self.id == other.id } } impl PartialOrd for ScopeOrder { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for ScopeOrder { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.height.cmp(&other.height).then(self.id.cmp(&other.id)) } } impl Hash for ScopeOrder { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.id.hash(state); } } impl VirtualDom { /// Queue a task to be polled pub(crate) fn queue_task(&mut self, task: Task, order: ScopeOrder) { let mut dirty_tasks = self.runtime.dirty_tasks.borrow_mut(); match dirty_tasks.get(&order) { Some(scope) => scope.queue_task(task), None => { let scope = DirtyTasks::from(order); scope.queue_task(task); dirty_tasks.insert(scope); } } } /// Queue a scope to be rerendered pub(crate) fn queue_scope(&mut self, order: ScopeOrder) { self.dirty_scopes.insert(order); } /// Check if there are any dirty scopes pub(crate) fn has_dirty_scopes(&self) -> bool { !self.dirty_scopes.is_empty() } /// Take the top task from the highest scope pub(crate) fn pop_task(&mut self) -> Option<Task> { let mut dirty_tasks = self.runtime.dirty_tasks.borrow_mut(); let tasks = dirty_tasks.first()?; // The scope that owns the effect should still exist. We can't just ignore the task if the scope doesn't exist // because the scope id may have been reallocated debug_assert!(self.scopes.contains(tasks.order.id.0)); let mut tasks = tasks.tasks_queued.borrow_mut(); let task = tasks.pop_front()?; if tasks.is_empty() { drop(tasks); dirty_tasks.pop_first(); } Some(task) } /// Take any effects from the highest scope. This should only be called if there is no pending scope reruns or tasks pub(crate) fn pop_effect(&mut self) -> Option<Effect> { let mut pending_effects = self.runtime.pending_effects.borrow_mut(); let effect = pending_effects.pop_first()?; // The scope that owns the effect should still exist. We can't just ignore the effect if the scope doesn't exist // because the scope id may have been reallocated debug_assert!(self.scopes.contains(effect.order.id.0)); Some(effect) } /// Take any work from the highest scope. This may include rerunning the scope and/or running tasks pub(crate) fn pop_work(&mut self) -> Option<Work> { let dirty_scope = self.dirty_scopes.first(); // Make sure the top dirty scope is valid #[cfg(debug_assertions)] if let Some(scope) = dirty_scope { assert!(self.scopes.contains(scope.id.0)); } // Find the height of the highest dirty scope let dirty_task = { let mut dirty_tasks = self.runtime.dirty_tasks.borrow_mut(); let mut dirty_task = dirty_tasks.first(); // Pop any invalid tasks off of each dirty scope; while let Some(task) = dirty_task { if task.tasks_queued.borrow().is_empty() { dirty_tasks.pop_first(); dirty_task = dirty_tasks.first() } else { break; } } dirty_task.map(|task| task.order) }; match (dirty_scope, dirty_task) { (Some(scope), Some(task)) => { let tasks_order = task.borrow(); match scope.cmp(tasks_order) { std::cmp::Ordering::Less => { let scope = self.dirty_scopes.pop_first().unwrap(); Some(Work::RerunScope(scope)) } std::cmp::Ordering::Equal | std::cmp::Ordering::Greater => { Some(Work::PollTask(self.pop_task().unwrap())) } } } (Some(_), None) => { let scope = self.dirty_scopes.pop_first().unwrap(); Some(Work::RerunScope(scope)) } (None, Some(_)) => Some(Work::PollTask(self.pop_task().unwrap())), (None, None) => None, } } } #[derive(Debug)] pub enum Work { RerunScope(ScopeOrder), PollTask(Task), } #[derive(Debug, Clone, Eq)] pub(crate) struct DirtyTasks { pub order: ScopeOrder, pub tasks_queued: RefCell<VecDeque<Task>>, } impl From<ScopeOrder> for DirtyTasks { fn from(order: ScopeOrder) -> Self { Self { order, tasks_queued: VecDeque::new().into(), } } } impl DirtyTasks { pub fn queue_task(&self, task: Task) { let mut borrow_mut = self.tasks_queued.borrow_mut(); // If the task is already queued, we don't need to do anything if borrow_mut.contains(&task) { return; } borrow_mut.push_back(task); } pub(crate) fn remove(&self, id: Task) { self.tasks_queued.borrow_mut().retain(|task| *task != id); } } impl Borrow<ScopeOrder> for DirtyTasks { fn borrow(&self) -> &ScopeOrder { &self.order } } impl Ord for DirtyTasks { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.order.cmp(&other.order) } } impl PartialOrd for DirtyTasks { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl PartialEq for DirtyTasks { fn eq(&self, other: &Self) -> bool { self.order == other.order } } impl Hash for DirtyTasks { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.order.hash(state); } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/any_props.rs
packages/core/src/any_props.rs
use crate::{innerlude::CapturedPanic, ComponentFunction, Element}; use std::{any::Any, panic::AssertUnwindSafe}; pub(crate) type BoxedAnyProps = Box<dyn AnyProps>; /// A trait for a component that can be rendered. pub(crate) trait AnyProps: 'static { /// Render the component with the internal props. fn render(&self) -> Element; /// Make the old props equal to the new type erased props. Return if the props were equal and should be memoized. fn memoize(&mut self, other: &dyn Any) -> bool; /// Get the props as a type erased `dyn Any`. fn props(&self) -> &dyn Any; /// Get the props as a type erased `dyn Any`. fn props_mut(&mut self) -> &mut dyn Any; /// Duplicate this component into a new boxed component. fn duplicate(&self) -> BoxedAnyProps; } /// A component along with the props the component uses to render. pub(crate) struct VProps<F: ComponentFunction<P, M>, P, M> { render_fn: F, memo: fn(&mut P, &P) -> bool, props: P, name: &'static str, phantom: std::marker::PhantomData<M>, } impl<F: ComponentFunction<P, M>, P: Clone, M> Clone for VProps<F, P, M> { fn clone(&self) -> Self { Self { render_fn: self.render_fn.clone(), memo: self.memo, props: self.props.clone(), name: self.name, phantom: std::marker::PhantomData, } } } impl<F: ComponentFunction<P, M> + Clone, P: Clone + 'static, M: 'static> VProps<F, P, M> { /// Create a [`VProps`] object. pub fn new( render_fn: F, memo: fn(&mut P, &P) -> bool, props: P, name: &'static str, ) -> VProps<F, P, M> { VProps { render_fn, memo, props, name, phantom: std::marker::PhantomData, } } } impl<F: ComponentFunction<P, M> + Clone, P: Clone + 'static, M: 'static> AnyProps for VProps<F, P, M> { fn memoize(&mut self, other: &dyn Any) -> bool { match other.downcast_ref::<P>() { Some(other) => (self.memo)(&mut self.props, other), None => false, } } fn props(&self) -> &dyn Any { &self.props } fn props_mut(&mut self) -> &mut dyn Any { &mut self.props } fn render(&self) -> Element { fn render_inner(_name: &str, res: Result<Element, Box<dyn Any + Send>>) -> Element { match res { Ok(node) => node, Err(err) => { // on wasm this massively bloats binary sizes and we can't even capture the panic // so do nothing #[cfg(not(target_arch = "wasm32"))] { tracing::error!("Panic while rendering component `{_name}`: {err:?}"); } Element::Err(CapturedPanic(err).into()) } } } render_inner( self.name, std::panic::catch_unwind(AssertUnwindSafe(move || { self.render_fn.rebuild(self.props.clone()) })), ) } fn duplicate(&self) -> BoxedAnyProps { Box::new(Self { render_fn: self.render_fn.clone(), memo: self.memo, props: self.props.clone(), name: self.name, phantom: std::marker::PhantomData, }) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/global_context.rs
packages/core/src/global_context.rs
use crate::innerlude::CapturedError; use crate::{innerlude::SuspendedFuture, runtime::Runtime, Element, ScopeId, Task}; use std::future::Future; use std::rc::Rc; use std::sync::Arc; /// Get the current scope id pub fn current_scope_id() -> ScopeId { Runtime::with(|rt| rt.current_scope_id()) } /// Throw a [`CapturedError`] into the current scope. The error will bubble up to the nearest [`crate::ErrorBoundary()`] or the root of the app. /// /// # Examples /// ```rust, no_run /// # use dioxus::prelude::*; /// fn Component() -> Element { /// let request = spawn(async move { /// match reqwest::get("https://api.example.com").await { /// Ok(_) => unimplemented!(), /// // You can explicitly throw an error into a scope with throw_error /// Err(err) => dioxus::core::throw_error(err), /// } /// }); /// /// unimplemented!() /// } /// ``` pub fn throw_error(error: impl Into<CapturedError> + 'static) { Runtime::with(|rt| rt.throw_error(rt.current_scope_id(), error)) } /// Consume context from the current scope pub fn try_consume_context<T: 'static + Clone>() -> Option<T> { Runtime::with_current_scope(|cx| cx.consume_context::<T>()) } /// Consume context from the current scope pub fn consume_context<T: 'static + Clone>() -> T { Runtime::with_current_scope(|cx| cx.consume_context::<T>()) .unwrap_or_else(|| panic!("Could not find context {}", std::any::type_name::<T>())) } /// Consume context from the current scope pub fn consume_context_from_scope<T: 'static + Clone>(scope_id: ScopeId) -> Option<T> { Runtime::current() .try_get_state(scope_id) .and_then(|cx| cx.consume_context::<T>()) } /// Check if the current scope has a context pub fn has_context<T: 'static + Clone>() -> Option<T> { Runtime::with_current_scope(|cx| cx.has_context::<T>()) } /// Provide context to the current scope pub fn provide_context<T: 'static + Clone>(value: T) -> T { Runtime::with_current_scope(|cx| cx.provide_context(value)) } /// Provide a context to the root scope pub fn provide_root_context<T: 'static + Clone>(value: T) -> T { Runtime::with_current_scope(|cx| cx.provide_root_context(value)) } /// Suspended the current component on a specific task and then return None pub fn suspend(task: Task) -> Element { Err(crate::innerlude::RenderError::Suspended( SuspendedFuture::new(task), )) } /// Start a new future on the same thread as the rest of the VirtualDom. /// /// **You should generally use `spawn` instead of this method unless you specifically need to run a task during suspense** /// /// This future will not contribute to suspense resolving but it will run during suspense. /// /// Because this future runs during suspense, you need to be careful to work with hydration. It is not recommended to do any async IO work in this future, as it can easily cause hydration issues. However, you can use isomorphic tasks to do work that can be consistently replicated on the server and client like logging or responding to state changes. /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # use dioxus_core::spawn_isomorphic; /// // ❌ Do not do requests in isomorphic tasks. It may resolve at a different time on the server and client, causing hydration issues. /// let mut state = use_signal(|| None); /// spawn_isomorphic(async move { /// state.set(Some(reqwest::get("https://api.example.com").await)); /// }); /// /// // ✅ You may wait for a signal to change and then log it /// let mut state = use_signal(|| 0); /// spawn_isomorphic(async move { /// loop { /// tokio::time::sleep(std::time::Duration::from_secs(1)).await; /// println!("State is {state}"); /// } /// }); /// ``` /// #[doc = include_str!("../docs/common_spawn_errors.md")] pub fn spawn_isomorphic(fut: impl Future<Output = ()> + 'static) -> Task { Runtime::with_current_scope(|cx| cx.spawn_isomorphic(fut)) } /// Spawns the future and returns the [`Task`]. This task will automatically be canceled when the component is dropped. /// /// # Example /// ```rust /// use dioxus::prelude::*; /// /// fn App() -> Element { /// rsx! { /// button { /// onclick: move |_| { /// spawn(async move { /// tokio::time::sleep(std::time::Duration::from_secs(1)).await; /// println!("Hello World"); /// }); /// }, /// "Print hello in one second" /// } /// } /// } /// ``` /// #[doc = include_str!("../docs/common_spawn_errors.md")] pub fn spawn(fut: impl Future<Output = ()> + 'static) -> Task { Runtime::with_current_scope(|cx| cx.spawn(fut)) } /// Queue an effect to run after the next render. You generally shouldn't need to interact with this function directly. [use_effect](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html) will call this function for you. pub fn queue_effect(f: impl FnOnce() + 'static) { Runtime::with_current_scope(|cx| cx.queue_effect(f)) } /// Spawn a future that Dioxus won't clean up when this component is unmounted /// /// This is good for tasks that need to be run after the component has been dropped. /// /// **This will run the task in the root scope. Any calls to global methods inside the future (including `context`) will be run in the root scope.** /// /// # Example /// /// ```rust /// use dioxus::prelude::*; /// use dioxus_core::spawn_forever; /// /// // The parent component can create and destroy children dynamically /// fn App() -> Element { /// let mut count = use_signal(|| 0); /// /// rsx! { /// button { /// onclick: move |_| count += 1, /// "Increment" /// } /// button { /// onclick: move |_| count -= 1, /// "Decrement" /// } /// /// for id in 0..10 { /// Child { id } /// } /// } /// } /// /// #[component] /// fn Child(id: i32) -> Element { /// rsx! { /// button { /// onclick: move |_| { /// // This will spawn a task in the root scope that will run forever /// // It will keep running even if you drop the child component by decreasing the count /// spawn_forever(async move { /// loop { /// tokio::time::sleep(std::time::Duration::from_secs(1)).await; /// println!("Running task spawned in child component {id}"); /// } /// }); /// }, /// "Spawn background task" /// } /// } /// } /// ``` /// #[doc = include_str!("../docs/common_spawn_errors.md")] pub fn spawn_forever(fut: impl Future<Output = ()> + 'static) -> Task { Runtime::with_scope(ScopeId::ROOT, |cx| cx.spawn(fut)) } /// Informs the scheduler that this task is no longer needed and should be removed. /// /// This drops the task immediately. pub fn remove_future(id: Task) { Runtime::with(|rt| rt.remove_task(id)); } /// Store a value between renders. The foundational hook for all other hooks. /// /// Accepts an `initializer` closure, which is run on the first use of the hook (typically the initial render). /// `use_hook` will return a clone of the value on every render. /// /// In order to clean up resources you would need to implement the [`Drop`] trait for an inner value stored in a RC or similar (Signals for instance), /// as these only drop their inner value once all references have been dropped, which only happens when the component is dropped. /// /// <div class="warning"> /// /// `use_hook` is not reactive. It just returns the value on every render. If you need state that will track changes, use [`use_signal`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_signal.html) instead. /// /// ❌ Don't use `use_hook` with `Rc<RefCell<T>>` for state. It will not update the UI and other hooks when the state changes. /// ```rust /// use dioxus::prelude::*; /// use std::rc::Rc; /// use std::cell::RefCell; /// /// pub fn Comp() -> Element { /// let count = use_hook(|| Rc::new(RefCell::new(0))); /// /// rsx! { /// button { /// onclick: move |_| *count.borrow_mut() += 1, /// "{count.borrow()}" /// } /// } /// } /// ``` /// /// ✅ Use `use_signal` instead. /// ```rust /// use dioxus::prelude::*; /// /// pub fn Comp() -> Element { /// let mut count = use_signal(|| 0); /// /// rsx! { /// button { /// onclick: move |_| count += 1, /// "{count}" /// } /// } /// } /// ``` /// /// </div> /// /// # Example /// /// ```rust, no_run /// use dioxus::prelude::*; /// /// // prints a greeting on the initial render /// pub fn use_hello_world() { /// use_hook(|| println!("Hello, world!")); /// } /// ``` /// /// # Custom Hook Example /// /// ```rust, no_run /// use dioxus::prelude::*; /// /// pub struct InnerCustomState(usize); /// /// impl Drop for InnerCustomState { /// fn drop(&mut self){ /// println!("Component has been dropped."); /// } /// } /// /// #[derive(Clone, Copy)] /// pub struct CustomState { /// inner: Signal<InnerCustomState> /// } /// /// pub fn use_custom_state() -> CustomState { /// use_hook(|| CustomState { /// inner: Signal::new(InnerCustomState(0)) /// }) /// } /// ``` #[track_caller] pub fn use_hook<State: Clone + 'static>(initializer: impl FnOnce() -> State) -> State { Runtime::with_current_scope(|cx| cx.use_hook(initializer)) } /// Get the current render since the inception of this component. /// /// This can be used as a helpful diagnostic when debugging hooks/renders, etc. pub fn generation() -> usize { Runtime::with_current_scope(|cx| cx.generation()) } /// Get the parent of the current scope if it exists. pub fn parent_scope() -> Option<ScopeId> { Runtime::with_current_scope(|cx| cx.parent_id()) } /// Mark the current scope as dirty, causing it to re-render. pub fn needs_update() { Runtime::with_current_scope(|cx| cx.needs_update()); } /// Mark the current scope as dirty, causing it to re-render. pub fn needs_update_any(id: ScopeId) { Runtime::with_current_scope(|cx| cx.needs_update_any(id)); } /// Schedule an update for the current component. /// /// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime. /// /// Note: The function returned by this method will schedule an update for the current component even if it has already updated between when `schedule_update` was called and when the returned function is called. /// If the desired behavior is to invalidate the current rendering of the current component (and no-op if already invalidated) /// [`subscribe`](crate::reactive_context::ReactiveContext::subscribe) to the [`current`](crate::reactive_context::ReactiveContext::current) [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead. /// /// You should prefer [`schedule_update_any`] if you need to update multiple components. #[track_caller] pub fn schedule_update() -> Arc<dyn Fn() + Send + Sync> { Runtime::with_current_scope(|cx| cx.schedule_update()) } /// Schedule an update for any component given its [`ScopeId`]. /// /// A component's [`ScopeId`] can be obtained from the [`current_scope_id`] method. /// /// Note: Unlike [`needs_update`], the function returned by this method will work outside of the dioxus runtime. /// /// Note: It does not matter when `schedule_update_any` is called: the returned function will invalidate what ever generation of the specified component is current when returned function is called. /// If the desired behavior is to schedule invalidation of the current rendering of a component, use [`ReactiveContext`](crate::reactive_context::ReactiveContext) instead. #[track_caller] pub fn schedule_update_any() -> Arc<dyn Fn(ScopeId) + Send + Sync> { Runtime::with_current_scope(|cx| cx.schedule_update_any()) } /// Creates a callback that will be run before the component is removed. /// This can be used to clean up side effects from the component /// (created with [`use_effect`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html)). /// /// Note: /// Effects do not run on the server, but use_drop **DOES**. It runs any time the component is dropped including during SSR rendering on the server. If your clean up logic targets web, the logic has to be gated by a feature, see the below example for details. /// /// Example: /// ```rust /// use dioxus::prelude::*; /// use dioxus_core::use_drop; /// /// fn app() -> Element { /// let mut state = use_signal(|| true); /// rsx! { /// for _ in 0..100 { /// h1 { /// "spacer" /// } /// } /// if state() { /// child_component {} /// } /// button { /// onclick: move |_| { /// state.toggle() /// }, /// "Unmount element" /// } /// } /// } /// /// fn child_component() -> Element { /// let mut original_scroll_position = use_signal(|| 0.0); /// /// use_effect(move || { /// let window = web_sys::window().unwrap(); /// let document = window.document().unwrap(); /// let element = document.get_element_by_id("my_element").unwrap(); /// element.scroll_into_view(); /// original_scroll_position.set(window.scroll_y().unwrap()); /// }); /// /// use_drop(move || { /// // This only make sense to web and hence the `web!` macro /// web! { /// /// restore scroll to the top of the page /// let window = web_sys::window().unwrap(); /// window.scroll_with_x_and_y(original_scroll_position(), 0.0); /// } /// }); /// /// rsx! { /// div { /// id: "my_element", /// "hello" /// } /// } /// } /// ``` #[doc(alias = "use_on_unmount")] pub fn use_drop<D: FnOnce() + 'static>(destroy: D) { struct LifeCycle<D: FnOnce()> { /// Wrap the closure in an option so that we can take it out on drop. ondestroy: Option<D>, } /// On drop, we want to run the closure. impl<D: FnOnce()> Drop for LifeCycle<D> { fn drop(&mut self) { if let Some(f) = self.ondestroy.take() { f(); } } } use_hook(|| { Rc::new(LifeCycle { ondestroy: Some(destroy), }) }); } /// A hook that allows you to insert a "before render" function. /// /// This function will always be called before dioxus tries to render your component. This should be used for safely handling /// early returns pub fn use_before_render(f: impl FnMut() + 'static) { use_hook(|| Runtime::with_current_scope(|cx| cx.push_before_render(f))); } /// Push this function to be run after the next render /// /// This function will always be called before dioxus tries to render your component. This should be used for safely handling /// early returns pub fn use_after_render(f: impl FnMut() + 'static) { use_hook(|| Runtime::with_current_scope(|cx| cx.push_after_render(f))); } /// Use a hook with a cleanup function pub fn use_hook_with_cleanup<T: Clone + 'static>( hook: impl FnOnce() -> T, cleanup: impl FnOnce(T) + 'static, ) -> T { let value = use_hook(hook); let _value = value.clone(); use_drop(move || cleanup(_value)); value }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/diff/node.rs
packages/core/src/diff/node.rs
use crate::innerlude::MountId; use crate::{Attribute, AttributeValue, DynamicNode::*}; use crate::{VNode, VirtualDom, WriteMutations}; use core::iter::Peekable; use crate::{ arena::ElementId, innerlude::{ElementPath, ElementRef, VNodeMount, VText}, nodes::DynamicNode, scopes::ScopeId, TemplateNode, }; impl VNode { pub(crate) fn diff_node( &self, new: &VNode, dom: &mut VirtualDom, mut to: Option<&mut impl WriteMutations>, ) { // The node we are diffing from should always be mounted debug_assert!( dom.runtime .mounts .borrow() .get(self.mount.get().0) .is_some() || to.is_none() ); // If the templates are different, we need to replace the entire template if self.template != new.template { let mount_id = self.mount.get(); let parent = dom.get_mounted_parent(mount_id); return self.replace(std::slice::from_ref(new), parent, dom, to); } self.move_mount_to(new, dom); // If the templates are the same, we don't need to do anything, except copy over the mount information if self == new { return; } // If the templates are the same, we can diff the attributes and children // Start with the attributes // Since the attributes are only side effects, we can skip diffing them entirely if the node is suspended and we aren't outputting mutations if let Some(to) = to.as_deref_mut() { self.diff_attributes(new, dom, to); } // Now diff the dynamic nodes let mount_id = new.mount.get(); for (dyn_node_idx, (old, new)) in self .dynamic_nodes .iter() .zip(new.dynamic_nodes.iter()) .enumerate() { self.diff_dynamic_node(mount_id, dyn_node_idx, old, new, dom, to.as_deref_mut()) } } fn move_mount_to(&self, new: &VNode, dom: &mut VirtualDom) { // Copy over the mount information let mount_id = self.mount.take(); new.mount.set(mount_id); if mount_id.mounted() { let mut mounts = dom.runtime.mounts.borrow_mut(); let mount = &mut mounts[mount_id.0]; // Update the reference to the node for bubbling events mount.node = new.clone(); } } fn diff_dynamic_node( &self, mount: MountId, idx: usize, old_node: &DynamicNode, new_node: &DynamicNode, dom: &mut VirtualDom, mut to: Option<&mut impl WriteMutations>, ) { tracing::trace!("diffing dynamic node from {old_node:?} to {new_node:?}"); match (old_node, new_node) { (Text(old), Text(new)) => { // Diffing text is just a side effect, if we are diffing suspended nodes and are not outputting mutations, we can skip it if let Some(to) = to { let id = ElementId(dom.get_mounted_dyn_node(mount, idx)); self.diff_vtext(to, id, old, new) } } (Placeholder(_), Placeholder(_)) => {} (Fragment(old), Fragment(new)) => dom.diff_non_empty_fragment( to, old, new, Some(self.reference_to_dynamic_node(mount, idx)), ), (Component(old), Component(new)) => { let scope_id = ScopeId(dom.get_mounted_dyn_node(mount, idx)); self.diff_vcomponent( mount, idx, new, old, scope_id, Some(self.reference_to_dynamic_node(mount, idx)), dom, to, ) } (old, new) => { // TODO: we should pass around the mount instead of the mount id // that would make moving the mount around here much easier // Mark the mount as unused. When a scope is created, it reads the mount and // if it is the placeholder value, it will create the scope, otherwise it will // reuse the scope let old_mount = dom.get_mounted_dyn_node(mount, idx); dom.set_mounted_dyn_node(mount, idx, usize::MAX); let new_nodes_on_stack = self.create_dynamic_node(new, mount, idx, dom, to.as_deref_mut()); // Restore the mount for the scope we are removing let new_mount = dom.get_mounted_dyn_node(mount, idx); dom.set_mounted_dyn_node(mount, idx, old_mount); self.remove_dynamic_node(mount, dom, to, true, idx, old, Some(new_nodes_on_stack)); // Restore the mount for the node we created dom.set_mounted_dyn_node(mount, idx, new_mount); } }; } /// Try to get the dynamic node and its index for a root node pub(crate) fn get_dynamic_root_node_and_id( &self, root_idx: usize, ) -> Option<(usize, &DynamicNode)> { self.template.roots[root_idx] .dynamic_id() .map(|id| (id, &self.dynamic_nodes[id])) } pub(crate) fn find_first_element(&self, dom: &VirtualDom) -> ElementId { let mount_id = self.mount.get(); let first = match self.get_dynamic_root_node_and_id(0) { // This node is static, just get the root id None => dom.get_mounted_root_node(mount_id, 0), // If it is dynamic and shallow, grab the id from the mounted dynamic nodes Some((idx, Placeholder(_) | Text(_))) => { ElementId(dom.get_mounted_dyn_node(mount_id, idx)) } // The node is a fragment, so we need to find the first element in the fragment Some((_, Fragment(children))) => { let child = children.first().unwrap(); child.find_first_element(dom) } // The node is a component, so we need to find the first element in the component Some((id, Component(_))) => { let scope = ScopeId(dom.get_mounted_dyn_node(mount_id, id)); dom.get_scope(scope) .unwrap() .root_node() .find_first_element(dom) } }; // The first element should never be the default element id (the root element) debug_assert_ne!(first, ElementId::default()); first } pub(crate) fn find_last_element(&self, dom: &VirtualDom) -> ElementId { let mount_id = self.mount.get(); let last_root_index = self.template.roots.len() - 1; let last = match self.get_dynamic_root_node_and_id(last_root_index) { // This node is static, just get the root id None => dom.get_mounted_root_node(mount_id, last_root_index), // If it is dynamic and shallow, grab the id from the mounted dynamic nodes Some((idx, Placeholder(_) | Text(_))) => { ElementId(dom.get_mounted_dyn_node(mount_id, idx)) } // The node is a fragment, so we need to find the last element in the fragment Some((_, Fragment(children))) => { let child = children.last().unwrap(); child.find_last_element(dom) } // The node is a component, so we need to find the first element in the component Some((id, Component(_))) => { let scope = ScopeId(dom.get_mounted_dyn_node(mount_id, id)); dom.get_scope(scope) .unwrap() .root_node() .find_last_element(dom) } }; // The last element should never be the default element id (the root element) debug_assert_ne!(last, ElementId::default()); last } /// Diff the two text nodes /// /// This just sets the text of the node if it's different. fn diff_vtext(&self, to: &mut impl WriteMutations, id: ElementId, left: &VText, right: &VText) { if left.value != right.value { to.set_node_text(&right.value, id); } } pub(crate) fn replace( &self, right: &[VNode], parent: Option<ElementRef>, dom: &mut VirtualDom, to: Option<&mut impl WriteMutations>, ) { self.replace_inner(right, parent, dom, to, true) } /// Replace this node with new children, but *don't destroy* the old node's component state /// /// This is useful for moving a node from the rendered nodes into a suspended node pub(crate) fn move_node_to_background( &self, right: &[VNode], parent: Option<ElementRef>, dom: &mut VirtualDom, to: Option<&mut impl WriteMutations>, ) { self.replace_inner(right, parent, dom, to, false) } pub(crate) fn replace_inner( &self, right: &[VNode], parent: Option<ElementRef>, dom: &mut VirtualDom, mut to: Option<&mut impl WriteMutations>, destroy_component_state: bool, ) { let m = dom.create_children(to.as_deref_mut(), right, parent); // Instead of *just* removing it, we can use the replace mutation self.remove_node_inner(dom, to, destroy_component_state, Some(m)) } /// Remove a node from the dom and potentially replace it with the top m nodes from the stack pub(crate) fn remove_node<M: WriteMutations>( &self, dom: &mut VirtualDom, to: Option<&mut M>, replace_with: Option<usize>, ) { self.remove_node_inner(dom, to, true, replace_with) } /// Remove a node, but only maybe destroy the component state of that node. During suspense, we need to remove a node from the real dom without wiping the component state pub(crate) fn remove_node_inner<M: WriteMutations>( &self, dom: &mut VirtualDom, to: Option<&mut M>, destroy_component_state: bool, replace_with: Option<usize>, ) { let mount = self.mount.get(); if !mount.mounted() { return; } // Clean up any attributes that have claimed a static node as dynamic for mount/unmounts // Will not generate mutations! self.reclaim_attributes(mount, dom); // Remove the nested dynamic nodes // We don't generate mutations for these, as they will be removed by the parent (in the next line) // But we still need to make sure to reclaim them from the arena and drop their hooks, etc self.remove_nested_dyn_nodes::<M>(mount, dom, destroy_component_state); // Clean up the roots, assuming we need to generate mutations for these // This is done last in order to preserve Node ID reclaim order (reclaim in reverse order of claim) self.reclaim_roots(mount, dom, to, destroy_component_state, replace_with); if destroy_component_state { let mount = self.mount.take(); // Remove the mount information dom.runtime.mounts.borrow_mut().remove(mount.0); } } fn reclaim_roots( &self, mount: MountId, dom: &mut VirtualDom, mut to: Option<&mut impl WriteMutations>, destroy_component_state: bool, replace_with: Option<usize>, ) { let roots = self.template.roots; for (idx, node) in roots.iter().enumerate() { let last_node = idx == roots.len() - 1; if let Some(id) = node.dynamic_id() { let dynamic_node = &self.dynamic_nodes[id]; self.remove_dynamic_node( mount, dom, to.as_deref_mut(), destroy_component_state, id, dynamic_node, replace_with.filter(|_| last_node), ); } else if let Some(to) = to.as_deref_mut() { let id = dom.get_mounted_root_node(mount, idx); if let (true, Some(replace_with)) = (last_node, replace_with) { to.replace_node_with(id, replace_with); } else { to.remove_node(id); } dom.reclaim(id); } else { let id = dom.get_mounted_root_node(mount, idx); dom.reclaim(id); } } } fn remove_nested_dyn_nodes<M: WriteMutations>( &self, mount: MountId, dom: &mut VirtualDom, destroy_component_state: bool, ) { let template = self.template; for (idx, dyn_node) in self.dynamic_nodes.iter().enumerate() { let path_len = template.node_paths.get(idx).map(|path| path.len()); // Roots are cleaned up automatically above and nodes with a empty path are placeholders if let Some(2..) = path_len { self.remove_dynamic_node( mount, dom, Option::<&mut M>::None, destroy_component_state, idx, dyn_node, None, ) } } } fn remove_dynamic_node( &self, mount: MountId, dom: &mut VirtualDom, mut to: Option<&mut impl WriteMutations>, destroy_component_state: bool, idx: usize, node: &DynamicNode, replace_with: Option<usize>, ) { match node { Component(_comp) => { let scope_id = ScopeId(dom.get_mounted_dyn_node(mount, idx)); dom.remove_component_node(to, destroy_component_state, scope_id, replace_with); } Text(_) | Placeholder(_) => { let id = ElementId(dom.get_mounted_dyn_node(mount, idx)); if let Some(to) = to { if let Some(replace_with) = replace_with { to.replace_node_with(id, replace_with); } else { to.remove_node(id); } } dom.reclaim(id) } Fragment(nodes) => { for node in &nodes[..nodes.len() - 1] { node.remove_node_inner(dom, to.as_deref_mut(), destroy_component_state, None) } if let Some(last_node) = nodes.last() { last_node.remove_node_inner(dom, to, destroy_component_state, replace_with) } } }; } pub(super) fn reclaim_attributes(&self, mount: MountId, dom: &mut VirtualDom) { let mut next_id = None; for (idx, path) in self.template.attr_paths.iter().enumerate() { // We clean up the roots in the next step, so don't worry about them here if path.len() <= 1 { continue; } // only reclaim the new element if it's different from the previous one let new_id = dom.get_mounted_dyn_attr(mount, idx); if Some(new_id) != next_id { dom.reclaim(new_id); next_id = Some(new_id); } } } pub(super) fn diff_attributes( &self, new: &VNode, dom: &mut VirtualDom, to: &mut impl WriteMutations, ) { let mount_id = new.mount.get(); for (idx, (old_attrs, new_attrs)) in self .dynamic_attrs .iter() .zip(new.dynamic_attrs.iter()) .enumerate() { let mut old_attributes_iter = old_attrs.iter().peekable(); let mut new_attributes_iter = new_attrs.iter().peekable(); let attribute_id = dom.get_mounted_dyn_attr(mount_id, idx); let path = self.template.attr_paths[idx]; loop { match (old_attributes_iter.peek(), new_attributes_iter.peek()) { (Some(old_attribute), Some(new_attribute)) => { // check which name is greater match old_attribute.name.cmp(new_attribute.name) { // The two attributes are the same, so diff them std::cmp::Ordering::Equal => { let old = old_attributes_iter.next().unwrap(); let new = new_attributes_iter.next().unwrap(); // Volatile attributes are attributes that the browser may override so we always update them let volatile = old.volatile; // We only need to write the attribute if the attribute is volatile or the value has changed // and this is not an event listener. // Interpreters reference event listeners by name and element id, so we don't need to write them // even if the closure has changed. let attribute_changed = match (&old.value, &new.value) { (AttributeValue::Text(l), AttributeValue::Text(r)) => l != r, (AttributeValue::Float(l), AttributeValue::Float(r)) => l != r, (AttributeValue::Int(l), AttributeValue::Int(r)) => l != r, (AttributeValue::Bool(l), AttributeValue::Bool(r)) => l != r, (AttributeValue::Any(l), AttributeValue::Any(r)) => { !l.as_ref().any_cmp(r.as_ref()) } (AttributeValue::None, AttributeValue::None) => false, (AttributeValue::Listener(_), AttributeValue::Listener(_)) => { false } _ => true, }; if volatile || attribute_changed { self.write_attribute( path, new, attribute_id, mount_id, dom, to, ); } } // In a sorted list, if the old attribute name is first, then the new attribute is missing std::cmp::Ordering::Less => { let old = old_attributes_iter.next().unwrap(); self.remove_attribute(old, attribute_id, to) } // In a sorted list, if the new attribute name is first, then the old attribute is missing std::cmp::Ordering::Greater => { let new = new_attributes_iter.next().unwrap(); self.write_attribute(path, new, attribute_id, mount_id, dom, to); } } } (Some(_), None) => { let left = old_attributes_iter.next().unwrap(); self.remove_attribute(left, attribute_id, to) } (None, Some(_)) => { let right = new_attributes_iter.next().unwrap(); self.write_attribute(path, right, attribute_id, mount_id, dom, to) } (None, None) => break, } } } } fn remove_attribute(&self, attribute: &Attribute, id: ElementId, to: &mut impl WriteMutations) { match &attribute.value { AttributeValue::Listener(_) => { to.remove_event_listener(&attribute.name[2..], id); } _ => { to.set_attribute( attribute.name, attribute.namespace, &AttributeValue::None, id, ); } } } fn write_attribute( &self, path: &'static [u8], attribute: &Attribute, id: ElementId, mount: MountId, dom: &mut VirtualDom, to: &mut impl WriteMutations, ) { match &attribute.value { AttributeValue::Listener(_) => { let element_ref = ElementRef { path: ElementPath { path }, mount, }; let mut elements = dom.runtime.elements.borrow_mut(); elements[id.0] = Some(element_ref); to.create_event_listener(&attribute.name[2..], id); } _ => { to.set_attribute(attribute.name, attribute.namespace, &attribute.value, id); } } } /// Create this rsx block. This will create scopes from components that this rsx block contains, but it will not write anything to the DOM. pub(crate) fn create( &self, dom: &mut VirtualDom, parent: Option<ElementRef>, mut to: Option<&mut impl WriteMutations>, ) -> usize { // Get the most up to date template let template = self.template; // Initialize the mount information for this vnode if it isn't already mounted if !self.mount.get().mounted() { let mut mounts = dom.runtime.mounts.borrow_mut(); let entry = mounts.vacant_entry(); let mount = MountId(entry.key()); self.mount.set(mount); tracing::trace!(?self, ?mount, "creating template"); entry.insert(VNodeMount { node: self.clone(), parent, root_ids: vec![ElementId(0); template.roots.len()].into_boxed_slice(), mounted_attributes: vec![ElementId(0); template.attr_paths.len()] .into_boxed_slice(), mounted_dynamic_nodes: vec![usize::MAX; template.node_paths.len()] .into_boxed_slice(), }); } // Walk the roots, creating nodes and assigning IDs // nodes in an iterator of (dynamic_node_index, path) and attrs in an iterator of (attr_index, path) let mut nodes = template.node_paths.iter().copied().enumerate().peekable(); let mut attrs = template.attr_paths.iter().copied().enumerate().peekable(); // Get the mounted id of this block // At this point, we should have already mounted the block debug_assert!( dom.runtime.mounts.borrow().contains( self.mount .get() .as_usize() .expect("node should already be mounted"), ), "Tried to find mount {:?} in dom.mounts, but it wasn't there", self.mount.get() ); let mount = self.mount.get(); // Go through each root node and create the node, adding it to the stack. // Each node already exists in the template, so we can just clone it from the template let nodes_created = template .roots .iter() .enumerate() .map(|(root_idx, root)| { match root { TemplateNode::Dynamic { id } => { // Take a dynamic node off the depth first iterator nodes.next().unwrap(); // Then mount the node self.create_dynamic_node( &self.dynamic_nodes[*id], mount, *id, dom, to.as_deref_mut(), ) } // For static text and element nodes, just load the template root. This may be a placeholder or just a static node. We now know that each root node has a unique id TemplateNode::Text { .. } | TemplateNode::Element { .. } => { if let Some(to) = to.as_deref_mut() { self.load_template_root(mount, root_idx, dom, to); } // If this is an element, load in all of the placeholder or dynamic content under this root element too if matches!(root, TemplateNode::Element { .. }) { // !!VERY IMPORTANT!! // Write out all attributes before we load the children. Loading the children will change paths we rely on // to assign ids to elements with dynamic attributes if let Some(to) = to.as_deref_mut() { self.write_attrs(mount, &mut attrs, root_idx as u8, dom, to); } // This operation relies on the fact that the root node is the top node on the stack so we need to do it here self.load_placeholders( mount, &mut nodes, root_idx as u8, dom, to.as_deref_mut(), ); } // This creates one node on the stack 1 } } }) .sum(); // And return the number of nodes we created on the stack nodes_created } } impl VNode { /// Get a reference back into a dynamic node fn reference_to_dynamic_node(&self, mount: MountId, dynamic_node_id: usize) -> ElementRef { ElementRef { path: ElementPath { path: self.template.node_paths[dynamic_node_id], }, mount, } } pub(crate) fn create_dynamic_node( &self, node: &DynamicNode, mount: MountId, dynamic_node_id: usize, dom: &mut VirtualDom, to: Option<&mut impl WriteMutations>, ) -> usize { use DynamicNode::*; match node { Component(component) => { let parent = Some(self.reference_to_dynamic_node(mount, dynamic_node_id)); self.create_component_node(mount, dynamic_node_id, component, parent, dom, to) } Fragment(frag) => { let parent = Some(self.reference_to_dynamic_node(mount, dynamic_node_id)); dom.create_children(to, frag, parent) } Text(text) => { // If we are diffing suspended nodes and are not outputting mutations, we can skip it if let Some(to) = to { self.create_dynamic_text(mount, dynamic_node_id, text, dom, to) } else { 0 } } Placeholder(_) => { // If we are diffing suspended nodes and are not outputting mutations, we can skip it if let Some(to) = to { tracing::trace!("creating placeholder"); self.create_placeholder(mount, dynamic_node_id, dom, to) } else { tracing::trace!("skipping creating placeholder"); 0 } } } } /// Load all of the placeholder nodes for descendent of this root node /// /// ```rust, no_run /// # use dioxus::prelude::*; /// # let some_text = "hello world"; /// # let some_value = "123"; /// rsx! { /// div { // We just wrote this node /// // This is a placeholder /// {some_value} /// /// // Load this too /// "{some_text}" /// } /// }; /// ``` /// /// IMPORTANT: This function assumes that root node is the top node on the stack fn load_placeholders( &self, mount: MountId, dynamic_nodes_iter: &mut Peekable<impl Iterator<Item = (usize, &'static [u8])>>, root_idx: u8, dom: &mut VirtualDom, mut to: Option<&mut impl WriteMutations>, ) { fn collect_dyn_node_range( dynamic_nodes: &mut Peekable<impl Iterator<Item = (usize, &'static [u8])>>, root_idx: u8, ) -> Option<(usize, usize)> { let start = match dynamic_nodes.peek() { Some((idx, [first, ..])) if *first == root_idx => *idx, _ => return None, }; let mut end = start; while let Some((idx, p)) = dynamic_nodes.next_if(|(_, p)| matches!(p, [idx, ..] if *idx == root_idx)) { if p.len() == 1 { continue; } end = idx; } Some((start, end)) } let (start, end) = match collect_dyn_node_range(dynamic_nodes_iter, root_idx) { Some((a, b)) => (a, b), None => return, }; // !!VERY IMPORTANT!! // // We need to walk the dynamic nodes in reverse order because we are going to replace the // placeholder with the new nodes, which will invalidate our paths into the template. // If we go in reverse, we leave a "wake of destruction" in our path, but our next iteration // will still be "clean" since we only invalidated downstream nodes. // // Forgetting to do this will cause weird bugs like: // https://github.com/DioxusLabs/dioxus/issues/2809 // // Which are quite serious. // There might be more places in this codebase where we need to do `.rev()` let reversed_iter = (start..=end).rev(); for dynamic_node_id in reversed_iter { let m = self.create_dynamic_node( &self.dynamic_nodes[dynamic_node_id], mount, dynamic_node_id, dom, to.as_deref_mut(), ); if let Some(to) = to.as_deref_mut() { // If we actually created real new nodes, we need to replace the placeholder for this dynamic node with the new dynamic nodes if m > 0 { // The path is one shorter because the top node is the root let path = &self.template.node_paths[dynamic_node_id][1..]; to.replace_placeholder_with_nodes(path, m); } } } } /// After we have written a root element, we need to write all the attributes that are on the root node /// /// ```rust, ignore /// rsx! { /// div { // We just wrote this node /// class: "{class}", // We need to set these attributes /// id: "{id}", /// style: "{style}", /// } /// } /// ``` /// /// IMPORTANT: This function assumes that root node is the top node on the stack fn write_attrs( &self, mount: MountId, dynamic_attributes_iter: &mut Peekable<impl Iterator<Item = (usize, &'static [u8])>>, root_idx: u8, dom: &mut VirtualDom, to: &mut impl WriteMutations, ) { let mut last_path = None; // Only take nodes that are under this root node let from_root_node = |(_, path): &(usize, &[u8])| path.first() == Some(&root_idx); while let Some((attribute_idx, attribute_path)) = dynamic_attributes_iter.next_if(from_root_node) { let attribute = &self.dynamic_attrs[attribute_idx]; let id = match last_path { // If the last path was exactly the same, we can reuse the id Some((path, id)) if path == attribute_path => id, // Otherwise, we need to create a new id _ => { let id = self.assign_static_node_as_dynamic(mount, attribute_path, dom, to);
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
true
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/diff/mod.rs
packages/core/src/diff/mod.rs
//! This module contains all the code for creating and diffing nodes. //! //! For suspense there are three different cases we need to handle: //! - Creating nodes/scopes without mounting them //! - Diffing nodes that are not mounted //! - Mounted nodes that have already been created //! //! To support those cases, we lazily create components and only optionally write to the real dom while diffing with Option<&mut impl WriteMutations> #![allow(clippy::too_many_arguments)] use crate::{ arena::MountId, innerlude::{ElementRef, WriteMutations}, nodes::VNode, virtual_dom::VirtualDom, ElementId, TemplateNode, }; mod component; mod iterator; mod node; impl VirtualDom { pub(crate) fn create_children( &mut self, mut to: Option<&mut impl WriteMutations>, nodes: &[VNode], parent: Option<ElementRef>, ) -> usize { nodes .iter() .map(|child| child.create(self, parent, to.as_deref_mut())) .sum() } pub(crate) fn get_mounted_parent(&self, mount: MountId) -> Option<ElementRef> { let mounts = self.runtime.mounts.borrow(); mounts[mount.0].parent } pub(crate) fn get_mounted_dyn_node(&self, mount: MountId, dyn_node_idx: usize) -> usize { let mounts = self.runtime.mounts.borrow(); mounts[mount.0].mounted_dynamic_nodes[dyn_node_idx] } pub(crate) fn set_mounted_dyn_node(&self, mount: MountId, dyn_node_idx: usize, value: usize) { let mut mounts = self.runtime.mounts.borrow_mut(); mounts[mount.0].mounted_dynamic_nodes[dyn_node_idx] = value; } pub(crate) fn get_mounted_dyn_attr(&self, mount: MountId, dyn_attr_idx: usize) -> ElementId { let mounts = self.runtime.mounts.borrow(); mounts[mount.0].mounted_attributes[dyn_attr_idx] } pub(crate) fn set_mounted_dyn_attr( &self, mount: MountId, dyn_attr_idx: usize, value: ElementId, ) { let mut mounts = self.runtime.mounts.borrow_mut(); mounts[mount.0].mounted_attributes[dyn_attr_idx] = value; } pub(crate) fn get_mounted_root_node(&self, mount: MountId, root_idx: usize) -> ElementId { let mounts = self.runtime.mounts.borrow(); mounts[mount.0].root_ids[root_idx] } pub(crate) fn set_mounted_root_node(&self, mount: MountId, root_idx: usize, value: ElementId) { let mut mounts = self.runtime.mounts.borrow_mut(); mounts[mount.0].root_ids[root_idx] = value; } /// Remove these nodes from the dom /// Wont generate mutations for the inner nodes fn remove_nodes( &mut self, mut to: Option<&mut impl WriteMutations>, nodes: &[VNode], replace_with: Option<usize>, ) { for (i, node) in nodes.iter().rev().enumerate() { let last_node = i == nodes.len() - 1; node.remove_node(self, to.as_deref_mut(), replace_with.filter(|_| last_node)); } } } /// We can apply various optimizations to dynamic nodes that are the single child of their parent. /// /// IE /// - for text - we can use SetTextContent /// - for clearing children we can use RemoveChildren /// - for appending children we can use AppendChildren #[allow(dead_code)] fn is_dyn_node_only_child(node: &VNode, idx: usize) -> bool { let template = node.template; let path = template.node_paths[idx]; // use a loop to index every static node's children until the path has run out // only break if the last path index is a dynamic node let mut static_node = &template.roots[path[0] as usize]; for i in 1..path.len() - 1 { match static_node { TemplateNode::Element { children, .. } => static_node = &children[path[i] as usize], _ => return false, } } match static_node { TemplateNode::Element { children, .. } => children.len() == 1, _ => false, } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/diff/iterator.rs
packages/core/src/diff/iterator.rs
use crate::{ innerlude::{ElementRef, WriteMutations}, nodes::VNode, DynamicNode, ScopeId, VirtualDom, }; use rustc_hash::{FxHashMap, FxHashSet}; impl VirtualDom { pub(crate) fn diff_non_empty_fragment( &mut self, to: Option<&mut impl WriteMutations>, old: &[VNode], new: &[VNode], parent: Option<ElementRef>, ) { let new_is_keyed = new[0].key.is_some(); let old_is_keyed = old[0].key.is_some(); debug_assert!( new.iter().all(|n| n.key.is_some() == new_is_keyed), "all siblings must be keyed or all siblings must be non-keyed" ); debug_assert!( old.iter().all(|o| o.key.is_some() == old_is_keyed), "all siblings must be keyed or all siblings must be non-keyed" ); if new_is_keyed && old_is_keyed { self.diff_keyed_children(to, old, new, parent); } else { self.diff_non_keyed_children(to, old, new, parent); } } // Diff children that are not keyed. // // The parent must be on the top of the change list stack when entering this // function: // // [... parent] // // the change list stack is in the same state when this function returns. fn diff_non_keyed_children( &mut self, mut to: Option<&mut impl WriteMutations>, old: &[VNode], new: &[VNode], parent: Option<ElementRef>, ) { use std::cmp::Ordering; // Handled these cases in `diff_children` before calling this function. debug_assert!(!new.is_empty()); debug_assert!(!old.is_empty()); match old.len().cmp(&new.len()) { Ordering::Greater => self.remove_nodes(to.as_deref_mut(), &old[new.len()..], None), Ordering::Less => self.create_and_insert_after( to.as_deref_mut(), &new[old.len()..], old.last().unwrap(), parent, ), Ordering::Equal => {} } for (new, old) in new.iter().zip(old.iter()) { old.diff_node(new, self, to.as_deref_mut()); } } // Diffing "keyed" children. // // With keyed children, we care about whether we delete, move, or create nodes // versus mutate existing nodes in place. Presumably there is some sort of CSS // transition animation that makes the virtual DOM diffing algorithm // observable. By specifying keys for nodes, we know which virtual DOM nodes // must reuse (or not reuse) the same physical DOM nodes. // // This is loosely based on Inferno's keyed patching implementation. However, we // have to modify the algorithm since we are compiling the diff down into change // list instructions that will be executed later, rather than applying the // changes to the DOM directly as we compare virtual DOMs. // // https://github.com/infernojs/inferno/blob/36fd96/packages/inferno/src/DOM/patching.ts#L530-L739 // // The stack is empty upon entry. fn diff_keyed_children( &mut self, mut to: Option<&mut impl WriteMutations>, old: &[VNode], new: &[VNode], parent: Option<ElementRef>, ) { if cfg!(debug_assertions) { let mut keys = rustc_hash::FxHashSet::default(); let mut assert_unique_keys = |children: &[VNode]| { keys.clear(); for child in children { let key = child.key.clone(); debug_assert!( key.is_some(), "if any sibling is keyed, all siblings must be keyed" ); keys.insert(key); } debug_assert_eq!( children.len(), keys.len(), "keyed siblings must each have a unique key" ); }; assert_unique_keys(old); assert_unique_keys(new); } // First up, we diff all the nodes with the same key at the beginning of the // children. // // `shared_prefix_count` is the count of how many nodes at the start of // `new` and `old` share the same keys. let (left_offset, right_offset) = match self.diff_keyed_ends(to.as_deref_mut(), old, new, parent) { Some(count) => count, None => return, }; // Ok, we now hopefully have a smaller range of children in the middle // within which to re-order nodes with the same keys, remove old nodes with // now-unused keys, and create new nodes with fresh keys. let old_middle = &old[left_offset..(old.len() - right_offset)]; let new_middle = &new[left_offset..(new.len() - right_offset)]; debug_assert!( !old_middle.is_empty(), "Old middle returned from `diff_keyed_ends` should not be empty" ); debug_assert!( !new_middle.is_empty(), "New middle returned from `diff_keyed_ends` should not be empty" ); // A few nodes in the middle were removed, just remove the old nodes if new_middle.is_empty() { self.remove_nodes(to, old_middle, None); } else { self.diff_keyed_middle(to, old_middle, new_middle, parent); } } /// Diff both ends of the children that share keys. /// /// Returns a left offset and right offset of that indicates a smaller section to pass onto the middle diffing. /// /// If there is no offset, then this function returns None and the diffing is complete. fn diff_keyed_ends( &mut self, mut to: Option<&mut impl WriteMutations>, old: &[VNode], new: &[VNode], parent: Option<ElementRef>, ) -> Option<(usize, usize)> { let mut left_offset = 0; for (old, new) in old.iter().zip(new.iter()) { // abort early if we finally run into nodes with different keys if old.key != new.key { break; } old.diff_node(new, self, to.as_deref_mut()); left_offset += 1; } // If that was all of the old children, then create and append the remaining // new children and we're finished. if left_offset == old.len() { self.create_and_insert_after(to, &new[left_offset..], &new[left_offset - 1], parent); return None; } // if the shared prefix is less than either length, then we need to walk backwards let mut right_offset = 0; for (old, new) in old.iter().rev().zip(new.iter().rev()) { // abort early if we finally run into nodes with different keys if old.key != new.key { break; } old.diff_node(new, self, to.as_deref_mut()); right_offset += 1; } // If that was all of the old children, then create and prepend the remaining // new children and we're finished. if right_offset == old.len() { self.create_and_insert_before( to, &new[..new.len() - right_offset], &new[new.len() - right_offset], parent, ); return None; } // If the right offset + the left offset is the same as the new length, then we just need to remove the old nodes if right_offset + left_offset == new.len() { self.remove_nodes(to, &old[left_offset..old.len() - right_offset], None); return None; } // If the right offset + the left offset is the same as the old length, then we just need to add the new nodes if right_offset + left_offset == old.len() { self.create_and_insert_before( to, &new[left_offset..new.len() - right_offset], &new[new.len() - right_offset], parent, ); return None; } Some((left_offset, right_offset)) } // The most-general, expensive code path for keyed children diffing. // // We find the longest subsequence within `old` of children that are relatively // ordered the same way in `new` (via finding a longest-increasing-subsequence // of the old child's index within `new`). The children that are elements of // this subsequence will remain in place, minimizing the number of DOM moves we // will have to do. // // Upon entry to this function, the change list stack must be empty. // // This function will load the appropriate nodes onto the stack and do diffing in place. // // Upon exit from this function, it will be restored to that same self. #[allow(clippy::too_many_lines)] fn diff_keyed_middle( &mut self, mut to: Option<&mut impl WriteMutations>, old: &[VNode], new: &[VNode], parent: Option<ElementRef>, ) { /* 1. Map the old keys into a numerical ordering based on indices. 2. Create a map of old key to its index 3. Map each new key to the old key, carrying over the old index. - IE if we have ABCD becomes BACD, our sequence would be 1,0,2,3 - if we have ABCD to ABDE, our sequence would be 0,1,3,MAX because E doesn't exist now, we should have a list of integers that indicates where in the old list the new items map to. 4. Compute the LIS of this list - this indicates the longest list of new children that won't need to be moved. 5. Identify which nodes need to be removed 6. Identify which nodes will need to be diffed 7. Going along each item in the new list, create it and insert it before the next closest item in the LIS. - if the item already existed, just move it to the right place. 8. Finally, generate instructions to remove any old children. 9. Generate instructions to finally diff children that are the same between both */ // 0. Debug sanity checks // Should have already diffed the shared-key prefixes and suffixes. debug_assert_ne!(new.first().map(|i| &i.key), old.first().map(|i| &i.key)); debug_assert_ne!(new.last().map(|i| &i.key), old.last().map(|i| &i.key)); // 1. Map the old keys into a numerical ordering based on indices. // 2. Create a map of old key to its index // IE if the keys were A B C, then we would have (A, 0) (B, 1) (C, 2). let old_key_to_old_index = old .iter() .enumerate() .map(|(i, o)| (o.key.as_ref().unwrap().as_str(), i)) .collect::<FxHashMap<_, _>>(); let mut shared_keys = FxHashSet::default(); // 3. Map each new key to the old key, carrying over the old index. let new_index_to_old_index = new .iter() .map(|node| { let key = node.key.as_ref().unwrap(); if let Some(&index) = old_key_to_old_index.get(key.as_str()) { shared_keys.insert(key); index } else { usize::MAX } }) .collect::<Box<[_]>>(); // If none of the old keys are reused by the new children, then we remove all the remaining old children and // create the new children afresh. if shared_keys.is_empty() { debug_assert!( !old.is_empty(), "we should never be appending - just creating N" ); let m = self.create_children(to.as_deref_mut(), new, parent); self.remove_nodes(to, old, Some(m)); return; } // remove any old children that are not shared for child_to_remove in old .iter() .filter(|child| !shared_keys.contains(child.key.as_ref().unwrap())) { child_to_remove.remove_node(self, to.as_deref_mut(), None); } // 4. Compute the LIS of this list let mut lis_sequence = Vec::with_capacity(new_index_to_old_index.len()); let mut allocation = vec![0; new_index_to_old_index.len() * 2]; let (predecessors, starts) = allocation.split_at_mut(new_index_to_old_index.len()); longest_increasing_subsequence::lis_with( &new_index_to_old_index, &mut lis_sequence, |a, b| a < b, predecessors, starts, ); // if a new node gets u32 max and is at the end, then it might be part of our LIS (because u32 max is a valid LIS) if lis_sequence.first().map(|f| new_index_to_old_index[*f]) == Some(usize::MAX) { lis_sequence.remove(0); } // Diff each nod in the LIS for idx in &lis_sequence { old[new_index_to_old_index[*idx]].diff_node(&new[*idx], self, to.as_deref_mut()); } /// Create or diff each node in a range depending on whether it is in the LIS or not /// Returns the number of nodes created on the stack fn create_or_diff( vdom: &mut VirtualDom, new: &[VNode], old: &[VNode], mut to: Option<&mut impl WriteMutations>, parent: Option<ElementRef>, new_index_to_old_index: &[usize], range: std::ops::Range<usize>, ) -> usize { let range_start = range.start; new[range] .iter() .enumerate() .map(|(idx, new_node)| { let new_idx = range_start + idx; let old_index = new_index_to_old_index[new_idx]; // If the node existed in the old list, diff it if let Some(old_node) = old.get(old_index) { old_node.diff_node(new_node, vdom, to.as_deref_mut()); if let Some(to) = to.as_deref_mut() { new_node.push_all_root_nodes(vdom, to) } else { 0 } } else { // Otherwise, just add it to the stack new_node.create(vdom, parent, to.as_deref_mut()) } }) .sum() } // add mount instruction for the items before the LIS let last = *lis_sequence.first().unwrap(); if last < (new.len() - 1) { let nodes_created = create_or_diff( self, new, old, to.as_deref_mut(), parent, &new_index_to_old_index, (last + 1)..new.len(), ); // Insert all the nodes that we just created after the last node in the LIS self.insert_after(to.as_deref_mut(), nodes_created, &new[last]); } // For each node inside of the LIS, but not included in the LIS, generate a mount instruction // We loop over the LIS in reverse order and insert any nodes we find in the gaps between indexes let mut lis_iter = lis_sequence.iter(); let mut last = *lis_iter.next().unwrap(); for next in lis_iter { if last - next > 1 { let nodes_created = create_or_diff( self, new, old, to.as_deref_mut(), parent, &new_index_to_old_index, (next + 1)..last, ); self.insert_before(to.as_deref_mut(), nodes_created, &new[last]); } last = *next; } // add mount instruction for the items after the LIS let first_lis = *lis_sequence.last().unwrap(); if first_lis > 0 { let nodes_created = create_or_diff( self, new, old, to.as_deref_mut(), parent, &new_index_to_old_index, 0..first_lis, ); self.insert_before(to, nodes_created, &new[first_lis]); } } fn create_and_insert_before( &mut self, mut to: Option<&mut impl WriteMutations>, new: &[VNode], before: &VNode, parent: Option<ElementRef>, ) { let m = self.create_children(to.as_deref_mut(), new, parent); self.insert_before(to, m, before); } fn insert_before(&mut self, to: Option<&mut impl WriteMutations>, new: usize, before: &VNode) { if let Some(to) = to { if new > 0 { let id = before.find_first_element(self); to.insert_nodes_before(id, new); } } } fn create_and_insert_after( &mut self, mut to: Option<&mut impl WriteMutations>, new: &[VNode], after: &VNode, parent: Option<ElementRef>, ) { let m = self.create_children(to.as_deref_mut(), new, parent); self.insert_after(to, m, after); } fn insert_after(&mut self, to: Option<&mut impl WriteMutations>, new: usize, after: &VNode) { if let Some(to) = to { if new > 0 { let id = after.find_last_element(self); to.insert_nodes_after(id, new); } } } } impl VNode { /// Push all the root nodes on the stack pub(crate) fn push_all_root_nodes( &self, dom: &VirtualDom, to: &mut impl WriteMutations, ) -> usize { let template = self.template; let mounts = dom.runtime.mounts.borrow(); let mount = mounts.get(self.mount.get().0).unwrap(); template .roots .iter() .enumerate() .map( |(root_idx, _)| match self.get_dynamic_root_node_and_id(root_idx) { Some((_, DynamicNode::Fragment(nodes))) => { let mut accumulated = 0; for node in nodes { accumulated += node.push_all_root_nodes(dom, to); } accumulated } Some((idx, DynamicNode::Component(_))) => { let scope = ScopeId(mount.mounted_dynamic_nodes[idx]); let node = dom.get_scope(scope).unwrap().root_node(); node.push_all_root_nodes(dom, to) } // This is a static root node or a single dynamic node, just push it None | Some((_, DynamicNode::Placeholder(_) | DynamicNode::Text(_))) => { to.push_root(mount.root_ids[root_idx]); 1 } }, ) .sum() } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/diff/component.rs
packages/core/src/diff/component.rs
use std::{ any::TypeId, ops::{Deref, DerefMut}, }; use crate::{ any_props::AnyProps, innerlude::{ ElementRef, MountId, ScopeOrder, SuspenseBoundaryProps, SuspenseBoundaryPropsWithOwner, VComponent, WriteMutations, }, nodes::VNode, scopes::{LastRenderedNode, ScopeId}, virtual_dom::VirtualDom, Element, SuspenseContext, }; impl VirtualDom { pub(crate) fn run_and_diff_scope<M: WriteMutations>( &mut self, to: Option<&mut M>, scope_id: ScopeId, ) { let scope = &mut self.scopes[scope_id.0]; if SuspenseBoundaryProps::downcast_from_props(&mut *scope.props).is_some() { SuspenseBoundaryProps::diff(scope_id, self, to) } else { let new_nodes = self.run_scope(scope_id); self.diff_scope(to, scope_id, new_nodes); } } #[tracing::instrument(skip(self, to), level = "trace", name = "VirtualDom::diff_scope")] fn diff_scope<M: WriteMutations>( &mut self, to: Option<&mut M>, scope: ScopeId, new_nodes: Element, ) { self.runtime.clone().with_scope_on_stack(scope, || { // We don't diff the nodes if the scope is suspended or has an error let Ok(new_real_nodes) = &new_nodes else { return; }; let scope_state = &mut self.scopes[scope.0]; // Load the old and new rendered nodes let old = scope_state.last_rendered_node.take().unwrap(); // If there are suspended scopes, we need to check if the scope is suspended before we diff it // If it is suspended, we need to diff it but write the mutations nothing // Note: It is important that we still diff the scope even if it is suspended, because the scope may render other child components which may change between renders let mut render_to = to.filter(|_| self.runtime.scope_should_render(scope)); old.diff_node(new_real_nodes, self, render_to.as_deref_mut()); self.scopes[scope.0].last_rendered_node = Some(LastRenderedNode::new(new_nodes)); if render_to.is_some() { self.runtime.get_state(scope).mount(&self.runtime); } }) } /// Create a new [`Scope`](crate::scope_context::Scope) for a component. /// /// Returns the number of nodes created on the stack #[tracing::instrument(skip(self, to), level = "trace", name = "VirtualDom::create_scope")] pub(crate) fn create_scope<M: WriteMutations>( &mut self, to: Option<&mut M>, scope: ScopeId, new_nodes: LastRenderedNode, parent: Option<ElementRef>, ) -> usize { self.runtime.clone().with_scope_on_stack(scope, || { // If there are suspended scopes, we need to check if the scope is suspended before we diff it // If it is suspended, we need to diff it but write the mutations nothing // Note: It is important that we still diff the scope even if it is suspended, because the scope may render other child components which may change between renders let mut render_to = to.filter(|_| self.runtime.scope_should_render(scope)); // Create the node let nodes = new_nodes.create(self, parent, render_to.as_deref_mut()); // Then set the new node as the last rendered node self.scopes[scope.0].last_rendered_node = Some(new_nodes); if render_to.is_some() { self.runtime.get_state(scope).mount(&self.runtime); } nodes }) } pub(crate) fn remove_component_node<M: WriteMutations>( &mut self, to: Option<&mut M>, destroy_component_state: bool, scope_id: ScopeId, replace_with: Option<usize>, ) { // If this is a suspense boundary, remove the suspended nodes as well SuspenseContext::remove_suspended_nodes::<M>(self, scope_id, destroy_component_state); // Remove the component from the dom if let Some(node) = self.scopes[scope_id.0].last_rendered_node.clone() { node.remove_node_inner(self, to, destroy_component_state, replace_with) }; if destroy_component_state { // Now drop all the resources self.drop_scope(scope_id); } } } impl VNode { pub(crate) fn diff_vcomponent( &self, mount: MountId, idx: usize, new: &VComponent, old: &VComponent, scope_id: ScopeId, parent: Option<ElementRef>, dom: &mut VirtualDom, to: Option<&mut impl WriteMutations>, ) { // Replace components that have different render fns if old.render_fn != new.render_fn { return self.replace_vcomponent(mount, idx, new, parent, dom, to); } // copy out the box for both let old_scope = &mut dom.scopes[scope_id.0]; let old_props: &mut dyn AnyProps = old_scope.props.deref_mut(); let new_props: &dyn AnyProps = new.props.deref(); // If the props are static, then we try to memoize by setting the new with the old // The target ScopeState still has the reference to the old props, so there's no need to update anything // This also implicitly drops the new props since they're not used if old_props.memoize(new_props.props()) { tracing::trace!("Memoized props for component {:#?}", scope_id,); return; } // Now diff the scope dom.run_and_diff_scope(to, scope_id); let height = dom.runtime.get_state(scope_id).height; dom.dirty_scopes.remove(&ScopeOrder::new(height, scope_id)); } fn replace_vcomponent( &self, mount: MountId, idx: usize, new: &VComponent, parent: Option<ElementRef>, dom: &mut VirtualDom, mut to: Option<&mut impl WriteMutations>, ) { let scope = ScopeId(dom.get_mounted_dyn_node(mount, idx)); // Remove the scope id from the mount dom.set_mounted_dyn_node(mount, idx, ScopeId::PLACEHOLDER.0); let m = self.create_component_node(mount, idx, new, parent, dom, to.as_deref_mut()); // Instead of *just* removing it, we can use the replace mutation dom.remove_component_node(to, true, scope, Some(m)); } /// Create a new component (if it doesn't already exist) node and then mount the [`crate::ScopeState`] for a component /// /// Returns the number of nodes created on the stack pub(super) fn create_component_node( &self, mount: MountId, idx: usize, component: &VComponent, parent: Option<ElementRef>, dom: &mut VirtualDom, to: Option<&mut impl WriteMutations>, ) -> usize { // If this is a suspense boundary, run our suspense creation logic instead of running the component if component.props.props().type_id() == TypeId::of::<SuspenseBoundaryPropsWithOwner>() { return SuspenseBoundaryProps::create(mount, idx, component, parent, dom, to); } let mut scope_id = ScopeId(dom.get_mounted_dyn_node(mount, idx)); // If the scopeid is a placeholder, we need to load up a new scope for this vcomponent. If it's already mounted, then we can just use that if scope_id.is_placeholder() { scope_id = dom .new_scope(component.props.duplicate(), component.name) .state() .id; // Store the scope id for the next render dom.set_mounted_dyn_node(mount, idx, scope_id.0); // If this is a new scope, we also need to run it once to get the initial state let new = dom.run_scope(scope_id); // Then set the new node as the last rendered node dom.scopes[scope_id.0].last_rendered_node = Some(LastRenderedNode::new(new)); } let scope = ScopeId(dom.get_mounted_dyn_node(mount, idx)); let new_node = dom.scopes[scope.0] .last_rendered_node .clone() .expect("Component to be mounted"); dom.create_scope(to, scope, new_node, parent) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/suspense/mod.rs
packages/core/src/suspense/mod.rs
//! Suspense allows you to render a placeholder while nodes are waiting for data in the background //! //! During suspense on the server: //! - Rebuild once //! - Send page with loading placeholders down to the client //! - loop //! - Poll (only) suspended futures //! - If a scope is marked as dirty and that scope is a suspense boundary, under a suspended boundary, or the suspense placeholder, rerun the scope //! - If it is a different scope, ignore it and warn the user //! - Rerender the scope on the server and send down the nodes under a hidden div with serialized data //! //! During suspense on the web: //! - Rebuild once without running server futures //! - Rehydrate the placeholders that were initially sent down. At this point, no suspense nodes are resolved so the client and server pages should be the same //! - loop //! - Wait for work or suspense data //! - If suspense data comes in //! - replace the suspense placeholder //! - get any data associated with the suspense placeholder and rebuild nodes under the suspense that was resolved //! - rehydrate the suspense placeholders that were at that node //! - If work comes in //! - Just do the work; this may remove suspense placeholders that the server hasn't yet resolved. If we see new data come in from the server about that node, ignore it //! //! Generally suspense placeholders should not be stateful because they are driven from the server. If they are stateful and the client renders something different, hydration will fail. mod component; pub use component::*; use crate::innerlude::*; use std::{ cell::{Cell, Ref, RefCell}, fmt::Debug, rc::Rc, }; /// A task that has been suspended which may have an optional loading placeholder #[derive(Clone, PartialEq, Debug)] pub struct SuspendedFuture { origin: ScopeId, task: TaskId, } impl SuspendedFuture { /// Create a new suspended future pub fn new(task: Task) -> Self { Self { task: task.id, origin: current_scope_id(), } } /// Get the task that was suspended pub fn task(&self) -> Task { Task::from_id(self.task) } /// Create a deep clone of this suspended future pub(crate) fn deep_clone(&self) -> Self { Self { task: self.task, origin: self.origin, } } } impl std::fmt::Display for SuspendedFuture { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "SuspendedFuture {{ task: {:?} }}", self.task) } } /// A context with information about suspended components #[derive(Debug, Clone)] pub struct SuspenseContext { inner: Rc<SuspenseBoundaryInner>, } impl PartialEq for SuspenseContext { fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.inner, &other.inner) } } impl SuspenseContext { /// Create a new suspense boundary in a specific scope pub(crate) fn new() -> Self { Self { inner: Rc::new(SuspenseBoundaryInner { rt: Runtime::current(), suspended_tasks: RefCell::new(vec![]), id: Cell::new(ScopeId::ROOT), suspended_nodes: Default::default(), frozen: Default::default(), after_suspense_resolved: Default::default(), }), } } /// Mount the context in a specific scope pub(crate) fn mount(&self, scope: ScopeId) { self.inner.id.set(scope); } /// Get the suspense boundary's suspended nodes pub fn suspended_nodes(&self) -> Option<VNode> { self.inner .suspended_nodes .borrow() .as_ref() .map(|node| node.clone()) } /// Set the suspense boundary's suspended nodes pub(crate) fn set_suspended_nodes(&self, suspended_nodes: VNode) { self.inner .suspended_nodes .borrow_mut() .replace(suspended_nodes); } /// Take the suspense boundary's suspended nodes pub(crate) fn take_suspended_nodes(&self) -> Option<VNode> { self.inner.suspended_nodes.borrow_mut().take() } /// Check if the suspense boundary is resolved and frozen pub fn frozen(&self) -> bool { self.inner.frozen.get() } /// Resolve the suspense boundary on the server and freeze it to prevent future reruns of any child nodes of the suspense boundary pub fn freeze(&self) { self.inner.frozen.set(true); } /// Check if there are any suspended tasks pub fn has_suspended_tasks(&self) -> bool { !self.inner.suspended_tasks.borrow().is_empty() } /// Check if the suspense boundary is currently rendered as suspended pub fn is_suspended(&self) -> bool { self.inner.suspended_nodes.borrow().is_some() } /// Add a suspended task pub(crate) fn add_suspended_task(&self, task: SuspendedFuture) { self.inner.suspended_tasks.borrow_mut().push(task); self.inner.rt.needs_update(self.inner.id.get()); } /// Remove a suspended task pub(crate) fn remove_suspended_task(&self, task: Task) { self.inner .suspended_tasks .borrow_mut() .retain(|t| t.task != task.id); self.inner.rt.needs_update(self.inner.id.get()); } /// Get all suspended tasks pub fn suspended_futures(&self) -> Ref<'_, [SuspendedFuture]> { Ref::map(self.inner.suspended_tasks.borrow(), |tasks| { tasks.as_slice() }) } /// Run a closure after suspense is resolved pub fn after_suspense_resolved(&self, callback: impl FnOnce() + 'static) { let mut closures = self.inner.after_suspense_resolved.borrow_mut(); closures.push(Box::new(callback)); } /// Run all closures that were queued to run after suspense is resolved pub(crate) fn run_resolved_closures(&self, runtime: &Runtime) { runtime.while_not_rendering(|| { self.inner .after_suspense_resolved .borrow_mut() .drain(..) .for_each(|f| f()); }) } } /// A boundary that will capture any errors from child components pub struct SuspenseBoundaryInner { rt: Rc<Runtime>, suspended_tasks: RefCell<Vec<SuspendedFuture>>, id: Cell<ScopeId>, /// The nodes that are suspended under this boundary suspended_nodes: RefCell<Option<VNode>>, /// On the server, you can only resolve a suspense boundary once. This is used to track if the suspense boundary has been resolved and if it should be frozen frozen: Cell<bool>, /// Closures queued to run after the suspense boundary is resolved after_suspense_resolved: RefCell<Vec<Box<dyn FnOnce()>>>, } impl Debug for SuspenseBoundaryInner { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SuspenseBoundaryInner") .field("suspended_tasks", &self.suspended_tasks) .field("id", &self.id) .field("suspended_nodes", &self.suspended_nodes) .field("frozen", &self.frozen) .finish() } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/src/suspense/component.rs
packages/core/src/suspense/component.rs
use crate::{innerlude::*, scope_context::SuspenseLocation}; /// Properties for the [`SuspenseBoundary()`] component. #[allow(non_camel_case_types)] pub struct SuspenseBoundaryProps { fallback: Callback<SuspenseContext, Element>, /// The children of the suspense boundary children: LastRenderedNode, } impl Clone for SuspenseBoundaryProps { fn clone(&self) -> Self { Self { fallback: self.fallback, children: self.children.clone(), } } } impl SuspenseBoundaryProps { /** Create a builder for building `SuspenseBoundaryProps`. On the builder, call `.fallback(...)`, `.children(...)`(optional) to set the values of the fields. Finally, call `.build()` to create the instance of `SuspenseBoundaryProps`. */ #[allow(dead_code, clippy::type_complexity)] fn builder() -> SuspenseBoundaryPropsBuilder<((), ())> { SuspenseBoundaryPropsBuilder { owner: Owner::default(), fields: ((), ()), _phantom: ::core::default::Default::default(), } } } #[must_use] #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub struct SuspenseBoundaryPropsBuilder<TypedBuilderFields> { owner: Owner, fields: TypedBuilderFields, _phantom: (), } impl Properties for SuspenseBoundaryProps where Self: Clone, { type Builder = SuspenseBoundaryPropsBuilder<((), ())>; fn builder() -> Self::Builder { SuspenseBoundaryProps::builder() } fn memoize(&mut self, new: &Self) -> bool { let equal = self == new; self.fallback.__point_to(&new.fallback); if !equal { let new_clone = new.clone(); self.children = new_clone.children; } equal } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub trait SuspenseBoundaryPropsBuilder_Optional<T> { fn into_value<F: FnOnce() -> T>(self, default: F) -> T; } impl<T> SuspenseBoundaryPropsBuilder_Optional<T> for () { fn into_value<F: FnOnce() -> T>(self, default: F) -> T { default() } } impl<T> SuspenseBoundaryPropsBuilder_Optional<T> for (T,) { fn into_value<F: FnOnce() -> T>(self, _: F) -> T { self.0 } } #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__children> SuspenseBoundaryPropsBuilder<((), __children)> { #[allow(clippy::type_complexity)] pub fn fallback<__Marker>( self, fallback: impl SuperInto<Callback<SuspenseContext, Element>, __Marker>, ) -> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> { let fallback = (with_owner(self.owner.clone(), move || { SuperInto::super_into(fallback) }),); let (_, children) = self.fields; SuspenseBoundaryPropsBuilder { owner: self.owner, fields: (fallback, children), _phantom: self._phantom, } } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub enum SuspenseBoundaryPropsBuilder_Error_Repeated_field_fallback {} #[doc(hidden)] #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__children> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> { #[deprecated(note = "Repeated field fallback")] #[allow(clippy::type_complexity)] pub fn fallback( self, _: SuspenseBoundaryPropsBuilder_Error_Repeated_field_fallback, ) -> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> { self } } #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__fallback> SuspenseBoundaryPropsBuilder<(__fallback, ())> { #[allow(clippy::type_complexity)] pub fn children( self, children: Element, ) -> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> { let children = (children,); let (fallback, _) = self.fields; SuspenseBoundaryPropsBuilder { owner: self.owner, fields: (fallback, children), _phantom: self._phantom, } } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub enum SuspenseBoundaryPropsBuilder_Error_Repeated_field_children {} #[doc(hidden)] #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__fallback> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> { #[deprecated(note = "Repeated field children")] #[allow(clippy::type_complexity)] pub fn children( self, _: SuspenseBoundaryPropsBuilder_Error_Repeated_field_children, ) -> SuspenseBoundaryPropsBuilder<(__fallback, (Element,))> { self } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, non_snake_case)] pub enum SuspenseBoundaryPropsBuilder_Error_Missing_required_field_fallback {} #[doc(hidden)] #[allow(dead_code, non_camel_case_types, missing_docs, clippy::panic)] impl<__children> SuspenseBoundaryPropsBuilder<((), __children)> { #[deprecated(note = "Missing required field fallback")] pub fn build( self, _: SuspenseBoundaryPropsBuilder_Error_Missing_required_field_fallback, ) -> SuspenseBoundaryProps { panic!() } } #[doc(hidden)] #[allow(dead_code, non_camel_case_types, missing_docs)] pub struct SuspenseBoundaryPropsWithOwner { inner: SuspenseBoundaryProps, owner: Owner, } #[automatically_derived] #[allow(dead_code, non_camel_case_types, missing_docs)] impl ::core::clone::Clone for SuspenseBoundaryPropsWithOwner { #[inline] fn clone(&self) -> SuspenseBoundaryPropsWithOwner { SuspenseBoundaryPropsWithOwner { inner: ::core::clone::Clone::clone(&self.inner), owner: ::core::clone::Clone::clone(&self.owner), } } } impl PartialEq for SuspenseBoundaryPropsWithOwner { fn eq(&self, other: &Self) -> bool { self.inner.eq(&other.inner) } } impl SuspenseBoundaryPropsWithOwner { /// Create a component from the props. pub fn into_vcomponent<M: 'static>( self, render_fn: impl ComponentFunction<SuspenseBoundaryProps, M>, ) -> VComponent { let component_name = std::any::type_name_of_val(&render_fn); VComponent::new( move |wrapper: Self| render_fn.rebuild(wrapper.inner), self, component_name, ) } } impl Properties for SuspenseBoundaryPropsWithOwner { type Builder = (); fn builder() -> Self::Builder { unreachable!() } fn memoize(&mut self, new: &Self) -> bool { self.inner.memoize(&new.inner) } } #[allow(dead_code, non_camel_case_types, missing_docs)] impl<__children: SuspenseBoundaryPropsBuilder_Optional<Element>> SuspenseBoundaryPropsBuilder<((Callback<SuspenseContext, Element>,), __children)> { pub fn build(self) -> SuspenseBoundaryPropsWithOwner { let (fallback, children) = self.fields; let fallback = fallback.0; let children = SuspenseBoundaryPropsBuilder_Optional::into_value(children, VNode::empty); SuspenseBoundaryPropsWithOwner { inner: SuspenseBoundaryProps { fallback, children: LastRenderedNode::new(children), }, owner: self.owner, } } } #[automatically_derived] #[allow(non_camel_case_types)] impl ::core::cmp::PartialEq for SuspenseBoundaryProps { #[inline] fn eq(&self, other: &SuspenseBoundaryProps) -> bool { self.fallback == other.fallback && self.children == other.children } } /// Suspense Boundaries let you render a fallback UI while a child component is suspended. /// /// # Example /// /// ```rust /// # use dioxus::prelude::*; /// # fn Article() -> Element { rsx! { "Article" } } /// fn App() -> Element { /// rsx! { /// SuspenseBoundary { /// fallback: |_| rsx! { "Loading..." }, /// Article {} /// } /// } /// } /// ``` #[allow(non_snake_case)] pub fn SuspenseBoundary(mut __props: SuspenseBoundaryProps) -> Element { unreachable!("SuspenseBoundary should not be called directly") } #[allow(non_snake_case)] #[doc(hidden)] mod SuspenseBoundary_completions { #[doc(hidden)] #[allow(non_camel_case_types)] /// This enum is generated to help autocomplete the braces after the component. It does nothing pub enum Component { SuspenseBoundary {}, } } use generational_box::Owner; #[allow(unused)] pub use SuspenseBoundary_completions::Component::SuspenseBoundary; /// Suspense has a custom diffing algorithm that diffs the suspended nodes in the background without rendering them impl SuspenseBoundaryProps { /// Try to downcast [`AnyProps`] to [`SuspenseBoundaryProps`] pub(crate) fn downcast_from_props(props: &mut dyn AnyProps) -> Option<&mut Self> { let inner: Option<&mut SuspenseBoundaryPropsWithOwner> = props.props_mut().downcast_mut(); inner.map(|inner| &mut inner.inner) } pub(crate) fn create<M: WriteMutations>( mount: MountId, idx: usize, component: &VComponent, parent: Option<ElementRef>, dom: &mut VirtualDom, to: Option<&mut M>, ) -> usize { let mut scope_id = ScopeId(dom.get_mounted_dyn_node(mount, idx)); // If the ScopeId is a placeholder, we need to load up a new scope for this vcomponent. If it's already mounted, then we can just use that if scope_id.is_placeholder() { { let suspense_context = SuspenseContext::new(); let suspense_boundary_location = crate::scope_context::SuspenseLocation::SuspenseBoundary( suspense_context.clone(), ); dom.runtime .clone() .with_suspense_location(suspense_boundary_location, || { let scope_state = dom .new_scope(component.props.duplicate(), component.name) .state(); suspense_context.mount(scope_state.id); scope_id = scope_state.id; }); } // Store the scope id for the next render dom.set_mounted_dyn_node(mount, idx, scope_id.0); } dom.runtime.clone().with_scope_on_stack(scope_id, || { let scope_state = &mut dom.scopes[scope_id.0]; let props = Self::downcast_from_props(&mut *scope_state.props).unwrap(); let suspense_context = SuspenseContext::downcast_suspense_boundary_from_scope(&dom.runtime, scope_id) .unwrap(); let children = props.children.clone(); // First always render the children in the background. Rendering the children may cause this boundary to suspend suspense_context.under_suspense_boundary(&dom.runtime(), || { children.create(dom, parent, None::<&mut M>); }); // Store the (now mounted) children back into the scope state let scope_state = &mut dom.scopes[scope_id.0]; let props = Self::downcast_from_props(&mut *scope_state.props).unwrap(); props.children.clone_from(&children); let scope_state = &mut dom.scopes[scope_id.0]; let suspense_context = scope_state .state() .suspense_location() .suspense_context() .unwrap() .clone(); // If there are suspended futures, render the fallback let nodes_created = if !suspense_context.suspended_futures().is_empty() { let (node, nodes_created) = suspense_context.in_suspense_placeholder(&dom.runtime(), || { let scope_state = &mut dom.scopes[scope_id.0]; let props = Self::downcast_from_props(&mut *scope_state.props).unwrap(); let suspense_context = SuspenseContext::downcast_suspense_boundary_from_scope( &dom.runtime, scope_id, ) .unwrap(); suspense_context.set_suspended_nodes(children.as_vnode().clone()); let suspense_placeholder = LastRenderedNode::new(props.fallback.call(suspense_context)); let nodes_created = suspense_placeholder.create(dom, parent, to); (suspense_placeholder, nodes_created) }); let scope_state = &mut dom.scopes[scope_id.0]; scope_state.last_rendered_node = Some(node); nodes_created } else { // Otherwise just render the children in the real dom debug_assert!(children.mount.get().mounted()); let nodes_created = suspense_context .under_suspense_boundary(&dom.runtime(), || children.create(dom, parent, to)); let scope_state = &mut dom.scopes[scope_id.0]; scope_state.last_rendered_node = children.into(); let suspense_context = SuspenseContext::downcast_suspense_boundary_from_scope(&dom.runtime, scope_id) .unwrap(); suspense_context.take_suspended_nodes(); mark_suspense_resolved(&suspense_context, dom, scope_id); nodes_created }; nodes_created }) } #[doc(hidden)] /// Manually rerun the children of this suspense boundary without diffing against the old nodes. /// /// This should only be called by dioxus-web after the suspense boundary has been streamed in from the server. pub fn resolve_suspense<M: WriteMutations>( scope_id: ScopeId, dom: &mut VirtualDom, to: &mut M, only_write_templates: impl FnOnce(&mut M), replace_with: usize, ) { dom.runtime.clone().with_scope_on_stack(scope_id, || { let _runtime = RuntimeGuard::new(dom.runtime()); let Some(scope_state) = dom.scopes.get_mut(scope_id.0) else { return; }; // Reset the suspense context let suspense_context = scope_state .state() .suspense_location() .suspense_context() .unwrap() .clone(); suspense_context.inner.suspended_tasks.borrow_mut().clear(); // Get the parent of the suspense boundary to later create children with the right parent let currently_rendered = scope_state.last_rendered_node.clone().unwrap(); let mount = currently_rendered.mount.get(); let parent = { let mounts = dom.runtime.mounts.borrow(); mounts .get(mount.0) .expect("suspense placeholder is not mounted") .parent }; let props = Self::downcast_from_props(&mut *scope_state.props).unwrap(); // Unmount any children to reset any scopes under this suspense boundary let children = props.children.clone(); let suspense_context = SuspenseContext::downcast_suspense_boundary_from_scope(&dom.runtime, scope_id) .unwrap(); // Take the suspended nodes out of the suspense boundary so the children know that the boundary is not suspended while diffing let suspended = suspense_context.take_suspended_nodes(); if let Some(node) = suspended { node.remove_node(&mut *dom, None::<&mut M>, None); } // Replace the rendered nodes with resolved nodes currently_rendered.remove_node(&mut *dom, Some(to), Some(replace_with)); // Switch to only writing templates only_write_templates(to); children.mount.take(); // First always render the children in the background. Rendering the children may cause this boundary to suspend suspense_context.under_suspense_boundary(&dom.runtime(), || { children.create(dom, parent, Some(to)); }); // Store the (now mounted) children back into the scope state let scope_state = &mut dom.scopes[scope_id.0]; let props = Self::downcast_from_props(&mut *scope_state.props).unwrap(); props.children.clone_from(&children); scope_state.last_rendered_node = Some(children); // Run any closures that were waiting for the suspense to resolve suspense_context.run_resolved_closures(&dom.runtime); }) } pub(crate) fn diff<M: WriteMutations>( scope_id: ScopeId, dom: &mut VirtualDom, to: Option<&mut M>, ) { dom.runtime.clone().with_scope_on_stack(scope_id, || { let scope = &mut dom.scopes[scope_id.0]; let myself = Self::downcast_from_props(&mut *scope.props) .unwrap() .clone(); let last_rendered_node = scope.last_rendered_node.clone().unwrap(); let Self { fallback, children, .. } = myself; let suspense_context = scope.state().suspense_boundary().unwrap().clone(); let suspended_nodes = suspense_context.suspended_nodes(); let suspended = !suspense_context.suspended_futures().is_empty(); match (suspended_nodes, suspended) { // We already have suspended nodes that still need to be suspended // Just diff the normal and suspended nodes (Some(suspended_nodes), true) => { let new_suspended_nodes: VNode = children.as_vnode().clone(); // Diff the placeholder nodes in the dom let new_placeholder = suspense_context.in_suspense_placeholder(&dom.runtime(), || { let old_placeholder = last_rendered_node; let new_placeholder = LastRenderedNode::new(fallback.call(suspense_context.clone())); old_placeholder.diff_node(&new_placeholder, dom, to); new_placeholder }); // Set the last rendered node to the placeholder dom.scopes[scope_id.0].last_rendered_node = Some(new_placeholder); // Diff the suspended nodes in the background suspense_context.under_suspense_boundary(&dom.runtime(), || { suspended_nodes.diff_node(&new_suspended_nodes, dom, None::<&mut M>); }); let suspense_context = SuspenseContext::downcast_suspense_boundary_from_scope( &dom.runtime, scope_id, ) .unwrap(); suspense_context.set_suspended_nodes(new_suspended_nodes); } // We have no suspended nodes, and we are not suspended. Just diff the children like normal (None, false) => { let old_children = last_rendered_node; let new_children = children; suspense_context.under_suspense_boundary(&dom.runtime(), || { old_children.diff_node(&new_children, dom, to); }); // Set the last rendered node to the new children dom.scopes[scope_id.0].last_rendered_node = new_children.into(); } // We have no suspended nodes, but we just became suspended. Move the children to the background (None, true) => { let old_children = last_rendered_node; let new_children: VNode = children.as_vnode().clone(); let new_placeholder = LastRenderedNode::new(fallback.call(suspense_context.clone())); // Move the children to the background let mount = old_children.mount.get(); let parent = dom.get_mounted_parent(mount); suspense_context.in_suspense_placeholder(&dom.runtime(), || { old_children.move_node_to_background( std::slice::from_ref(&new_placeholder), parent, dom, to, ); }); // Then diff the new children in the background suspense_context.under_suspense_boundary(&dom.runtime(), || { old_children.diff_node(&new_children, dom, None::<&mut M>); }); // Set the last rendered node to the new suspense placeholder dom.scopes[scope_id.0].last_rendered_node = Some(new_placeholder); let suspense_context = SuspenseContext::downcast_suspense_boundary_from_scope( &dom.runtime, scope_id, ) .unwrap(); suspense_context.set_suspended_nodes(new_children); un_resolve_suspense(dom, scope_id); } // We have suspended nodes, but we just got out of suspense. Move the suspended nodes to the foreground (Some(_), false) => { // Take the suspended nodes out of the suspense boundary so the children know that the boundary is not suspended while diffing let old_suspended_nodes = suspense_context.take_suspended_nodes().unwrap(); let old_placeholder = last_rendered_node; let new_children = children; // First diff the two children nodes in the background suspense_context.under_suspense_boundary(&dom.runtime(), || { old_suspended_nodes.diff_node(&new_children, dom, None::<&mut M>); // Then replace the placeholder with the new children let mount = old_placeholder.mount.get(); let parent = dom.get_mounted_parent(mount); old_placeholder.replace( std::slice::from_ref(&new_children), parent, dom, to, ); }); // Set the last rendered node to the new children dom.scopes[scope_id.0].last_rendered_node = Some(new_children); mark_suspense_resolved(&suspense_context, dom, scope_id); } } }) } } /// Move to a resolved suspense state fn mark_suspense_resolved( suspense_context: &SuspenseContext, dom: &mut VirtualDom, scope_id: ScopeId, ) { dom.resolved_scopes.push(scope_id); // Run any closures that were waiting for the suspense to resolve suspense_context.run_resolved_closures(&dom.runtime); } /// Move from a resolved suspense state to an suspended state fn un_resolve_suspense(dom: &mut VirtualDom, scope_id: ScopeId) { dom.resolved_scopes.retain(|&id| id != scope_id); } impl SuspenseContext { /// Run a closure under a suspense boundary pub(crate) fn under_suspense_boundary<O>(&self, runtime: &Runtime, f: impl FnOnce() -> O) -> O { runtime.with_suspense_location(SuspenseLocation::UnderSuspense(self.clone()), f) } /// Run a closure under a suspense placeholder pub(crate) fn in_suspense_placeholder<O>(&self, runtime: &Runtime, f: impl FnOnce() -> O) -> O { runtime.with_suspense_location(SuspenseLocation::InSuspensePlaceholder(self.clone()), f) } /// Try to get a suspense boundary from a scope id pub fn downcast_suspense_boundary_from_scope( runtime: &Runtime, scope_id: ScopeId, ) -> Option<Self> { runtime .try_get_state(scope_id) .and_then(|scope| scope.suspense_boundary()) } pub(crate) fn remove_suspended_nodes<M: WriteMutations>( dom: &mut VirtualDom, scope_id: ScopeId, destroy_component_state: bool, ) { let Some(scope) = Self::downcast_suspense_boundary_from_scope(&dom.runtime, scope_id) else { return; }; // Remove the suspended nodes if let Some(node) = scope.take_suspended_nodes() { node.remove_node_inner(dom, None::<&mut M>, destroy_component_state, None) } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/diff_dynamic_node.rs
packages/core/tests/diff_dynamic_node.rs
use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::prelude::*; use dioxus_core::generation; use pretty_assertions::assert_eq; #[test] fn toggle_option_text() { let mut dom = VirtualDom::new(|| { let gen = generation(); let text = if gen % 2 != 0 { Some("hello") } else { None }; println!("{:?}", text); rsx! { div { {text} } } }); // load the div and then assign the None as a placeholder assert_eq!( dom.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, CreatePlaceholder { id: ElementId(2,) }, ReplacePlaceholder { path: &[0], m: 1 }, AppendChildren { id: ElementId(0), m: 1 }, ] ); // Rendering again should replace the placeholder with an text node dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ CreateTextNode { value: "hello".to_string(), id: ElementId(3,) }, ReplaceWith { id: ElementId(2,), m: 1 }, ] ); // Rendering again should replace the placeholder with an text node dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ CreatePlaceholder { id: ElementId(2,) }, ReplaceWith { id: ElementId(3,), m: 1 }, ] ); } // Regression test for https://github.com/DioxusLabs/dioxus/issues/2815 #[test] fn toggle_template() { fn app() -> Element { rsx!( Comp { if true { "{true}" } } ) } #[component] fn Comp(children: Element) -> Element { let show = generation() % 2 == 0; rsx! { if show { {children} } } } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); // Rendering again should replace the placeholder with an text node dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ CreatePlaceholder { id: ElementId(2) }, ReplaceWith { id: ElementId(1), m: 1 }, ] ); dom.mark_dirty(ScopeId(ScopeId::APP.0 + 1)); assert_eq!( dom.render_immediate_to_vec().edits, [ CreateTextNode { value: "true".to_string(), id: ElementId(1) }, ReplaceWith { id: ElementId(2), m: 1 }, ] ); dom.mark_dirty(ScopeId(ScopeId::APP.0 + 1)); assert_eq!( dom.render_immediate_to_vec().edits, [ CreatePlaceholder { id: ElementId(2) }, ReplaceWith { id: ElementId(1), m: 1 }, ] ); dom.mark_dirty(ScopeId(ScopeId::APP.0 + 1)); assert_eq!( dom.render_immediate_to_vec().edits, [ CreateTextNode { value: "true".to_string(), id: ElementId(1) }, ReplaceWith { id: ElementId(2), m: 1 }, ] ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/kitchen_sink.rs
packages/core/tests/kitchen_sink.rs
use dioxus::dioxus_core::{ElementId, Mutation}; use dioxus::prelude::*; use dioxus_core::IntoAttributeValue; use pretty_assertions::assert_eq; fn basic_syntax_is_a_template() -> Element { let asd = 123; let var = 123; rsx! { div { key: "{asd}", class: "asd", class: "{asd}", class: if true { "{asd}" }, class: if false { "{asd}" }, onclick: move |_| {}, div { "{var}" } div { h1 { "var" } p { "you're great!" } div { background_color: "red", h1 { "var" } div { b { "asd" } "not great" } } p { "you're great!" } } } } } #[test] fn dual_stream() { let mut dom = VirtualDom::new(basic_syntax_is_a_template); let edits = dom.rebuild_to_vec(); use Mutation::*; assert_eq!(edits.edits, { [ LoadTemplate { index: 0, id: ElementId(1) }, SetAttribute { name: "class", value: "asd 123 123 ".into_value(), id: ElementId(1), ns: None, }, NewEventListener { name: "click".to_string(), id: ElementId(1) }, CreateTextNode { value: "123".to_string(), id: ElementId(2) }, ReplacePlaceholder { path: &[0, 0], m: 1 }, AppendChildren { id: ElementId(0), m: 1 }, ] }); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/suspense.rs
packages/core/tests/suspense.rs
use dioxus::prelude::*; use dioxus_core::{generation, AttributeValue, ElementId, Mutation}; use pretty_assertions::assert_eq; use std::future::poll_fn; use std::task::Poll; async fn poll_three_times() { // Poll each task 3 times let mut count = 0; poll_fn(|cx| { println!("polling... {}", count); if count < 3 { count += 1; cx.waker().wake_by_ref(); Poll::Pending } else { Poll::Ready(()) } }) .await; } #[test] fn suspense_resolves_ssr() { // wait just a moment, not enough time for the boundary to resolve tokio::runtime::Builder::new_current_thread() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); dom.rebuild_in_place(); dom.wait_for_suspense().await; dom.render_immediate(&mut dioxus_core::NoOpMutations); let out = dioxus_ssr::render(&dom); assert_eq!(out, "<div>Waiting for... child</div>"); }); } fn app() -> Element { rsx!( div { "Waiting for... " SuspenseBoundary { fallback: |_| rsx! { "fallback" }, suspended_child {} } } ) } fn suspended_child() -> Element { let mut val = use_signal(|| 0); // Tasks that are not suspended should never be polled spawn(async move { panic!("Non-suspended task was polled"); }); // Memos should still work like normal let memo = use_memo(move || val * 2); assert_eq!(memo, val * 2); if val() < 3 { let task = spawn(async move { poll_three_times().await; println!("waiting... {}", val); val += 1; }); suspend(task)?; } rsx!("child") } /// When switching from a suspense fallback to the real child, the state of that component must be kept #[test] fn suspense_keeps_state() { tokio::runtime::Builder::new_current_thread() .enable_time() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.render_suspense_immediate().await; let out = dioxus_ssr::render(&dom); assert_eq!(out, "fallback"); dom.wait_for_suspense().await; let out = dioxus_ssr::render(&dom); assert_eq!(out, "<div>child with future resolved</div>"); }); fn app() -> Element { rsx! { SuspenseBoundary { fallback: |_| rsx! { "fallback" }, Child {} } } } #[component] fn Child() -> Element { let mut future_resolved = use_signal(|| false); let task = use_hook(|| { spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(100)).await; future_resolved.set(true); }) }); if !future_resolved() { suspend(task)?; } println!("future resolved: {future_resolved:?}"); if future_resolved() { rsx! { div { "child with future resolved" } } } else { rsx! { div { "this should never be rendered" } } } } } /// spawn doesn't run in suspense #[test] fn suspense_does_not_poll_spawn() { tokio::runtime::Builder::new_current_thread() .enable_time() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.wait_for_suspense().await; let out = dioxus_ssr::render(&dom); assert_eq!(out, "<div>child with future resolved</div>"); }); fn app() -> Element { rsx! { SuspenseBoundary { fallback: |_| rsx! { "fallback" }, Child {} } } } #[component] fn Child() -> Element { let mut future_resolved = use_signal(|| false); // futures that are spawned, but not suspended should never be polled use_hook(|| { spawn(async move { panic!("Non-suspended task was polled"); }); }); let task = use_hook(|| { spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(100)).await; future_resolved.set(true); }) }); if !future_resolved() { suspend(task)?; } rsx! { div { "child with future resolved" } } } } /// suspended nodes are not mounted, so they should not run effects #[test] fn suspended_nodes_dont_trigger_effects() { tokio::runtime::Builder::new_current_thread() .enable_time() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); let work = async move { loop { dom.wait_for_work().await; dom.render_immediate(&mut dioxus_core::NoOpMutations); } }; tokio::select! { _ = work => {}, _ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {} } }); fn app() -> Element { rsx! { SuspenseBoundary { fallback: |_| rsx! { "fallback" }, Child {} } } } #[component] fn RerendersFrequently() -> Element { let mut count = use_signal(|| 0); use_future(move || async move { for _ in 0..100 { tokio::time::sleep(std::time::Duration::from_millis(10)).await; count.set(count() + 1); } }); rsx! { div { "rerenders frequently" } } } #[component] fn Child() -> Element { let mut future_resolved = use_signal(|| false); use_effect(|| panic!("effects should not run during suspense")); let task = use_hook(|| { spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(500)).await; future_resolved.set(true); }) }); if !future_resolved() { suspend(task)?; } rsx! { div { "child with future resolved" } } } } /// Make sure we keep any state of components when we switch from a resolved future to a suspended future #[test] fn resolved_to_suspended() { static SUSPENDED: GlobalSignal<bool> = Signal::global(|| false); tokio::runtime::Builder::new_current_thread() .enable_time() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); let out = dioxus_ssr::render(&dom); assert_eq!(out, "rendered 1 times"); dom.in_scope(ScopeId::APP, || *SUSPENDED.write() = true); dom.render_suspense_immediate().await; let out = dioxus_ssr::render(&dom); assert_eq!(out, "fallback"); dom.wait_for_suspense().await; let out = dioxus_ssr::render(&dom); assert_eq!(out, "rendered 3 times"); }); fn app() -> Element { rsx! { SuspenseBoundary { fallback: |_| rsx! { "fallback" }, Child {} } } } #[component] fn Child() -> Element { let mut render_count = use_signal(|| 0); render_count += 1; let mut task = use_hook(|| CopyValue::new(None)); tracing::info!("render_count: {}", render_count.peek()); if SUSPENDED() { if task().is_none() { task.set(Some(spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(100)).await; tracing::info!("task finished"); *SUSPENDED.write() = false; }))); } suspend(task().unwrap())?; } rsx! { "rendered {render_count.peek()} times" } } } /// Make sure suspense tells the renderer that a suspense boundary was resolved #[test] fn suspense_tracks_resolved() { tokio::runtime::Builder::new_current_thread() .enable_time() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.render_suspense_immediate().await; dom.wait_for_suspense_work().await; assert_eq!( dom.render_suspense_immediate().await, vec![ScopeId(ScopeId::APP.0 + 1)] ); }); fn app() -> Element { rsx! { SuspenseBoundary { fallback: |_| rsx! { "fallback" }, Child {} } } } #[component] fn Child() -> Element { let mut resolved = use_signal(|| false); let task = use_hook(|| { spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(100)).await; tracing::info!("task finished"); resolved.set(true); }) }); if resolved() { println!("suspense is resolved"); } else { println!("suspense is not resolved"); suspend(task)?; } rsx! { "child" } } } // Regression test for https://github.com/DioxusLabs/dioxus/issues/2783 #[test] fn toggle_suspense() { use dioxus::prelude::*; fn app() -> Element { rsx! { SuspenseBoundary { fallback: |_| rsx! { "fallback" }, if generation() % 2 == 0 { Page {} } else { Home {} } } } } #[component] pub fn Home() -> Element { let _calculation = use_resource(|| async move { tokio::time::sleep(std::time::Duration::from_secs(1)).await; 1 + 1 }) .suspend()?; rsx! { "hello world" } } #[component] pub fn Page() -> Element { rsx! { "goodbye world" } } tokio::runtime::Builder::new_current_thread() .enable_time() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); let mutations = dom.rebuild_to_vec(); // First create goodbye world println!("{:#?}", mutations); assert_eq!( mutations.edits, [ Mutation::LoadTemplate { index: 0, id: ElementId(1) }, Mutation::AppendChildren { id: ElementId(0), m: 1 } ] ); dom.mark_dirty(ScopeId::APP); let mutations = dom.render_immediate_to_vec(); // Then replace that with nothing println!("{:#?}", mutations); assert_eq!( mutations.edits, [ Mutation::CreatePlaceholder { id: ElementId(2) }, Mutation::ReplaceWith { id: ElementId(1), m: 1 }, ] ); dom.wait_for_work().await; let mutations = dom.render_immediate_to_vec(); // Then replace it with a placeholder println!("{:#?}", mutations); assert_eq!( mutations.edits, [ Mutation::LoadTemplate { index: 0, id: ElementId(1) }, Mutation::ReplaceWith { id: ElementId(2), m: 1 }, ] ); dom.wait_for_work().await; let mutations = dom.render_immediate_to_vec(); // Then replace it with the resolved node println!("{:#?}", mutations); assert_eq!( mutations.edits, [ Mutation::CreatePlaceholder { id: ElementId(2,) }, Mutation::ReplaceWith { id: ElementId(1,), m: 1 }, Mutation::LoadTemplate { index: 0, id: ElementId(1) }, Mutation::ReplaceWith { id: ElementId(2), m: 1 }, ] ); }); } #[test] fn nested_suspense_resolves_client() { use Mutation::*; async fn poll_three_times() { // Poll each task 3 times let mut count = 0; poll_fn(|cx| { println!("polling... {}", count); if count < 3 { count += 1; cx.waker().wake_by_ref(); Poll::Pending } else { Poll::Ready(()) } }) .await; } fn app() -> Element { rsx! { SuspenseBoundary { fallback: move |_| rsx! {}, LoadTitle {} } MessageWithLoader { id: 0 } } } #[component] fn MessageWithLoader(id: usize) -> Element { rsx! { SuspenseBoundary { fallback: move |_| rsx! { "Loading {id}..." }, Message { id } } } } #[component] fn LoadTitle() -> Element { let title = use_resource(move || async_content(0)).suspend()?(); rsx! { document::Title { "{title.title}" } } } #[component] fn Message(id: usize) -> Element { let message = use_resource(move || async_content(id)).suspend()?(); rsx! { h2 { id: "title-{id}", "{message.title}" } p { id: "body-{id}", "{message.body}" } div { id: "children-{id}", padding: "10px", for child in message.children { MessageWithLoader { id: child } } } } } #[derive(Clone)] pub struct Content { title: String, body: String, children: Vec<usize>, } async fn async_content(id: usize) -> Content { let content_tree = [ Content { title: "The robot says hello world".to_string(), body: "The robot becomes sentient and says hello world".to_string(), children: vec![1, 2], }, Content { title: "The world says hello back".to_string(), body: "In a stunning turn of events, the world collectively unites and says hello back" .to_string(), children: vec![], }, Content { title: "Goodbye Robot".to_string(), body: "The robot says goodbye".to_string(), children: vec![3], }, Content { title: "Goodbye Robot again".to_string(), body: "The robot says goodbye again".to_string(), children: vec![], }, ]; poll_three_times().await; content_tree[id].clone() } // wait just a moment, not enough time for the boundary to resolve tokio::runtime::Builder::new_current_thread() .build() .unwrap() .block_on(async { let mut dom = VirtualDom::new(app); let mutations = dom.rebuild_to_vec(); // Initial loading message and loading title assert_eq!( mutations.edits, vec![ CreatePlaceholder { id: ElementId(1,) }, CreateTextNode { value: "Loading 0...".to_string(), id: ElementId(2,) }, AppendChildren { id: ElementId(0,), m: 2 }, ] ); dom.wait_for_work().await; // DOM STATE: // placeholder // ID: 1 // "Loading 0..." // ID: 2 let mutations = dom.render_immediate_to_vec(); // Fill in the contents of the initial message and start loading the nested suspense // The title also finishes loading assert_eq!( mutations.edits, vec![ // Creating and swapping these placeholders doesn't do anything // It is just extra work that we are forced to do because mutations are not // reversible. We start rendering the children and then realize it is suspended. // Then we need to replace what we just rendered with the suspense placeholder CreatePlaceholder { id: ElementId(3,) }, ReplaceWith { id: ElementId(1,), m: 1 }, // Replace the pending placeholder with the title placeholder CreatePlaceholder { id: ElementId(1,) }, ReplaceWith { id: ElementId(3,), m: 1 }, // Replace loading... with a placeholder for us to fill in later CreatePlaceholder { id: ElementId(3,) }, ReplaceWith { id: ElementId(2,), m: 1 }, // Load the title LoadTemplate { index: 0, id: ElementId(2,) }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("title-0".to_string()), id: ElementId(2,), }, CreateTextNode { value: "The robot says hello world".to_string(), id: ElementId(4,) }, ReplacePlaceholder { path: &[0,], m: 1 }, // Then load the body LoadTemplate { index: 1, id: ElementId(5,) }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("body-0".to_string()), id: ElementId(5,), }, CreateTextNode { value: "The robot becomes sentient and says hello world".to_string(), id: ElementId(6,) }, ReplacePlaceholder { path: &[0,], m: 1 }, // Then load the suspended children LoadTemplate { index: 2, id: ElementId(7,) }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("children-0".to_string()), id: ElementId(7,), }, CreateTextNode { value: "Loading 1...".to_string(), id: ElementId(8,) }, CreateTextNode { value: "Loading 2...".to_string(), id: ElementId(9,) }, ReplacePlaceholder { path: &[0,], m: 2 }, // Finally replace the loading placeholder in the body with the resolved children ReplaceWith { id: ElementId(3,), m: 3 }, ] ); dom.wait_for_work().await; // DOM STATE: // placeholder // ID: 1 // h2 // ID: 2 // p // ID: 5 // div // ID: 7 // "Loading 1..." // ID: 8 // "Loading 2..." // ID: 9 let mutations = dom.render_immediate_to_vec(); assert_eq!( mutations.edits, vec![ // Replace the first loading placeholder with a placeholder for us to fill in later CreatePlaceholder { id: ElementId( 3, ), }, ReplaceWith { id: ElementId( 8, ), m: 1, }, // Load the nested suspense LoadTemplate { index: 0, id: ElementId( 8, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("title-1".to_string()), id: ElementId( 8, ), }, CreateTextNode { value: "The world says hello back".to_string(), id: ElementId(10,) }, ReplacePlaceholder { path: &[ 0, ], m: 1, }, LoadTemplate { index: 1, id: ElementId( 11, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("body-1".to_string()), id: ElementId( 11, ), }, CreateTextNode { value: "In a stunning turn of events, the world collectively unites and says hello back".to_string(), id: ElementId(12,) }, ReplacePlaceholder { path: &[ 0, ], m: 1, }, LoadTemplate { index: 2, id: ElementId( 13, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("children-1".to_string()), id: ElementId( 13, ), }, CreatePlaceholder { id: ElementId(14,) }, ReplacePlaceholder { path: &[ 0, ], m: 1, }, ReplaceWith { id: ElementId( 3, ), m: 3, }, // Replace the second loading placeholder with a placeholder for us to fill in later CreatePlaceholder { id: ElementId( 3, ), }, ReplaceWith { id: ElementId( 9, ), m: 1, }, LoadTemplate { index: 0, id: ElementId( 9, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("title-2".to_string()), id: ElementId( 9, ), }, CreateTextNode { value: "Goodbye Robot".to_string(), id: ElementId(15,) }, ReplacePlaceholder { path: &[ 0, ], m: 1, }, LoadTemplate { index: 1, id: ElementId( 16, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("body-2".to_string()), id: ElementId( 16, ), }, CreateTextNode { value: "The robot says goodbye".to_string(), id: ElementId(17,) }, ReplacePlaceholder { path: &[ 0, ], m: 1, }, LoadTemplate { index: 2, id: ElementId( 18, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("children-2".to_string()), id: ElementId( 18, ), }, // Create a placeholder for the resolved children CreateTextNode { value: "Loading 3...".to_string(), id: ElementId(19,) }, ReplacePlaceholder { path: &[0,], m: 1 }, // Replace the loading placeholder with the resolved children ReplaceWith { id: ElementId( 3, ), m: 3, }, ] ); dom.wait_for_work().await; let mutations = dom.render_immediate_to_vec(); assert_eq!( mutations.edits, vec![ CreatePlaceholder { id: ElementId( 3, ), }, ReplaceWith { id: ElementId( 19, ), m: 1, }, LoadTemplate { index: 0, id: ElementId( 19, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("title-3".to_string()), id: ElementId( 19, ), }, CreateTextNode { value: "Goodbye Robot again".to_string(), id: ElementId(20,) }, ReplacePlaceholder { path: &[ 0, ], m: 1, }, LoadTemplate { index: 1, id: ElementId( 21, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("body-3".to_string()), id: ElementId( 21, ), }, CreateTextNode { value: "The robot says goodbye again".to_string(), id: ElementId(22,) }, ReplacePlaceholder { path: &[ 0, ], m: 1, }, LoadTemplate { index: 2, id: ElementId( 23, ), }, SetAttribute { name: "id", ns: None, value: AttributeValue::Text("children-3".to_string()), id: ElementId( 23, ), }, CreatePlaceholder { id: ElementId(24,) }, ReplacePlaceholder { path: &[ 0 ], m: 1, }, ReplaceWith { id: ElementId( 3, ), m: 3, }, ] ) }); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/miri_stress.rs
packages/core/tests/miri_stress.rs
#![allow(non_snake_case)] use std::rc::Rc; use dioxus::prelude::*; use dioxus_core::{generation, NoOpMutations}; /// This test checks that we should release all memory used by the virtualdom when it exits. /// /// When miri runs, it'll let us know if we leaked or aliased. #[test] fn test_memory_leak() { fn app() -> Element { let val = generation(); spawn(async {}); if val == 2 || val == 4 { return rsx!({}); } let mut name = use_hook(|| String::from("numbers: ")); name.push_str("123 "); rsx!( div { "Hello, world!" } Child {} Child {} Child {} Child {} Child {} Child {} BorrowedChild { name: name.clone() } BorrowedChild { name: name.clone() } BorrowedChild { name: name.clone() } BorrowedChild { name: name.clone() } BorrowedChild { name: name.clone() } ) } #[derive(Props, Clone, PartialEq)] struct BorrowedProps { name: String, } fn BorrowedChild(cx: BorrowedProps) -> Element { rsx! { div { "goodbye {cx.name}" Child {} Child {} } } } fn Child() -> Element { rsx!( div { "goodbye world" } ) } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); for _ in 0..5 { dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); } } #[test] fn memo_works_properly() { fn app() -> Element { let val = generation(); if val == 2 || val == 4 { return Element::Ok(VNode::default()); } let name = use_hook(|| String::from("asd")); rsx!( div { "Hello, world! {name}" } Child { na: "asdfg".to_string() } ) } #[derive(PartialEq, Clone, Props)] struct ChildProps { na: String, } fn Child(_props: ChildProps) -> Element { rsx!( div { "goodbye world" } ) } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); } #[test] fn free_works_on_root_hooks() { /* On Drop, scopearena drops all the hook contents. and props */ #[derive(PartialEq, Clone, Props)] struct AppProps { inner: Rc<String>, } fn app(cx: AppProps) -> Element { let name: AppProps = use_hook(|| cx.clone()); rsx!(child_component { inner: name.inner.clone() }) } fn child_component(props: AppProps) -> Element { rsx!( div { "{props.inner}" } ) } let ptr = Rc::new("asdasd".to_string()); let mut dom = VirtualDom::new_with_props(app, AppProps { inner: ptr.clone() }); dom.rebuild(&mut dioxus_core::NoOpMutations); // ptr gets cloned into props and then into the hook assert!(Rc::strong_count(&ptr) > 1); drop(dom); assert_eq!(Rc::strong_count(&ptr), 1); } #[test] fn supports_async() { use std::time::Duration; use tokio::time::sleep; fn app() -> Element { let mut colors = use_signal(|| vec!["green", "blue", "red"]); let mut padding = use_signal(|| 10); use_hook(|| { spawn(async move { loop { sleep(Duration::from_millis(1000)).await; colors.with_mut(|colors| colors.reverse()); } }) }); use_hook(|| { spawn(async move { loop { sleep(Duration::from_millis(10)).await; padding.with_mut(|padding| { if *padding < 65 { *padding += 1; } else { *padding = 5; } }); } }) }); let colors = colors.read(); let big = colors[0]; let mid = colors[1]; let small = colors[2]; rsx! { div { background: "{big}", height: "stretch", width: "stretch", padding: "50", label { "hello" } div { background: "{mid}", height: "auto", width: "stretch", padding: "{padding}", label { "World" } div { background: "{small}", height: "auto", width: "stretch", padding: "20", label { "ddddddd" } } } } } } let rt = tokio::runtime::Builder::new_current_thread() .enable_time() .build() .unwrap(); rt.block_on(async { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); for _ in 0..10 { dom.wait_for_work().await; dom.render_immediate(&mut NoOpMutations); } }); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/safety.rs
packages/core/tests/safety.rs
//! Tests related to safety of the library. use dioxus::prelude::*; /// Ensure no issues with not calling rebuild_to_vec #[test] fn root_node_isnt_null() { let dom = VirtualDom::new(|| rsx!("Hello world!")); let scope = dom.base_scope(); // We haven't built the tree, so trying to get out the root node should fail assert!(scope.try_root_node().is_none()); dom.in_runtime(|| { // The height should be 0 assert_eq!(scope.height(), 0); }); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/event_propagation.rs
packages/core/tests/event_propagation.rs
use dioxus::prelude::*; use dioxus_core::ElementId; use std::{any::Any, rc::Rc, sync::Mutex}; static CLICKS: Mutex<usize> = Mutex::new(0); #[test] fn events_propagate() { set_event_converter(Box::new(dioxus::html::SerializedHtmlEventConverter)); let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); // Top-level click is registered let event = Event::new( Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())) as Rc<dyn Any>, true, ); dom.runtime().handle_event("click", event, ElementId(1)); assert_eq!(*CLICKS.lock().unwrap(), 1); // break reference.... for _ in 0..5 { dom.mark_dirty(ScopeId(0)); _ = dom.render_immediate_to_vec(); } // Lower click is registered let event = Event::new( Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())) as Rc<dyn Any>, true, ); dom.runtime().handle_event("click", event, ElementId(2)); assert_eq!(*CLICKS.lock().unwrap(), 3); // break reference.... for _ in 0..5 { dom.mark_dirty(ScopeId(0)); _ = dom.render_immediate_to_vec(); } // Stop propagation occurs let event = Event::new( Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())) as Rc<dyn Any>, true, ); dom.runtime().handle_event("click", event, ElementId(2)); assert_eq!(*CLICKS.lock().unwrap(), 3); } fn app() -> Element { rsx! { div { onclick: move |_| { println!("top clicked"); *CLICKS.lock().unwrap() += 1; }, {vec![ rsx! { problematic_child {} } ].into_iter()} } } } fn problematic_child() -> Element { rsx! { button { onclick: move |evt| { println!("bottom clicked"); let mut clicks = CLICKS.lock().unwrap(); if *clicks == 3 { evt.stop_propagation(); } else { *clicks += 1; } } } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/create_passthru.rs
packages/core/tests/create_passthru.rs
use dioxus::dioxus_core::Mutation::*; use dioxus::prelude::*; use dioxus_core::ElementId; /// Should push the text node onto the stack and modify it #[test] fn nested_passthru_creates() { fn app() -> Element { rsx! { PassThru { PassThru { PassThru { div { "hi" } } } } } } #[component] fn PassThru(children: Element) -> Element { rsx!({ children }) } let mut dom = VirtualDom::new(app); let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(1) }, AppendChildren { m: 1, id: ElementId(0) }, ] ) } /// Should load all the templates and append them /// /// Take note on how we don't spit out the template for child_comp since it's entirely dynamic #[test] fn nested_passthru_creates_add() { fn app() -> Element { rsx! { ChildComp { "1" ChildComp { "2" ChildComp { "3" div { "hi" } } } } } } #[component] fn ChildComp(children: Element) -> Element { rsx! {{children}} } let mut dom = VirtualDom::new(app); assert_eq!( dom.rebuild_to_vec().edits, [ // load 1 LoadTemplate { index: 0, id: ElementId(1) }, // load 2 LoadTemplate { index: 0, id: ElementId(2) }, // load 3 LoadTemplate { index: 0, id: ElementId(3) }, // load div that contains 4 LoadTemplate { index: 1, id: ElementId(4) }, AppendChildren { id: ElementId(0), m: 4 }, ] ); } /// note that the template is all dynamic roots - so it doesn't actually get cached as a template #[test] fn dynamic_node_as_root() { fn app() -> Element { let a = 123; let b = 456; rsx! { "{a}" "{b}" } } let mut dom = VirtualDom::new(app); let edits = dom.rebuild_to_vec(); // Since the roots were all dynamic, they should not cause any template muations // The root node is text, so we just create it on the spot assert_eq!( edits.edits, [ CreateTextNode { value: "123".to_string(), id: ElementId(1) }, CreateTextNode { value: "456".to_string(), id: ElementId(2) }, AppendChildren { id: ElementId(0), m: 2 } ] ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/children_drop_futures.rs
packages/core/tests/children_drop_futures.rs
//! Verify that when children are dropped, they drop their futures before they are polled use std::{sync::atomic::AtomicUsize, time::Duration}; use dioxus::prelude::*; use dioxus_core::generation; #[tokio::test] async fn child_futures_drop_first() { static POLL_COUNT: AtomicUsize = AtomicUsize::new(0); fn app() -> Element { if generation() == 0 { rsx! { Child {} } } else { rsx! {} } } #[component] fn Child() -> Element { // Spawn a task that will increment POLL_COUNT every 10 milliseconds // This should be dropped after the second time the parent is run use_hook(|| { spawn(async { POLL_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); }); }); rsx! {} } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); // Here the parent and task could resolve at the same time, but because the task is in the child, dioxus should run the parent first because the child might be dropped dom.mark_dirty(ScopeId::APP); tokio::select! { _ = dom.wait_for_work() => {} _ = tokio::time::sleep(Duration::from_millis(500)) => panic!("timed out") }; dom.render_immediate(&mut dioxus_core::NoOpMutations); // By the time the tasks are finished, we should've accumulated ticks from two tasks // Be warned that by setting the delay to too short, tokio might not schedule in the tasks assert_eq!( POLL_COUNT.fetch_add(0, std::sync::atomic::Ordering::Relaxed), 0 ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/memory_leak.rs
packages/core/tests/memory_leak.rs
#![allow(non_snake_case)] use dioxus::prelude::dioxus_core::NoOpMutations; use dioxus::prelude::*; use sysinfo::{ProcessRefreshKind, RefreshKind, System}; // Regression test for https://github.com/DioxusLabs/dioxus/issues/3421 #[tokio::test] async fn test_for_memory_leaks() { fn app() -> Element { let mut count = use_signal(|| 0); use_hook(|| { spawn(async move { loop { tokio::time::sleep(std::time::Duration::from_nanos(1)).await; let val = *count.peek_unchecked(); if val == 70 { count.set(0); } else { count.set(val + 1); } } }) }); rsx! { for el in 0..*count.read() { div { key: "{el}", div { onclick: move |_| { println!("click"); }, } AcceptsEventHandlerAndReadSignal { event_handler: move |_| { println!("click"); }, signal: el, } } } } } // Event handlers and ReadSignals have extra logic on component boundaries that has caused memory leaks // in the past #[component] fn AcceptsEventHandlerAndReadSignal( event_handler: EventHandler<MouseEvent>, signal: ReadSignal<i32>, ) -> Element { rsx! { div { onclick: event_handler, "{signal}" } } } // create the vdom, the real_dom, and the binding layer between them let mut vdom = VirtualDom::new(app); vdom.rebuild(&mut NoOpMutations); let pid = sysinfo::get_current_pid().expect("failed to get PID"); let refresh = RefreshKind::nothing().with_processes(ProcessRefreshKind::nothing().with_memory()); let mut system = System::new_with_specifics(refresh); let mut get_memory_usage = || { system.refresh_specifics(refresh); let this_process = system.process(pid).expect("failed to get process"); this_process.memory() }; let initial_memory_usage = get_memory_usage(); // we need to run the vdom in a async runtime for i in 0..=10000 { // wait for the vdom to update vdom.wait_for_work().await; // get the mutations from the vdom vdom.render_immediate(&mut NoOpMutations); if i % 1000 == 0 { let new_memory_usage = get_memory_usage(); println!("iteration: {} memory usage: {}", i, new_memory_usage); // Memory usage might increase as arenas fill up, but it shouldn't double from the initial render assert!(new_memory_usage < initial_memory_usage * 2); } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/boolattrs.rs
packages/core/tests/boolattrs.rs
use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::prelude::*; #[test] fn bool_test() { let mut app = VirtualDom::new(|| rsx!(div { hidden: false })); assert_eq!( app.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1) }, SetAttribute { name: "hidden", value: dioxus_core::AttributeValue::Bool(false), id: ElementId(1,), ns: None }, AppendChildren { m: 1, id: ElementId(0) }, ] ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/error_boundary.rs
packages/core/tests/error_boundary.rs
#![allow(non_snake_case)] use dioxus::{prelude::*, CapturedError}; #[test] fn catches_panic() { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); } fn app() -> Element { rsx! { div { h1 { "Title" } NoneChild {} ThrowChild {} } } } fn NoneChild() -> Element { VNode::empty() } fn ThrowChild() -> Element { Err(std::io::Error::new(std::io::ErrorKind::AddrInUse, "asd"))?; let _g: i32 = "123123".parse()?; rsx! { div {} } } #[test] fn clear_error_boundary() { static THREW_ERROR: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); #[component] fn App() -> Element { rsx! { AutoClearError {} } } #[component] pub fn ThrowsError() -> Element { if THREW_ERROR.load(std::sync::atomic::Ordering::SeqCst) { THREW_ERROR.store(true, std::sync::atomic::Ordering::SeqCst); Err(CapturedError::from_display("This is an error").into()) } else { rsx! { "We should see this" } } } #[component] pub fn AutoClearError() -> Element { rsx! { ErrorBoundary { handle_error: |error: ErrorContext| { error.clear_errors(); rsx! { "We cleared it" } }, ThrowsError {} } } } let mut dom = VirtualDom::new(App); dom.rebuild(&mut dioxus_core::NoOpMutations); let out = dioxus_ssr::render(&dom); assert_eq!(out, "We should see this"); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/fuzzing.rs
packages/core/tests/fuzzing.rs
#![cfg(not(miri))] use dioxus::prelude::*; use dioxus_core::{AttributeValue, DynamicNode, NoOpMutations, Template, VComponent, VNode, *}; use std::{any::Any, cell::RefCell, cfg, collections::HashSet, default::Default, rc::Rc}; fn random_ns() -> Option<&'static str> { let namespace = rand::random::<u8>() % 2; match namespace { 0 => None, 1 => Some(Box::leak( format!("ns{}", rand::random::<u8>()).into_boxed_str(), )), _ => unreachable!(), } } fn create_random_attribute(attr_idx: &mut usize) -> TemplateAttribute { match rand::random::<u8>() % 2 { 0 => TemplateAttribute::Static { name: Box::leak(format!("attr{}", rand::random::<u8>()).into_boxed_str()), value: Box::leak(format!("value{}", rand::random::<u8>()).into_boxed_str()), namespace: random_ns(), }, 1 => TemplateAttribute::Dynamic { id: { let old_idx = *attr_idx; *attr_idx += 1; old_idx }, }, _ => unreachable!(), } } fn create_random_template_node( dynamic_node_types: &mut Vec<DynamicNodeType>, template_idx: &mut usize, attr_idx: &mut usize, depth: usize, ) -> TemplateNode { match rand::random::<u8>() % 4 { 0 => { let attrs = { let attrs: Vec<_> = (0..(rand::random::<u8>() % 10)) .map(|_| create_random_attribute(attr_idx)) .collect(); Box::leak(attrs.into_boxed_slice()) }; TemplateNode::Element { tag: Box::leak(format!("tag{}", rand::random::<u8>()).into_boxed_str()), namespace: random_ns(), attrs, children: { if depth > 4 { &[] } else { let children: Vec<_> = (0..(rand::random::<u8>() % 3)) .map(|_| { create_random_template_node( dynamic_node_types, template_idx, attr_idx, depth + 1, ) }) .collect(); Box::leak(children.into_boxed_slice()) } }, } } 1 => TemplateNode::Text { text: Box::leak(format!("{}", rand::random::<u8>()).into_boxed_str()), }, 2 => TemplateNode::Dynamic { id: { let old_idx = *template_idx; *template_idx += 1; dynamic_node_types.push(DynamicNodeType::Text); old_idx }, }, 3 => TemplateNode::Dynamic { id: { let old_idx = *template_idx; *template_idx += 1; dynamic_node_types.push(DynamicNodeType::Other); old_idx }, }, _ => unreachable!(), } } fn generate_paths( node: &TemplateNode, current_path: &[u8], node_paths: &mut Vec<Vec<u8>>, attr_paths: &mut Vec<Vec<u8>>, ) { match node { TemplateNode::Element { children, attrs, .. } => { for attr in *attrs { match attr { TemplateAttribute::Static { .. } => {} TemplateAttribute::Dynamic { .. } => { attr_paths.push(current_path.to_vec()); } } } for (i, child) in children.iter().enumerate() { let mut current_path = current_path.to_vec(); current_path.push(i as u8); generate_paths(child, &current_path, node_paths, attr_paths); } } TemplateNode::Text { .. } => {} TemplateNode::Dynamic { .. } => { node_paths.push(current_path.to_vec()); } } } enum DynamicNodeType { Text, Other, } fn create_random_template(depth: u8) -> (Template, Box<[DynamicNode]>) { let mut dynamic_node_types = Vec::new(); let mut template_idx = 0; let mut attr_idx = 0; let roots = (0..(1 + rand::random::<u8>() % 5)) .map(|_| { create_random_template_node( &mut dynamic_node_types, &mut template_idx, &mut attr_idx, 0, ) }) .collect::<Vec<_>>(); assert!(!roots.is_empty()); let roots = Box::leak(roots.into_boxed_slice()); let mut node_paths = Vec::new(); let mut attr_paths = Vec::new(); for (i, root) in roots.iter().enumerate() { generate_paths(root, &[i as u8], &mut node_paths, &mut attr_paths); } let node_paths = Box::leak( node_paths .into_iter() .map(|v| &*Box::leak(v.into_boxed_slice())) .collect::<Vec<_>>() .into_boxed_slice(), ); let attr_paths = Box::leak( attr_paths .into_iter() .map(|v| &*Box::leak(v.into_boxed_slice())) .collect::<Vec<_>>() .into_boxed_slice(), ); let dynamic_nodes = dynamic_node_types .iter() .map(|ty| match ty { DynamicNodeType::Text => { DynamicNode::Text(VText::new(format!("{}", rand::random::<u8>()))) } DynamicNodeType::Other => create_random_dynamic_node(depth + 1), }) .collect(); (Template { roots, node_paths, attr_paths }, dynamic_nodes) } fn create_random_dynamic_node(depth: u8) -> DynamicNode { let range = if depth > 5 { 1 } else { 3 }; match rand::random::<u8>() % range { 0 => DynamicNode::Placeholder(Default::default()), 1 => (0..(rand::random::<u8>() % 5)) .map(|_| { VNode::new( None, Template { roots: &[TemplateNode::Dynamic { id: 0 }], node_paths: &[&[0]], attr_paths: &[], }, Box::new([DynamicNode::Component(VComponent::new( create_random_element, DepthProps { depth, root: false }, "create_random_element", ))]), Box::new([]), ) }) .into_dyn_node(), 2 => DynamicNode::Component(VComponent::new( create_random_element, DepthProps { depth, root: false }, "create_random_element", )), _ => unreachable!(), } } fn create_random_dynamic_attr() -> Attribute { let value = match rand::random::<u8>() % 7 { 0 => AttributeValue::Text(format!("{}", rand::random::<u8>())), 1 => AttributeValue::Float(rand::random()), 2 => AttributeValue::Int(rand::random()), 3 => AttributeValue::Bool(rand::random()), 4 => AttributeValue::any_value(rand::random::<u8>()), 5 => AttributeValue::None, 6 => { let value = AttributeValue::listener(|e: Event<String>| println!("{:?}", e)); return Attribute::new("ondata", value, None, false); } _ => unreachable!(), }; Attribute::new( Box::leak(format!("attr{}", rand::random::<u8>()).into_boxed_str()), value, random_ns(), rand::random(), ) } #[derive(PartialEq, Props, Clone)] struct DepthProps { depth: u8, root: bool, } fn create_random_element(cx: DepthProps) -> Element { let last_template = use_hook(|| Rc::new(RefCell::new(None))); if rand::random::<u8>() % 10 == 0 { needs_update(); } let range = if cx.root { 2 } else { 3 }; let node = match rand::random::<u8>() % range { // Change both the template and the dynamic nodes 0 => { let (template, dynamic_nodes) = create_random_template(cx.depth + 1); last_template.replace(Some(template)); VNode::new( None, template, dynamic_nodes, (0..template.attr_paths.len()) .map(|_| Box::new([create_random_dynamic_attr()]) as Box<[Attribute]>) .collect(), ) } // Change just the dynamic nodes 1 => { let (template, dynamic_nodes) = match *last_template.borrow() { Some(template) => ( template, (0..template.node_paths.len()) .map(|_| create_random_dynamic_node(cx.depth + 1)) .collect(), ), None => create_random_template(cx.depth + 1), }; VNode::new( None, template, dynamic_nodes, (0..template.attr_paths.len()) .map(|_| Box::new([create_random_dynamic_attr()]) as Box<[Attribute]>) .collect(), ) } // Remove the template _ => VNode::default(), }; Element::Ok(node) } // test for panics when creating random nodes and templates #[test] fn create() { let repeat_count = if cfg!(miri) { 100 } else { 1000 }; for _ in 0..repeat_count { let mut vdom = VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true }); vdom.rebuild(&mut NoOpMutations); } } // test for panics when diffing random nodes // This test will change the template every render which is not very realistic, but it helps stress the system #[test] fn diff() { let repeat_count = if cfg!(miri) { 100 } else { 1000 }; for _ in 0..repeat_count { let mut vdom = VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true }); vdom.rebuild(&mut NoOpMutations); // A list of all elements that have had event listeners // This is intentionally never cleared, so that we can test that calling event listeners that are removed doesn't cause a panic let mut event_listeners = HashSet::new(); for _ in 0..100 { for &id in &event_listeners { println!("firing event on {:?}", id); let event = Event::new( std::rc::Rc::new(String::from("hello world")) as Rc<dyn Any>, true, ); vdom.runtime().handle_event("data", event, id); } { vdom.render_immediate(&mut InsertEventListenerMutationHandler( &mut event_listeners, )); } } } } struct InsertEventListenerMutationHandler<'a>(&'a mut HashSet<ElementId>); impl WriteMutations for InsertEventListenerMutationHandler<'_> { fn append_children(&mut self, _: ElementId, _: usize) {} fn assign_node_id(&mut self, _: &'static [u8], _: ElementId) {} fn create_placeholder(&mut self, _: ElementId) {} fn create_text_node(&mut self, _: &str, _: ElementId) {} fn load_template(&mut self, _: Template, _: usize, _: ElementId) {} fn replace_node_with(&mut self, _: ElementId, _: usize) {} fn replace_placeholder_with_nodes(&mut self, _: &'static [u8], _: usize) {} fn insert_nodes_after(&mut self, _: ElementId, _: usize) {} fn insert_nodes_before(&mut self, _: ElementId, _: usize) {} fn set_attribute( &mut self, _: &'static str, _: Option<&'static str>, _: &AttributeValue, _: ElementId, ) { } fn set_node_text(&mut self, _: &str, _: ElementId) {} fn create_event_listener(&mut self, name: &'static str, id: ElementId) { println!("new event listener on {:?} for {:?}", id, name); self.0.insert(id); } fn remove_event_listener(&mut self, _: &'static str, _: ElementId) {} fn remove_node(&mut self, _: ElementId) {} fn push_root(&mut self, _: ElementId) {} }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/create_lists.rs
packages/core/tests/create_lists.rs
use dioxus::dioxus_core::Mutation::*; use dioxus::prelude::*; use dioxus_core::ElementId; use pretty_assertions::assert_eq; // A real-world usecase of templates at peak performance // In react, this would be a lot of node creation. // // In Dioxus, we memoize the rsx! body and simplify it down to a few template loads // // Also note that the IDs increase linearly. This lets us drive a vec on the renderer for O(1) re-indexing fn app() -> Element { rsx! { div { for i in 0..3 { div { h1 { "hello world! "} p { "{i}" } } } } } } #[test] fn list_renders() { let mut dom = VirtualDom::new(app); let edits = dom.rebuild_to_vec(); // note: we dont test template edits anymore // assert_eq!( // edits.templates, // [ // // Create the outer div // CreateElement { name: "div" }, // // todo: since this is the only child, we should just use // // append when modify the values (IE no need for a placeholder) // CreateStaticPlaceholder, // AppendChildren { m: 1 }, // SaveTemplate { m: 1 }, // // Create the inner template div // CreateElement { name: "div" }, // CreateElement { name: "h1" }, // CreateStaticText { value: "hello world! " }, // AppendChildren { m: 1 }, // CreateElement { name: "p" }, // CreateTextPlaceholder, // AppendChildren { m: 1 }, // AppendChildren { m: 2 }, // SaveTemplate { m: 1 } // ], // ); assert_eq!( edits.edits, [ // Load the outer div LoadTemplate { index: 0, id: ElementId(1) }, // Load each template one-by-one, rehydrating it LoadTemplate { index: 0, id: ElementId(2) }, CreateTextNode { value: "0".to_string(), id: ElementId(3) }, ReplacePlaceholder { path: &[1, 0], m: 1 }, LoadTemplate { index: 0, id: ElementId(4) }, CreateTextNode { value: "1".to_string(), id: ElementId(5) }, ReplacePlaceholder { path: &[1, 0], m: 1 }, LoadTemplate { index: 0, id: ElementId(6) }, CreateTextNode { value: "2".to_string(), id: ElementId(7) }, ReplacePlaceholder { path: &[1, 0], m: 1 }, // Replace the 0th childn on the div with the 3 templates on the stack ReplacePlaceholder { m: 3, path: &[0] }, // Append the container div to the dom AppendChildren { m: 1, id: ElementId(0) } ], ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/diff_unkeyed_list.rs
packages/core/tests/diff_unkeyed_list.rs
use std::collections::HashSet; use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::prelude::*; use dioxus_core::{generation, Mutation}; use pretty_assertions::assert_eq; #[test] fn list_creates_one_by_one() { let mut dom = VirtualDom::new(|| { let gen = generation(); rsx! { div { for i in 0..gen { div { "{i}" } } } } }); // load the div and then assign the empty fragment as a placeholder assert_eq!( dom.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, CreatePlaceholder { id: ElementId(2,) }, ReplacePlaceholder { path: &[0], m: 1 }, AppendChildren { id: ElementId(0), m: 1 }, ] ); // Rendering the first item should replace the placeholder with an element dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(3,) }, CreateTextNode { value: "0".to_string(), id: ElementId(4,) }, ReplacePlaceholder { path: &[0], m: 1 }, ReplaceWith { id: ElementId(2,), m: 1 }, ] ); // Rendering the next item should insert after the previous dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2,) }, CreateTextNode { value: "1".to_string(), id: ElementId(5,) }, ReplacePlaceholder { path: &[0], m: 1 }, InsertAfter { id: ElementId(3,), m: 1 }, ] ); // ... and again! dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(6,) }, CreateTextNode { value: "2".to_string(), id: ElementId(7,) }, ReplacePlaceholder { path: &[0], m: 1 }, InsertAfter { id: ElementId(2,), m: 1 }, ] ); // once more dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(8,) }, CreateTextNode { value: "3".to_string(), id: ElementId(9,) }, ReplacePlaceholder { path: &[0], m: 1 }, InsertAfter { id: ElementId(6,), m: 1 }, ] ); } #[test] fn removes_one_by_one() { let mut dom = VirtualDom::new(|| { let gen = 3 - generation() % 4; rsx! { div { for i in 0..gen { div { "{i}" } } } } }); // load the div and then assign the empty fragment as a placeholder assert_eq!( dom.rebuild_to_vec().edits, [ // The container LoadTemplate { index: 0, id: ElementId(1) }, // each list item LoadTemplate { index: 0, id: ElementId(2) }, CreateTextNode { value: "0".to_string(), id: ElementId(3) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 0, id: ElementId(4) }, CreateTextNode { value: "1".to_string(), id: ElementId(5) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 0, id: ElementId(6) }, CreateTextNode { value: "2".to_string(), id: ElementId(7) }, ReplacePlaceholder { path: &[0], m: 1 }, // replace the placeholder in the template with the 3 templates on the stack ReplacePlaceholder { m: 3, path: &[0] }, // Mount the div AppendChildren { id: ElementId(0), m: 1 } ] ); // Remove div(3) // Rendering the first item should replace the placeholder with an element dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [Remove { id: ElementId(6) }] ); // Remove div(2) dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [Remove { id: ElementId(4) }] ); // Remove div(1) and replace with a placeholder // todo: this should just be a remove with no placeholder dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ CreatePlaceholder { id: ElementId(4) }, ReplaceWith { id: ElementId(2), m: 1 } ] ); // load the 3 and replace the placeholder // todo: this should actually be append to, but replace placeholder is fine for now dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2) }, CreateTextNode { value: "0".to_string(), id: ElementId(3) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 0, id: ElementId(5) }, CreateTextNode { value: "1".to_string(), id: ElementId(6) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 0, id: ElementId(7) }, CreateTextNode { value: "2".to_string(), id: ElementId(8) }, ReplacePlaceholder { path: &[0], m: 1 }, ReplaceWith { id: ElementId(4), m: 3 } ] ); } #[test] fn list_shrink_multiroot() { let mut dom = VirtualDom::new(|| { rsx! { div { for i in 0..generation() { div { "{i}" } div { "{i}" } } } } }); assert_eq!( dom.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, CreatePlaceholder { id: ElementId(2,) }, ReplacePlaceholder { path: &[0,], m: 1 }, AppendChildren { id: ElementId(0), m: 1 } ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(3) }, CreateTextNode { value: "0".to_string(), id: ElementId(4) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 1, id: ElementId(5) }, CreateTextNode { value: "0".to_string(), id: ElementId(6) }, ReplacePlaceholder { path: &[0], m: 1 }, ReplaceWith { id: ElementId(2), m: 2 } ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2) }, CreateTextNode { value: "1".to_string(), id: ElementId(7) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 1, id: ElementId(8) }, CreateTextNode { value: "1".to_string(), id: ElementId(9) }, ReplacePlaceholder { path: &[0], m: 1 }, InsertAfter { id: ElementId(5), m: 2 } ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(10) }, CreateTextNode { value: "2".to_string(), id: ElementId(11) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 1, id: ElementId(12) }, CreateTextNode { value: "2".to_string(), id: ElementId(13) }, ReplacePlaceholder { path: &[0], m: 1 }, InsertAfter { id: ElementId(8), m: 2 } ] ); } #[test] fn removes_one_by_one_multiroot() { let mut dom = VirtualDom::new(|| { let gen = 3 - generation() % 4; rsx! { div { {(0..gen).map(|i| rsx! { div { "{i}" } div { "{i}" } })} } } }); // load the div and then assign the empty fragment as a placeholder assert_eq!( dom.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1) }, // LoadTemplate { index: 0, id: ElementId(2) }, CreateTextNode { value: "0".to_string(), id: ElementId(3) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 1, id: ElementId(4) }, CreateTextNode { value: "0".to_string(), id: ElementId(5) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 0, id: ElementId(6) }, CreateTextNode { value: "1".to_string(), id: ElementId(7) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 1, id: ElementId(8) }, CreateTextNode { value: "1".to_string(), id: ElementId(9) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 0, id: ElementId(10) }, CreateTextNode { value: "2".to_string(), id: ElementId(11) }, ReplacePlaceholder { path: &[0], m: 1 }, LoadTemplate { index: 1, id: ElementId(12) }, CreateTextNode { value: "2".to_string(), id: ElementId(13) }, ReplacePlaceholder { path: &[0], m: 1 }, ReplacePlaceholder { path: &[0], m: 6 }, AppendChildren { id: ElementId(0), m: 1 } ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [Remove { id: ElementId(10) }, Remove { id: ElementId(12) }] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [Remove { id: ElementId(6) }, Remove { id: ElementId(8) }] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ CreatePlaceholder { id: ElementId(8) }, Remove { id: ElementId(2) }, ReplaceWith { id: ElementId(4), m: 1 } ] ); } #[test] fn two_equal_fragments_are_equal_static() { let mut dom = VirtualDom::new(|| { rsx! { for _ in 0..5 { div { "hello" } } } }); dom.rebuild(&mut dioxus_core::NoOpMutations); assert!(dom.render_immediate_to_vec().edits.is_empty()); } #[test] fn two_equal_fragments_are_equal() { let mut dom = VirtualDom::new(|| { rsx! { for i in 0..5 { div { "hello {i}" } } } }); dom.rebuild(&mut dioxus_core::NoOpMutations); assert!(dom.render_immediate_to_vec().edits.is_empty()); } #[test] fn remove_many() { let mut dom = VirtualDom::new(|| { let num = match generation() % 3 { 0 => 0, 1 => 1, 2 => 5, _ => unreachable!(), }; rsx! { for i in 0..num { div { "hello {i}" } } } }); // len = 0 { let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ CreatePlaceholder { id: ElementId(1,) }, AppendChildren { id: ElementId(0), m: 1 }, ] ); } // len = 1 { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(2,) }, CreateTextNode { value: "hello 0".to_string(), id: ElementId(3,) }, ReplacePlaceholder { path: &[0,], m: 1 }, ReplaceWith { id: ElementId(1,), m: 1 }, ] ); } // len = 5 { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, CreateTextNode { value: "hello 1".to_string(), id: ElementId(4,) }, ReplacePlaceholder { path: &[0,], m: 1 }, LoadTemplate { index: 0, id: ElementId(5,) }, CreateTextNode { value: "hello 2".to_string(), id: ElementId(6,) }, ReplacePlaceholder { path: &[0,], m: 1 }, LoadTemplate { index: 0, id: ElementId(7,) }, CreateTextNode { value: "hello 3".to_string(), id: ElementId(8,) }, ReplacePlaceholder { path: &[0,], m: 1 }, LoadTemplate { index: 0, id: ElementId(9,) }, CreateTextNode { value: "hello 4".to_string(), id: ElementId(10,) }, ReplacePlaceholder { path: &[0,], m: 1 }, InsertAfter { id: ElementId(2,), m: 4 }, ] ); } // len = 0 { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!(edits.edits[0], CreatePlaceholder { id: ElementId(11,) }); let removed = edits.edits[1..5] .iter() .map(|edit| match edit { Mutation::Remove { id } => *id, _ => panic!("Expected remove"), }) .collect::<HashSet<_>>(); assert_eq!( removed, [ElementId(7), ElementId(5), ElementId(2), ElementId(1)] .into_iter() .collect::<HashSet<_>>() ); assert_eq!(edits.edits[5..], [ReplaceWith { id: ElementId(9,), m: 1 },]); } // len = 1 { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(9,) }, CreateTextNode { value: "hello 0".to_string(), id: ElementId(10,) }, ReplacePlaceholder { path: &[0,], m: 1 }, ReplaceWith { id: ElementId(11,), m: 1 }, ] ) } } #[test] fn replace_and_add_items() { let mut dom = VirtualDom::new(|| { let items = (0..generation()).map(|_| { if generation() % 2 == 0 { VNode::empty() } else { rsx! { li { "Fizz" } } } }); rsx! { ul { {items} } } }); // The list starts empty with a placeholder { let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, CreatePlaceholder { id: ElementId(2,) }, ReplacePlaceholder { path: &[0], m: 1 }, AppendChildren { id: ElementId(0), m: 1 }, ] ); } // Rerendering adds an a static template { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(3,) }, ReplaceWith { id: ElementId(2,), m: 1 }, ] ); } // Rerendering replaces the old node with a placeholder and adds a new placeholder { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ CreatePlaceholder { id: ElementId(2,) }, InsertAfter { id: ElementId(3,), m: 1 }, CreatePlaceholder { id: ElementId(4,) }, ReplaceWith { id: ElementId(3,), m: 1 }, ] ); } // Rerendering replaces both placeholders with the static nodes and add a new static node { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(3,) }, InsertAfter { id: ElementId(2,), m: 1 }, LoadTemplate { index: 0, id: ElementId(5,) }, ReplaceWith { id: ElementId(4,), m: 1 }, LoadTemplate { index: 0, id: ElementId(4,) }, ReplaceWith { id: ElementId(2,), m: 1 }, ] ); } } // Simplified regression test for https://github.com/DioxusLabs/dioxus/issues/4924 #[test] fn nested_unkeyed_lists() { let mut dom = VirtualDom::new(|| { let content = if generation() % 2 == 0 { vec!["5\n6"] } else { vec!["1\n2", "3\n4"] }; rsx! { for one in &content { for line in one.lines() { p { "{line}" } } } } }); // The list starts with one placeholder { let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ // load the p tag template LoadTemplate { index: 0, id: ElementId(1) }, // Create the first text node CreateTextNode { value: "5".into(), id: ElementId(2) }, // Replace the placeholder inside the p tag with the text node ReplacePlaceholder { path: &[0], m: 1 }, // load the p tag template LoadTemplate { index: 0, id: ElementId(3) }, // Create the second text node CreateTextNode { value: "6".into(), id: ElementId(4) }, // Replace the placeholder inside the p tag with the text node ReplacePlaceholder { path: &[0], m: 1 }, // Add the text nodes to the root node AppendChildren { id: ElementId(0), m: 2 } ] ); } // DOM state: // <pre> # Id 1 for if statement // <p> # Id 2 // "5" # Id 3 // <p> # Id 4 // "6" # Id 5 // // The diffing engine should add two new elements to the end and modify the first two elements in place { dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ // load the p tag template LoadTemplate { index: 0, id: ElementId(5) }, // Create the third text node CreateTextNode { value: "3".into(), id: ElementId(6) }, // Replace the placeholder inside the p tag with the text node ReplacePlaceholder { path: &[0], m: 1 }, // load the p tag template LoadTemplate { index: 0, id: ElementId(7) }, // Create the fourth text node CreateTextNode { value: "4".into(), id: ElementId(8) }, // Replace the placeholder inside the p tag with the text node ReplacePlaceholder { path: &[0], m: 1 }, // Insert the text nodes after the second p tag InsertAfter { id: ElementId(3), m: 2 }, // Set the first text node to "1" SetText { value: "1".into(), id: ElementId(2) }, // Set the second text node to "2" SetText { value: "2".into(), id: ElementId(4) } ] ); } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/attr_cleanup.rs
packages/core/tests/attr_cleanup.rs
//! dynamic attributes in dioxus necessitate an allocated node ID. //! //! This tests to ensure we clean it up use dioxus::prelude::*; use dioxus_core::{generation, ElementId, IntoAttributeValue, Mutation::*}; #[test] fn attrs_cycle() { tracing_subscriber::fmt::init(); let mut dom = VirtualDom::new(|| { let id = generation(); match id % 2 { 0 => rsx! { div {} }, 1 => rsx! { div { h1 { class: "{id}", id: "{id}" } } }, _ => unreachable!(), } }); assert_eq!( dom.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, AppendChildren { m: 1, id: ElementId(0) }, ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2,) }, AssignId { path: &[0,], id: ElementId(3,) }, SetAttribute { name: "class", value: "1".into_value(), id: ElementId(3,), ns: None }, SetAttribute { name: "id", value: "1".into_value(), id: ElementId(3,), ns: None }, ReplaceWith { id: ElementId(1,), m: 1 }, ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1) }, ReplaceWith { id: ElementId(2), m: 1 } ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2) }, AssignId { path: &[0], id: ElementId(3) }, SetAttribute { name: "class", value: dioxus_core::AttributeValue::Text("3".to_string()), id: ElementId(3), ns: None }, SetAttribute { name: "id", value: dioxus_core::AttributeValue::Text("3".to_string()), id: ElementId(3), ns: None }, ReplaceWith { id: ElementId(1), m: 1 } ] ); // we take the node taken by attributes since we reused it dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1) }, ReplaceWith { id: ElementId(2), m: 1 } ] ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/many_roots.rs
packages/core/tests/many_roots.rs
#![allow(non_snake_case)] use dioxus::dioxus_core::Mutation::*; use dioxus::prelude::*; use dioxus_core::{AttributeValue, ElementId}; use pretty_assertions::assert_eq; /// Should push the text node onto the stack and modify it /// Regression test for https://github.com/DioxusLabs/dioxus/issues/2809 and https://github.com/DioxusLabs/dioxus/issues/3055 #[test] fn many_roots() { fn app() -> Element { let width = "100%"; rsx! { div { MyNav {} MyOutlet {} div { // We need to make sure that dynamic attributes are set before the nodes before them are expanded // If they are set after, then the paths are incorrect width, } } } } fn MyNav() -> Element { rsx!( div { "trailing nav" } div { "whhhhh"} div { "bhhhh" } ) } fn MyOutlet() -> Element { rsx!( div { "homepage 1" } ) } let mut dom = VirtualDom::new(app); let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ // load the div {} container LoadTemplate { index: 0, id: ElementId(1) }, // Set the width attribute first AssignId { path: &[2], id: ElementId(2,) }, SetAttribute { name: "width", ns: Some("style",), value: AttributeValue::Text("100%".to_string()), id: ElementId(2,), }, // Load MyOutlet next LoadTemplate { index: 0, id: ElementId(3) }, ReplacePlaceholder { path: &[1], m: 1 }, // Then MyNav LoadTemplate { index: 0, id: ElementId(4) }, LoadTemplate { index: 1, id: ElementId(5) }, LoadTemplate { index: 2, id: ElementId(6) }, ReplacePlaceholder { path: &[0], m: 3 }, // Then mount the div to the dom AppendChildren { m: 1, id: ElementId(0) }, ] ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/lifecycle.rs
packages/core/tests/lifecycle.rs
#![allow(unused, non_upper_case_globals)] #![allow(non_snake_case)] //! Tests for the lifecycle of components. use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::html::SerializedHtmlEventConverter; use dioxus::prelude::*; use std::any::Any; use std::rc::Rc; use std::sync::{Arc, Mutex}; type Shared<T> = Arc<Mutex<T>>; #[test] fn manual_diffing() { #[derive(Clone)] struct AppProps { value: Shared<&'static str>, } fn app(cx: AppProps) -> Element { let val = cx.value.lock().unwrap(); rsx! { div { "{val}" } } }; let value = Arc::new(Mutex::new("Hello")); let mut dom = VirtualDom::new_with_props(app, AppProps { value: value.clone() }); dom.rebuild(&mut dioxus_core::NoOpMutations); *value.lock().unwrap() = "goodbye"; assert_eq!( dom.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(3) }, CreateTextNode { value: "goodbye".to_string(), id: ElementId(4) }, ReplacePlaceholder { path: &[0], m: 1 }, AppendChildren { m: 1, id: ElementId(0) } ] ); } #[test] fn events_generate() { set_event_converter(Box::new(SerializedHtmlEventConverter)); fn app() -> Element { let mut count = use_signal(|| 0); match count() { 0 => rsx! { div { onclick: move |_| count += 1, div { "nested" } "Click me!" } }, _ => VNode::empty(), } }; let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); let event = Event::new( Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())) as Rc<dyn Any>, true, ); dom.runtime().handle_event("click", event, ElementId(1)); dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [ CreatePlaceholder { id: ElementId(2) }, ReplaceWith { id: ElementId(1), m: 1 } ] ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/diff_keyed_list.rs
packages/core/tests/diff_keyed_list.rs
//! Diffing Tests //! //! These tests only verify that the diffing algorithm works properly for single components. //! //! It does not validated that component lifecycles work properly. This is done in another test file. use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::prelude::*; use dioxus_core::generation; /// Should result in moves, but not removals or additions #[test] fn keyed_diffing_out_of_order() { let mut dom = VirtualDom::new(|| { let order = match generation() % 2 { 0 => &[0, 1, 2, 3, /**/ 4, 5, 6, /**/ 7, 8, 9], 1 => &[0, 1, 2, 3, /**/ 6, 4, 5, /**/ 7, 8, 9], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); { assert_eq!( dom.rebuild_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, LoadTemplate { index: 0, id: ElementId(2,) }, LoadTemplate { index: 0, id: ElementId(3,) }, LoadTemplate { index: 0, id: ElementId(4,) }, LoadTemplate { index: 0, id: ElementId(5,) }, LoadTemplate { index: 0, id: ElementId(6,) }, LoadTemplate { index: 0, id: ElementId(7,) }, LoadTemplate { index: 0, id: ElementId(8,) }, LoadTemplate { index: 0, id: ElementId(9,) }, LoadTemplate { index: 0, id: ElementId(10,) }, AppendChildren { m: 10, id: ElementId(0) }, ] ); } dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ PushRoot { id: ElementId(7,) }, InsertBefore { id: ElementId(5,), m: 1 }, ] ); } /// Should result in moves only #[test] fn keyed_diffing_out_of_order_adds() { let mut dom = VirtualDom::new(|| { let order = match generation() % 2 { 0 => &[/**/ 4, 5, 6, 7, 8 /**/], 1 => &[/**/ 8, 7, 4, 5, 6 /**/], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ PushRoot { id: ElementId(5,) }, PushRoot { id: ElementId(4,) }, InsertBefore { id: ElementId(1,), m: 2 }, ] ); } /// Should result in moves only #[test] fn keyed_diffing_out_of_order_adds_3() { let mut dom = VirtualDom::new(|| { let order = match generation() % 2 { 0 => &[/**/ 4, 5, 6, 7, 8 /**/], 1 => &[/**/ 4, 8, 7, 5, 6 /**/], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ PushRoot { id: ElementId(5,) }, PushRoot { id: ElementId(4,) }, InsertBefore { id: ElementId(2,), m: 2 }, ] ); } /// Should result in moves only #[test] fn keyed_diffing_out_of_order_adds_4() { let mut dom = VirtualDom::new(|| { let order = match generation() % 2 { 0 => &[/**/ 4, 5, 6, 7, 8 /**/], 1 => &[/**/ 4, 5, 8, 7, 6 /**/], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ PushRoot { id: ElementId(5,) }, PushRoot { id: ElementId(4,) }, InsertBefore { id: ElementId(3,), m: 2 }, ] ); } /// Should result in moves only #[test] fn keyed_diffing_out_of_order_adds_5() { let mut dom = VirtualDom::new(|| { let order = match generation() % 2 { 0 => &[/**/ 4, 5, 6, 7, 8 /**/], 1 => &[/**/ 4, 5, 6, 8, 7 /**/], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ PushRoot { id: ElementId(5,) }, InsertBefore { id: ElementId(4,), m: 1 }, ] ); } /// Should result in moves only #[test] fn keyed_diffing_additions() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[/**/ 4, 5, 6, 7, 8 /**/], 1 => &[/**/ 4, 5, 6, 7, 8, 9, 10 /**/], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(6) }, LoadTemplate { index: 0, id: ElementId(7) }, InsertAfter { id: ElementId(5), m: 2 } ] ); } #[test] fn keyed_diffing_additions_and_moves_on_ends() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[/**/ 4, 5, 6, 7 /**/], 1 => &[/**/ 7, 4, 5, 6, 11, 12 /**/], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ // create 11, 12 LoadTemplate { index: 0, id: ElementId(5) }, LoadTemplate { index: 0, id: ElementId(6) }, InsertAfter { id: ElementId(3), m: 2 }, // move 7 to the front PushRoot { id: ElementId(4) }, InsertBefore { id: ElementId(1), m: 1 } ] ); } #[test] fn keyed_diffing_additions_and_moves_in_middle() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[/**/ 1, 2, 3, 4 /**/], 1 => &[/**/ 4, 1, 7, 8, 2, 5, 6, 3 /**/], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); // LIS: 4, 5, 6 dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ // create 5, 6 LoadTemplate { index: 0, id: ElementId(5) }, LoadTemplate { index: 0, id: ElementId(6) }, InsertBefore { id: ElementId(3), m: 2 }, // create 7, 8 LoadTemplate { index: 0, id: ElementId(7) }, LoadTemplate { index: 0, id: ElementId(8) }, InsertBefore { id: ElementId(2), m: 2 }, // move 7 PushRoot { id: ElementId(4) }, InsertBefore { id: ElementId(1), m: 1 } ] ); } #[test] fn controlled_keyed_diffing_out_of_order() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[4, 5, 6, 7], 1 => &[0, 5, 9, 6, 4], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); // LIS: 5, 6 dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ // remove 7 Remove { id: ElementId(4,) }, // move 4 to after 6 PushRoot { id: ElementId(1) }, InsertAfter { id: ElementId(3,), m: 1 }, // create 9 and insert before 6 LoadTemplate { index: 0, id: ElementId(4) }, InsertBefore { id: ElementId(3,), m: 1 }, // create 0 and insert before 5 LoadTemplate { index: 0, id: ElementId(5) }, InsertBefore { id: ElementId(2,), m: 1 }, ] ); } #[test] fn controlled_keyed_diffing_out_of_order_max_test() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[0, 1, 2, 3, 4], 1 => &[3, 0, 1, 10, 2], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ Remove { id: ElementId(5,) }, LoadTemplate { index: 0, id: ElementId(5) }, InsertBefore { id: ElementId(3,), m: 1 }, PushRoot { id: ElementId(4) }, InsertBefore { id: ElementId(1,), m: 1 }, ] ); } // noticed some weird behavior in the desktop interpreter // just making sure it doesnt happen in the core implementation #[test] fn remove_list() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[9, 8, 7, 6, 5], 1 => &[9, 8], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ Remove { id: ElementId(5) }, Remove { id: ElementId(4) }, Remove { id: ElementId(3) }, ] ); } #[test] fn no_common_keys() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[1, 2, 3], 1 => &[4, 5, 6], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(4) }, LoadTemplate { index: 0, id: ElementId(5) }, LoadTemplate { index: 0, id: ElementId(6) }, Remove { id: ElementId(3) }, Remove { id: ElementId(2) }, ReplaceWith { id: ElementId(1), m: 3 } ] ); } #[test] fn perfect_reverse() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[1, 2, 3, 4, 5, 6, 7, 8], 1 => &[9, 8, 7, 6, 5, 4, 3, 2, 1, 0], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec().edits; assert_eq!( edits, [ LoadTemplate { index: 0, id: ElementId(9,) }, InsertAfter { id: ElementId(1,), m: 1 }, LoadTemplate { index: 0, id: ElementId(10,) }, PushRoot { id: ElementId(8,) }, PushRoot { id: ElementId(7,) }, PushRoot { id: ElementId(6,) }, PushRoot { id: ElementId(5,) }, PushRoot { id: ElementId(4,) }, PushRoot { id: ElementId(3,) }, PushRoot { id: ElementId(2,) }, InsertBefore { id: ElementId(1,), m: 8 }, ] ) } #[test] fn old_middle_empty_left_pivot() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[/* */ /* */ 6, 7, 8, 9, 10], 1 => &[/* */ 4, 5, /* */ 6, 7, 8, 9, 10], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec().edits; assert_eq!( edits, [ LoadTemplate { index: 0, id: ElementId(6,) }, LoadTemplate { index: 0, id: ElementId(7,) }, InsertBefore { id: ElementId(1,), m: 2 }, ] ) } #[test] fn old_middle_empty_right_pivot() { let mut dom = VirtualDom::new(|| { let order: &[_] = match generation() % 2 { 0 => &[1, 2, 3, /* */ 6, 7, 8, 9, 10], 1 => &[1, 2, 3, /* */ 4, 5, 6, 7, 8, 9, 10 /* */], // 0 => &[/* */ 6, 7, 8, 9, 10], // 1 => &[/* */ 6, 7, 8, 9, 10, /* */ 4, 5], _ => unreachable!(), }; rsx!({ order.iter().map(|i| rsx!(div { key: "{i}" })) }) }); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); let edits = dom.render_immediate_to_vec().edits; assert_eq!( edits, [ LoadTemplate { index: 0, id: ElementId(9) }, LoadTemplate { index: 0, id: ElementId(10) }, InsertBefore { id: ElementId(4), m: 2 }, ] ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/create_dom.rs
packages/core/tests/create_dom.rs
#![allow(unused, non_upper_case_globals, non_snake_case)] //! Prove that the dom works normally through virtualdom methods. //! //! This methods all use "rebuild_to_vec" which completely bypasses the scheduler. //! Hard rebuild_to_vecs don't consume any events from the event queue. use dioxus::dioxus_core::Mutation::*; use dioxus::prelude::*; use dioxus_core::ElementId; #[test] fn test_original_diff() { let mut dom = VirtualDom::new(|| { rsx! { div { div { "Hello, world!" } } } }); let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ // add to root LoadTemplate { index: 0, id: ElementId(1) }, AppendChildren { m: 1, id: ElementId(0) } ] ) } #[test] fn create() { let mut dom = VirtualDom::new(|| { rsx! { div { div { "Hello, world!" div { div { Fragment { "hello""world" } } } } } } }); let _edits = dom.rebuild_to_vec(); // todo: we don't test template mutations anymore since the templates are passed along // assert_eq!( // edits.templates, // [ // // create template // CreateElement { name: "div" }, // CreateElement { name: "div" }, // CreateStaticText { value: "Hello, world!" }, // CreateElement { name: "div" }, // CreateElement { name: "div" }, // CreateStaticPlaceholder {}, // AppendChildren { m: 1 }, // AppendChildren { m: 1 }, // AppendChildren { m: 2 }, // AppendChildren { m: 1 }, // SaveTemplate { m: 1 }, // // The fragment child template // CreateStaticText { value: "hello" }, // CreateStaticText { value: "world" }, // SaveTemplate { m: 2 }, // ] // ); } #[test] fn create_list() { let mut dom = VirtualDom::new(|| rsx! {{(0..3).map(|f| rsx!( div { "hello" } ))}}); let _edits = dom.rebuild_to_vec(); // note: we dont test template edits anymore // assert_eq!( // edits.templates, // [ // // create template // CreateElement { name: "div" }, // CreateStaticText { value: "hello" }, // AppendChildren { m: 1 }, // SaveTemplate { m: 1 } // ] // ); } #[test] fn create_simple() { let mut dom = VirtualDom::new(|| { rsx! { div {} div {} div {} div {} } }); let edits = dom.rebuild_to_vec(); // note: we dont test template edits anymore // assert_eq!( // edits.templates, // [ // // create template // CreateElement { name: "div" }, // CreateElement { name: "div" }, // CreateElement { name: "div" }, // CreateElement { name: "div" }, // // add to root // SaveTemplate { m: 4 } // ] // ); } #[test] fn create_components() { let mut dom = VirtualDom::new(|| { rsx! { Child { "abc1" } Child { "abc2" } Child { "abc3" } } }); #[derive(Props, Clone, PartialEq)] struct ChildProps { children: Element, } fn Child(cx: ChildProps) -> Element { rsx! { h1 {} div { {cx.children} } p {} } } let _edits = dom.rebuild_to_vec(); // todo: test this } #[test] fn anchors() { let mut dom = VirtualDom::new(|| { rsx! { if true { div { "hello" } } if false { div { "goodbye" } } } }); // note that the template under "false" doesn't show up since it's not loaded let edits = dom.rebuild_to_vec(); // note: we dont test template edits anymore // assert_eq!( // edits.templates, // [ // // create each template // CreateElement { name: "div" }, // CreateStaticText { value: "hello" }, // AppendChildren { m: 1 }, // SaveTemplate { m: 1, name: "template" }, // ] // ); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(1) }, CreatePlaceholder { id: ElementId(2) }, AppendChildren { m: 2, id: ElementId(0) } ] ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/use_drop.rs
packages/core/tests/use_drop.rs
//! Tests the use_drop hook use dioxus::dioxus_core::use_drop; use dioxus::prelude::*; use std::sync::{Arc, Mutex}; type Shared<T> = Arc<Mutex<T>>; #[derive(Clone, Props)] struct AppProps { render_child: Shared<bool>, drop_count: Shared<u32>, } impl PartialEq for AppProps { fn eq(&self, other: &Self) -> bool { Arc::ptr_eq(&self.drop_count, &other.drop_count) } } fn app(props: AppProps) -> Element { let render_child = props.render_child.clone(); let render_child = *render_child.lock().unwrap(); println!( "Rendering app component with render_child: {}", render_child ); rsx! { if render_child { child_component { drop_count: props.drop_count.clone(), render_child: props.render_child.clone() } } } } fn child_component(props: AppProps) -> Element { println!("Rendering child component"); use_drop(move || { println!("Child component is being dropped"); let mut count = props.drop_count.lock().unwrap(); *count += 1; }); rsx! {} } #[test] fn drop_runs() { let drop_count = Arc::new(Mutex::new(0)); let render_child = Arc::new(Mutex::new(true)); let mut dom = VirtualDom::new_with_props( app, AppProps { drop_count: drop_count.clone(), render_child: render_child.clone() }, ); dom.rebuild_in_place(); assert_eq!(*drop_count.lock().unwrap(), 0); *render_child.lock().unwrap() = false; dom.mark_dirty(ScopeId::APP); dom.render_immediate(&mut dioxus_core::NoOpMutations); assert_eq!(*drop_count.lock().unwrap(), 1); *render_child.lock().unwrap() = false; }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/create_fragments.rs
packages/core/tests/create_fragments.rs
//! Do we create fragments properly across complex boundaries? use dioxus::dioxus_core::Mutation::*; use dioxus::prelude::*; use dioxus_core::ElementId; #[test] fn empty_fragment_creates_nothing() { fn app() -> Element { rsx!({}) } let mut vdom = VirtualDom::new(app); let edits = vdom.rebuild_to_vec(); assert_eq!( edits.edits, [ CreatePlaceholder { id: ElementId(1) }, AppendChildren { id: ElementId(0), m: 1 } ] ); } #[test] fn root_fragments_work() { let mut vdom = VirtualDom::new(|| { rsx!( div { "hello" } div { "goodbye" } ) }); assert_eq!( vdom.rebuild_to_vec().edits.last().unwrap(), &AppendChildren { id: ElementId(0), m: 2 } ); } #[test] fn fragments_nested() { let mut vdom = VirtualDom::new(|| { rsx!( div { "hello" } div { "goodbye" } {rsx! { div { "hello" } div { "goodbye" } {rsx! { div { "hello" } div { "goodbye" } {rsx! { div { "hello" } div { "goodbye" } }} }} }} ) }); assert_eq!( vdom.rebuild_to_vec().edits.last().unwrap(), &AppendChildren { id: ElementId(0), m: 8 } ); } #[test] fn fragments_across_components() { fn app() -> Element { rsx! { demo_child {} demo_child {} demo_child {} demo_child {} } } fn demo_child() -> Element { let world = "world"; rsx! { "hellO!" {world} } } assert_eq!( VirtualDom::new(app).rebuild_to_vec().edits.last().unwrap(), &AppendChildren { id: ElementId(0), m: 8 } ); } #[test] fn list_fragments() { fn app() -> Element { rsx!( h1 { "hello" } {(0..6).map(|f| rsx!( span { "{f}" }))} ) } assert_eq!( VirtualDom::new(app).rebuild_to_vec().edits.last().unwrap(), &AppendChildren { id: ElementId(0), m: 7 } ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/conditional_formatted_attributes.rs
packages/core/tests/conditional_formatted_attributes.rs
use dioxus::prelude::*; /// Make sure that rsx! handles conditional attributes with one formatted branch correctly /// Regression test for https://github.com/DioxusLabs/dioxus/issues/2997 #[test] fn partially_formatted_conditional_attribute() { let width = "1px"; _ = rsx! { div { width: if true { "{width}" } else { "100px" } } }; // And make sure it works if one of those branches is an expression // Regression test for https://github.com/DioxusLabs/dioxus/issues/3146 let opt = "button"; _ = rsx! { input { type: if true { opt } else { "text" }, } input { type: if true { opt.to_string() } else { "text with" }, } input { type: if true { opt.to_string() } else { "text with {width}" }, } input { type: if true { opt.to_string() } else if true { "" } else { "text with {width}" }, } input { type: if true { "one" } else if true { "two" } else { "three" }, } input { type: if true { "one" } else if true { "two" } else if true { "three" } else { opt }, } input { type: if true { "one" } else if true { if false { "true" } else { "false" } } else { "three" }, } input { type: if true { "one".to_string() }, } input { type: if true { "one" }, } }; }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/cycle.rs
packages/core/tests/cycle.rs
use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::prelude::*; use dioxus_core::generation; /// As we clean up old templates, the ID for the node should cycle #[test] fn cycling_elements() { let mut dom = VirtualDom::new(|| match generation() % 2 { 0 => rsx! { div { "wasd" } }, 1 => rsx! { div { "abcd" } }, _ => unreachable!(), }); { let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, AppendChildren { m: 1, id: ElementId(0) }, ] ); } dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2,) }, ReplaceWith { id: ElementId(1,), m: 1 }, ] ); // notice that the IDs cycle back to ElementId(1), preserving a minimal memory footprint dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, ReplaceWith { id: ElementId(2,), m: 1 }, ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2,) }, ReplaceWith { id: ElementId(1,), m: 1 }, ] ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/miri_full_app.rs
packages/core/tests/miri_full_app.rs
use dioxus::prelude::*; use dioxus_core::ElementId; use dioxus_elements::SerializedHtmlEventConverter; use std::{any::Any, rc::Rc}; #[test] fn miri_rollover() { set_event_converter(Box::new(SerializedHtmlEventConverter)); let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); for _ in 0..3 { let event = Event::new( Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())) as Rc<dyn Any>, true, ); dom.runtime().handle_event("click", event, ElementId(2)); dom.process_events(); _ = dom.render_immediate_to_vec(); } } fn app() -> Element { let mut idx = use_signal(|| 0); let onhover = |_| println!("go!"); rsx! { div { button { onclick: move |_| { idx += 1; println!("Clicked"); }, "+" } button { onclick: move |_| idx -= 1, "-" } ul { {(0..idx()).map(|i| rsx! { ChildExample { i: i, onhover: onhover } })} } } } } #[component] fn ChildExample(i: i32, onhover: EventHandler<MouseEvent>) -> Element { rsx! { li { onmouseover: move |e| onhover.call(e), "{i}" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/task.rs
packages/core/tests/task.rs
//! Verify that tasks get polled by the virtualdom properly, and that we escape wait_for_work safely use std::{sync::atomic::AtomicUsize, time::Duration}; use dioxus::prelude::*; use dioxus_core::{generation, needs_update, spawn_forever}; async fn run_vdom(app: fn() -> Element) { let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); tokio::select! { _ = dom.wait_for_work() => {} _ = tokio::time::sleep(Duration::from_millis(500)) => {} }; } #[tokio::test] async fn running_async() { static POLL_COUNT: AtomicUsize = AtomicUsize::new(0); fn app() -> Element { use_hook(|| { spawn(async { for x in 0..10 { tokio::time::sleep(Duration::from_micros(50)).await; POLL_COUNT.fetch_add(x, std::sync::atomic::Ordering::Relaxed); } }); spawn(async { for x in 0..10 { tokio::time::sleep(Duration::from_micros(25)).await; POLL_COUNT.fetch_add(x * 2, std::sync::atomic::Ordering::Relaxed); } }); }); rsx!({}) } run_vdom(app).await; // By the time the tasks are finished, we should've accumulated ticks from two tasks // Be warned that by setting the delay to too short, tokio might not schedule in the tasks assert_eq!( POLL_COUNT.fetch_add(0, std::sync::atomic::Ordering::Relaxed), 135 ); } #[tokio::test] async fn spawn_forever_persists() { use std::sync::atomic::Ordering; static POLL_COUNT: AtomicUsize = AtomicUsize::new(0); fn app() -> Element { if generation() > 0 { rsx!(div {}) } else { needs_update(); rsx!(Child {}) } } #[component] fn Child() -> Element { spawn_forever(async move { for _ in 0..10 { POLL_COUNT.fetch_add(1, Ordering::Relaxed); tokio::time::sleep(Duration::from_millis(50)).await; } }); rsx!(div {}) } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.render_immediate(&mut dioxus_core::NoOpMutations); tokio::select! { _ = dom.wait_for_work() => {} // We intentionally wait a bit longer than 50ms*10 to make sure the test has time to finish // Without the extra time, the test can fail on windows _ = tokio::time::sleep(Duration::from_millis(1000)) => {} }; // By the time the tasks are finished, we should've accumulated ticks from two tasks // Be warned that by setting the delay to too short, tokio might not schedule in the tasks assert_eq!(POLL_COUNT.load(Ordering::Relaxed), 10); } /// Prove that yield_now doesn't cause a deadlock #[tokio::test] async fn yield_now_works() { thread_local! { static SEQUENCE: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) }; } fn app() -> Element { // these two tasks should yield to eachother use_hook(|| { spawn(async move { for _ in 0..10 { tokio::task::yield_now().await; SEQUENCE.with(|s| s.borrow_mut().push(1)); } }) }); use_hook(|| { spawn(async move { for _ in 0..10 { tokio::task::yield_now().await; SEQUENCE.with(|s| s.borrow_mut().push(2)); } }) }); rsx!({}) } run_vdom(app).await; SEQUENCE.with(|s| assert_eq!(s.borrow().len(), 20)); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/tracing.rs
packages/core/tests/tracing.rs
use dioxus::html::SerializedHtmlEventConverter; use dioxus::prelude::*; use dioxus_core::{ElementId, Event}; use std::{any::Any, rc::Rc}; use tracing_fluent_assertions::{AssertionRegistry, AssertionsLayer}; use tracing_subscriber::{layer::SubscriberExt, Registry}; #[test] fn basic_tracing() { // setup tracing let assertion_registry = AssertionRegistry::default(); let base_subscriber = Registry::default(); // log to standard out for testing let std_out_log = tracing_subscriber::fmt::layer().pretty(); let subscriber = base_subscriber .with(std_out_log) .with(AssertionsLayer::new(&assertion_registry)); tracing::subscriber::set_global_default(subscriber).unwrap(); let new_virtual_dom = assertion_registry .build() .with_name("VirtualDom::new") .was_created() .was_entered_exactly(1) .was_closed() .finalize(); let edited_virtual_dom = assertion_registry .build() .with_name("VirtualDom::rebuild") .was_created() .was_entered_exactly(1) .was_closed() .finalize(); set_event_converter(Box::new(SerializedHtmlEventConverter)); let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); new_virtual_dom.assert(); edited_virtual_dom.assert(); for _ in 0..3 { let event = Event::new( Rc::new(PlatformEventData::new(Box::<SerializedMouseData>::default())) as Rc<dyn Any>, true, ); dom.runtime().handle_event("click", event, ElementId(2)); dom.process_events(); _ = dom.render_immediate_to_vec(); } } fn app() -> Element { let mut idx = use_signal(|| 0); let onhover = |_| println!("go!"); rsx! { div { button { onclick: move |_| { idx += 1; println!("Clicked"); }, "+" } button { onclick: move |_| idx -= 1, "-" } ul { {(0..idx()).map(|i| rsx! { ChildExample { i: i, onhover: onhover } })} } } } } #[component] fn ChildExample(i: i32, onhover: EventHandler<MouseEvent>) -> Element { rsx! { li { onmouseover: move |e| onhover.call(e), "{i}" } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/hotreloading.rs
packages/core/tests/hotreloading.rs
//! It should be possible to swap out templates at runtime, enabling hotreloading
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/context_api.rs
packages/core/tests/context_api.rs
use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::prelude::*; use dioxus_core::{consume_context_from_scope, generation}; #[test] fn state_shares() { fn app() -> Element { provide_context(generation() as i32); rsx!(child_1 {}) } fn child_1() -> Element { rsx!(child_2 {}) } fn child_2() -> Element { let value = consume_context::<i32>(); rsx!("Value is {value}") } let mut dom = VirtualDom::new(app); assert_eq!( dom.rebuild_to_vec().edits, [ CreateTextNode { value: "Value is 0".to_string(), id: ElementId(1,) }, AppendChildren { m: 1, id: ElementId(0) }, ] ); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); dom.in_runtime(|| { assert_eq!(consume_context_from_scope::<i32>(ScopeId::APP).unwrap(), 1); }); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); dom.in_runtime(|| { assert_eq!(consume_context_from_scope::<i32>(ScopeId::APP).unwrap(), 2); }); dom.mark_dirty(ScopeId(ScopeId::APP.0 + 2)); assert_eq!( dom.render_immediate_to_vec().edits, [SetText { value: "Value is 2".to_string(), id: ElementId(1,) },] ); dom.mark_dirty(ScopeId::APP); dom.mark_dirty(ScopeId(ScopeId::APP.0 + 2)); let edits = dom.render_immediate_to_vec(); assert_eq!( edits.edits, [SetText { value: "Value is 3".to_string(), id: ElementId(1,) },] ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/miri_simple.rs
packages/core/tests/miri_simple.rs
use dioxus::prelude::*; use dioxus_core::generation; #[test] fn app_drops() { fn app() -> Element { rsx! { div {} } } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); } #[test] fn hooks_drop() { fn app() -> Element { use_hook(|| String::from("asd")); use_hook(|| String::from("asd")); use_hook(|| String::from("asd")); use_hook(|| String::from("asd")); rsx! { div {} } } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); } #[test] fn contexts_drop() { fn app() -> Element { provide_context(String::from("asd")); rsx! { div { ChildComp {} } } } #[allow(non_snake_case)] fn ChildComp() -> Element { let el = consume_context::<String>(); rsx! { div { "hello {el}" } } } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); } #[test] fn tasks_drop() { fn app() -> Element { spawn(async { // tokio::time::sleep(std::time::Duration::from_millis(100000)).await; }); rsx! { div {} } } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); } #[test] fn root_props_drop() { #[derive(Clone)] struct RootProps(String); let mut dom = VirtualDom::new_with_props( |cx: RootProps| rsx!( div { "{cx.0}" } ), RootProps("asdasd".to_string()), ); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); } #[test] fn diffing_drops_old() { fn app() -> Element { rsx! { div { match generation() % 2 { 0 => rsx!( ChildComp1 { name: "asdasd".to_string() }), 1 => rsx!( ChildComp2 { name: "asdasd".to_string() }), _ => unreachable!() } } } } #[component] fn ChildComp1(name: String) -> Element { rsx! {"Hello {name}"} } #[component] fn ChildComp2(name: String) -> Element { rsx! {"Goodbye {name}"} } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); } #[test] fn hooks_drop_before_contexts() { fn app() -> Element { provide_context(123i32); use_hook(|| { #[derive(Clone)] struct ReadsContextOnDrop; impl Drop for ReadsContextOnDrop { fn drop(&mut self) { assert_eq!(123, consume_context::<i32>()); } } ReadsContextOnDrop }); rsx! { div {} } } let mut dom = VirtualDom::new(app); dom.rebuild(&mut dioxus_core::NoOpMutations); dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/attributes_pass.rs
packages/core/tests/attributes_pass.rs
use dioxus::prelude::*; use dioxus_core::TemplateNode; /// Make sure that rsx! is parsing templates and their attributes properly #[test] fn attributes_pass_properly() { let h = rsx! { circle { cx: 50, cy: 50, r: 40, stroke: "green", fill: "yellow" } }; let o = h.unwrap(); let template = &o.template; assert_eq!(template.attr_paths.len(), 3); let _circle = template.roots[0]; let TemplateNode::Element { attrs, tag, namespace, children } = _circle else { panic!("Expected an element"); }; assert_eq!(tag, "circle"); assert_eq!(namespace, Some("http://www.w3.org/2000/svg")); assert_eq!(children.len(), 0); assert_eq!(attrs.len(), 5); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/diff_component.rs
packages/core/tests/diff_component.rs
use dioxus::dioxus_core::{ElementId, Mutation::*}; use dioxus::prelude::*; use pretty_assertions::assert_eq; /// When returning sets of components, we do a light diff of the contents to preserve some react-like functionality /// /// This means that nav_bar should never get re-created and that we should only be swapping out /// different pointers #[test] fn component_swap() { // Check that templates with the same structure are deduplicated at compile time // If they are not, this test will fail because it is being run in debug mode where templates are not deduped let dynamic = 0; let template_1 = rsx! { "{dynamic}" }; let template_2 = rsx! { "{dynamic}" }; if template_1.unwrap().template != template_2.unwrap().template { return; } fn app() -> Element { let mut render_phase = use_signal(|| 0); render_phase += 1; match render_phase() { 0 => rsx! { nav_bar {} dash_board {} }, 1 => rsx! { nav_bar {} dash_results {} }, 2 => rsx! { nav_bar {} dash_board {} }, 3 => rsx! { nav_bar {} dash_results {} }, 4 => rsx! { nav_bar {} dash_board {} }, _ => rsx!("blah"), } } fn nav_bar() -> Element { rsx! { h1 { "NavBar" for _ in 0..3 { nav_link {} } } } } fn nav_link() -> Element { rsx!( h1 { "nav_link" } ) } fn dash_board() -> Element { rsx!( div { "dashboard" } ) } fn dash_results() -> Element { rsx!( div { "results" } ) } let mut dom = VirtualDom::new(app); { let edits = dom.rebuild_to_vec(); assert_eq!( edits.edits, [ LoadTemplate { index: 0, id: ElementId(1) }, LoadTemplate { index: 0, id: ElementId(2) }, LoadTemplate { index: 0, id: ElementId(3) }, LoadTemplate { index: 0, id: ElementId(4) }, ReplacePlaceholder { path: &[1], m: 3 }, LoadTemplate { index: 0, id: ElementId(5) }, AppendChildren { m: 2, id: ElementId(0) } ] ); } dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(6) }, ReplaceWith { id: ElementId(5), m: 1 } ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(5) }, ReplaceWith { id: ElementId(6), m: 1 } ] ); dom.mark_dirty(ScopeId::APP); assert_eq!( dom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(6) }, ReplaceWith { id: ElementId(5), m: 1 } ] ); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/diff_element.rs
packages/core/tests/diff_element.rs
use dioxus::dioxus_core::Mutation::*; use dioxus::dioxus_core::{AttributeValue, ElementId, NoOpMutations}; use dioxus::prelude::*; use dioxus_core::generation; #[test] fn text_diff() { fn app() -> Element { let gen = generation(); rsx!( h1 { "hello {gen}" } ) } let mut vdom = VirtualDom::new(app); vdom.rebuild(&mut NoOpMutations); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [SetText { value: "hello 1".to_string(), id: ElementId(2) }] ); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [SetText { value: "hello 2".to_string(), id: ElementId(2) }] ); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [SetText { value: "hello 3".to_string(), id: ElementId(2) }] ); } #[test] fn element_swap() { fn app() -> Element { let gen = generation(); match gen % 2 { 0 => rsx!( h1 { "hello 1" } ), 1 => rsx!( h2 { "hello 2" } ), _ => unreachable!(), } } let mut vdom = VirtualDom::new(app); vdom.rebuild(&mut NoOpMutations); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2,) }, ReplaceWith { id: ElementId(1,), m: 1 }, ] ); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, ReplaceWith { id: ElementId(2,), m: 1 }, ] ); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(2,) }, ReplaceWith { id: ElementId(1,), m: 1 }, ] ); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [ LoadTemplate { index: 0, id: ElementId(1,) }, ReplaceWith { id: ElementId(2,), m: 1 }, ] ); } #[test] fn attribute_diff() { fn app() -> Element { let gen = generation(); // attributes have to be sorted by name let attrs = match gen % 5 { 0 => vec![Attribute::new( "a", AttributeValue::Text("hello".into()), None, false, )], 1 => vec![ Attribute::new("a", AttributeValue::Text("hello".into()), None, false), Attribute::new("b", AttributeValue::Text("hello".into()), None, false), Attribute::new("c", AttributeValue::Text("hello".into()), None, false), ], 2 => vec![ Attribute::new("c", AttributeValue::Text("hello".into()), None, false), Attribute::new("d", AttributeValue::Text("hello".into()), None, false), Attribute::new("e", AttributeValue::Text("hello".into()), None, false), ], 3 => vec![Attribute::new( "d", AttributeValue::Text("world".into()), None, false, )], _ => unreachable!(), }; rsx!( div { ..attrs, "hello" } ) } let mut vdom = VirtualDom::new(app); vdom.rebuild(&mut NoOpMutations); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [ SetAttribute { name: "b", value: (AttributeValue::Text("hello".into())), id: ElementId(1,), ns: None, }, SetAttribute { name: "c", value: (AttributeValue::Text("hello".into())), id: ElementId(1,), ns: None, }, ] ); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [ SetAttribute { name: "a", value: AttributeValue::None, id: ElementId(1,), ns: None }, SetAttribute { name: "b", value: AttributeValue::None, id: ElementId(1,), ns: None }, SetAttribute { name: "d", value: AttributeValue::Text("hello".into()), id: ElementId(1,), ns: None, }, SetAttribute { name: "e", value: AttributeValue::Text("hello".into()), id: ElementId(1,), ns: None, }, ] ); vdom.mark_dirty(ScopeId::APP); assert_eq!( vdom.render_immediate_to_vec().edits, [ SetAttribute { name: "c", value: AttributeValue::None, id: ElementId(1,), ns: None }, SetAttribute { name: "d", value: AttributeValue::Text("world".into()), id: ElementId(1,), ns: None, }, SetAttribute { name: "e", value: AttributeValue::None, id: ElementId(1,), ns: None }, ] ); } #[test] fn diff_empty() { fn app() -> Element { match generation() % 2 { 0 => rsx! { div { "hello" } }, 1 => rsx! {}, _ => unreachable!(), } } let mut vdom = VirtualDom::new(app); vdom.rebuild(&mut NoOpMutations); vdom.mark_dirty(ScopeId::APP); let edits = vdom.render_immediate_to_vec().edits; assert_eq!( edits, [ CreatePlaceholder { id: ElementId(2,) }, ReplaceWith { id: ElementId(1,), m: 1 }, ] ) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/core/tests/bubble_error.rs
packages/core/tests/bubble_error.rs
//! we should properly bubble up errors from components use dioxus::prelude::*; use dioxus_core::generation; fn app() -> Element { let raw = match generation() % 2 { 0 => "123.123", 1 => "123.123.123", _ => unreachable!(), }; let value = raw.parse::<f32>().unwrap_or(123.123); rsx! { div { "hello {value}" } } } #[test] fn bubbles_error() { let mut dom = VirtualDom::new(app); { let _edits = dom.rebuild_to_vec(); } dom.mark_dirty(ScopeId::APP); _ = dom.render_immediate_to_vec(); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/asset-resolver/src/lib.rs
packages/asset-resolver/src/lib.rs
#![warn(missing_docs)] //! The asset resolver for the Dioxus bundle format. Each platform has its own way of resolving assets. This crate handles //! resolving assets in a cross-platform way. //! //! There are two broad locations for assets depending on the platform: //! - **Web**: Assets are stored on a remote server and fetched via HTTP requests. //! - **Native**: Assets are read from the local bundle. Each platform has its own bundle structure which may store assets //! as a file at a specific path or in an opaque format like Android's AssetManager. //! //! [`read_asset_bytes`]( abstracts over both of these methods, allowing you to read the bytes of an asset //! regardless of the platform. //! //! If you know you are on a desktop platform, you can use [`asset_path`] to resolve the path of an asset and read //! the contents with [`std::fs`]. //! //! ## Example //! ```rust //! # async fn asset_example() { //! use dioxus::prelude::*; //! //! // Bundle the static JSON asset into the application //! static JSON_ASSET: Asset = asset!("/assets/data.json"); //! //! // Read the bytes of the JSON asset //! let bytes = dioxus::asset_resolver::read_asset_bytes(&JSON_ASSET).await.unwrap(); //! //! // Deserialize the JSON data //! let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); //! assert_eq!(json["key"].as_str(), Some("value")); //! # } //! ``` use std::{fmt::Debug, path::PathBuf}; #[cfg(feature = "native")] pub mod native; #[cfg(feature = "web")] mod web; /// An error that can occur when resolving an asset to a path. Not all platforms can represent assets as paths, /// an error may mean that the asset doesn't exist or it cannot be represented as a path. #[non_exhaustive] #[derive(Debug, thiserror::Error)] pub enum AssetPathError { /// The asset was not found by the resolver. #[error("Failed to find the path in the asset directory")] NotFound, /// The asset may exist, but it cannot be represented as a path. #[error("Asset cannot be represented as a path")] CannotRepresentAsPath, } /// Tries to resolve the path of an asset from a given URI path. Depending on the platform, this may /// return an error even if the asset exists because some platforms cannot represent assets as paths. /// You should prefer [`read_asset_bytes`] to read the asset bytes directly /// for cross-platform compatibility. /// /// ## Platform specific behavior /// /// This function will only work on desktop platforms. It will always return an error in web and Android /// bundles. On Android assets are bundled in the APK, and cannot be represented as paths. In web bundles, /// Assets are fetched via HTTP requests and don't have a filesystem path. /// /// ## Example /// ```rust /// use dioxus::prelude::*; /// /// // Bundle the static JSON asset into the application /// static JSON_ASSET: Asset = asset!("/assets/data.json"); /// /// // Resolve the path of the asset. This will not work in web or Android bundles /// let path = dioxus::asset_resolver::asset_path(&JSON_ASSET).unwrap(); /// /// println!("Asset path: {:?}", path); /// /// // Read the bytes of the JSON asset /// let bytes = std::fs::read(path).unwrap(); /// /// // Deserialize the JSON data /// let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); /// assert_eq!(json["key"].as_str(), Some("value")); /// ``` /// /// ## Resolving assets from a folder /// /// To resolve an asset from a folder, you can pass the path of the file joined with your folder asset as a string: /// ```rust /// # async fn asset_example() { /// use dioxus::prelude::*; /// /// // Bundle the whole assets folder into the application /// static ASSETS: Asset = asset!("/assets"); /// /// // Resolve the path of the asset. This will not work in web or Android bundles /// let path = dioxus::asset_resolver::asset_path(format!("{ASSETS}/data.json")).unwrap(); /// /// println!("Asset path: {:?}", path); /// /// // Read the bytes of the JSON asset /// let bytes = std::fs::read(path).unwrap(); /// /// // Deserialize the JSON data /// let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); /// assert_eq!(json["key"].as_str(), Some("value")); /// # } /// ``` #[allow(unused)] pub fn asset_path(asset: impl ToString) -> Result<PathBuf, AssetPathError> { #[cfg(all(feature = "web", target_arch = "wasm32"))] return Err(AssetPathError::CannotRepresentAsPath); #[cfg(feature = "native")] return native::resolve_native_asset_path(asset.to_string().as_str()); Err(AssetPathError::NotFound) } /// An error that can occur when resolving an asset. #[non_exhaustive] #[derive(Debug, thiserror::Error)] pub enum AssetResolveError { /// An error occurred while resolving a native asset. #[error("Failed to resolve native asset: {0}")] Native(#[from] NativeAssetResolveError), /// An error occurred while resolving a web asset. #[error("Failed to resolve web asset: {0}")] Web(#[from] WebAssetResolveError), /// An error that occurs when no asset resolver is available for the current platform. #[error("Asset resolution is not supported on this platform")] UnsupportedPlatform, } /// Read the bytes of an asset. This will work on both web and native platforms. On the web, /// it will fetch the asset via HTTP, and on native platforms, it will read the asset from the filesystem or bundle. /// /// ## Errors /// This function will return an error if the asset cannot be found or if it fails to read which may be due to I/O errors or /// network issues. /// /// ## Example /// /// ```rust /// # async fn asset_example() { /// use dioxus::prelude::*; /// /// // Bundle the static JSON asset into the application /// static JSON_ASSET: Asset = asset!("/assets/data.json"); /// /// // Read the bytes of the JSON asset /// let bytes = dioxus::asset_resolver::read_asset_bytes(&JSON_ASSET).await.unwrap(); /// /// // Deserialize the JSON data /// let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); /// assert_eq!(json["key"].as_str(), Some("value")); /// # } /// ``` /// /// ## Loading assets from a folder /// /// To load an asset from a folder, you can pass the path of the file joined with your folder asset as a string: /// ```rust /// # async fn asset_example() { /// use dioxus::prelude::*; /// /// // Bundle the whole assets folder into the application /// static ASSETS: Asset = asset!("/assets"); /// /// // Read the bytes of the JSON asset /// let bytes = dioxus::asset_resolver::read_asset_bytes(format!("{ASSETS}/data.json")).await.unwrap(); /// /// // Deserialize the JSON data /// let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); /// assert_eq!(json["key"].as_str(), Some("value")); /// # } /// ``` #[allow(unused)] pub async fn read_asset_bytes(asset: impl ToString) -> Result<Vec<u8>, AssetResolveError> { let path = asset.to_string(); #[cfg(feature = "web")] return web::resolve_web_asset(&path) .await .map_err(AssetResolveError::Web); #[cfg(feature = "native")] return tokio::task::spawn_blocking(move || native::resolve_native_asset(&path)) .await .map_err(|err| AssetResolveError::Native(NativeAssetResolveError::JoinError(err))) .and_then(|result| result.map_err(AssetResolveError::Native)); Err(AssetResolveError::UnsupportedPlatform) } /// An error that occurs when resolving a native asset. #[non_exhaustive] #[derive(Debug, thiserror::Error)] pub enum NativeAssetResolveError { /// An I/O error occurred while reading the asset from the filesystem. #[error("Failed to read asset: {0}")] IoError(#[from] std::io::Error), /// The asset resolver failed to complete and could not be joined. #[cfg(feature = "native")] #[error("Asset resolver join failed: {0}")] JoinError(tokio::task::JoinError), } /// An error that occurs when resolving an asset on the web. pub struct WebAssetResolveError { #[cfg(feature = "web")] error: js_sys::Error, } impl Debug for WebAssetResolveError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut debug = f.debug_struct("WebAssetResolveError"); #[cfg(feature = "web")] debug.field("name", &self.error.name()); #[cfg(feature = "web")] debug.field("message", &self.error.message()); debug.finish() } } impl std::fmt::Display for WebAssetResolveError { #[allow(unreachable_code)] fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { #[cfg(feature = "web")] return write!(f, "{}", self.error.message()); write!(f, "WebAssetResolveError") } } impl std::error::Error for WebAssetResolveError {}
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/asset-resolver/src/native.rs
packages/asset-resolver/src/native.rs
//! Native specific utilities for resolving assets in a bundle. This module is intended for use in renderers that //! need to resolve asset bundles for resources like images, and fonts. use http::{status::StatusCode, Response}; use std::path::{Path, PathBuf}; use crate::{AssetPathError, NativeAssetResolveError}; /// An error that can occur when serving an asset. #[non_exhaustive] #[derive(Debug, thiserror::Error)] pub enum AssetServeError { /// The asset path could not be resolved. #[error("Failed to resolve asset: {0}")] ResolveError(#[from] NativeAssetResolveError), /// An error occurred while constructing the HTTP response. #[error("Failed to construct response: {0}")] ResponseError(#[from] http::Error), } /// Try to resolve the path of an asset from a given URI path. pub(crate) fn resolve_native_asset_path(path: &str) -> Result<PathBuf, AssetPathError> { #[allow(clippy::unnecessary_lazy_evaluations)] resolve_asset_path_from_filesystem(path).ok_or_else(|| { #[cfg(target_os = "android")] { // If the asset exists in the Android asset manager, return the can't be represented as a path // error instead if to_java_load_asset(path).is_some() { return AssetPathError::CannotRepresentAsPath; } } AssetPathError::NotFound }) } /// Try to resolve the path of an asset from a given URI path. fn resolve_asset_path_from_filesystem(path: &str) -> Option<PathBuf> { // If the user provided a custom asset handler, then call it and return the response if the request was handled. // The path is the first part of the URI, so we need to trim the leading slash. let mut uri_path = PathBuf::from( percent_encoding::percent_decode_str(path) .decode_utf8() .expect("expected URL to be UTF-8 encoded") .as_ref(), ); // If the asset doesn't exist, or starts with `/assets/`, then we'll try to serve out of the bundle // This lets us handle both absolute and relative paths without being too "special" // It just means that our macos bundle is a little "special" because we need to place an `assets` // dir in the `Resources` dir. // // If there's no asset root, we use the cargo manifest dir as the root, or the current dir if !uri_path.exists() || uri_path.starts_with("/assets/") { let bundle_root = get_asset_root(); let relative_path = uri_path.strip_prefix("/").unwrap(); uri_path = bundle_root.join(relative_path); } // If the asset exists, return it uri_path.exists().then_some(uri_path) } struct ResolvedAsset { mime_type: &'static str, body: Vec<u8>, } impl ResolvedAsset { fn new(mime_type: &'static str, body: Vec<u8>) -> Self { Self { mime_type, body } } fn into_response(self) -> Result<Response<Vec<u8>>, AssetServeError> { Ok(Response::builder() .header("Content-Type", self.mime_type) .header("Access-Control-Allow-Origin", "*") .body(self.body)?) } } /// Read the bytes for an asset pub(crate) fn resolve_native_asset(path: &str) -> Result<Vec<u8>, NativeAssetResolveError> { // Attempt to serve from the asset dir on android using its loader #[cfg(target_os = "android")] { if let Some(asset) = to_java_load_asset(path) { return Ok(asset); } } let Some(uri_path) = resolve_asset_path_from_filesystem(path) else { return Err(NativeAssetResolveError::IoError(std::io::Error::new( std::io::ErrorKind::NotFound, "Asset not found", ))); }; Ok(std::fs::read(uri_path)?) } /// Resolve the asset and its mime type fn resolve_asset(path: &str) -> Result<Option<ResolvedAsset>, NativeAssetResolveError> { // Attempt to serve from the asset dir on android using its loader #[cfg(target_os = "android")] { if let Some(asset) = to_java_load_asset(path) { let extension = path.rsplit_once('.').and_then(|(_, ext)| Some(ext)); let mime_type = get_mime_from_ext(extension); return Ok(Some(ResolvedAsset::new(mime_type, asset))); } } let Some(uri_path) = resolve_asset_path_from_filesystem(path) else { return Ok(None); }; let mime_type = get_mime_from_path(&uri_path)?; let body = std::fs::read(uri_path)?; Ok(Some(ResolvedAsset::new(mime_type, body))) } /// Serve an asset from the filesystem or a custom asset handler. /// /// This method properly accesses the asset directory based on the platform and serves the asset /// wrapped in an HTTP response. /// /// Platform specifics: /// - On the web, this returns AssetServerError since there's no filesystem access. Use `fetch` instead. /// - On Android, it attempts to load assets using the Android AssetManager. /// - On other platforms, it serves assets from the filesystem. pub fn serve_asset(path: &str) -> Result<Response<Vec<u8>>, AssetServeError> { match resolve_asset(path)? { Some(asset) => asset.into_response(), None => Ok(Response::builder() .status(StatusCode::NOT_FOUND) .body(String::from("Not Found").into_bytes())?), } } /// Get the asset directory, following tauri/cargo-bundles directory discovery approach /// /// Currently supports: /// - [x] macOS /// - [x] iOS /// - [x] Windows /// - [x] Linux (appimage) /// - [ ] Linux (rpm) /// - [x] Linux (deb) /// - [ ] Android #[allow(unreachable_code)] fn get_asset_root() -> PathBuf { let cur_exe = std::env::current_exe().unwrap(); #[cfg(target_os = "macos")] { return cur_exe .parent() .unwrap() .parent() .unwrap() .join("Resources"); } #[cfg(target_os = "linux")] { // In linux bundles, the assets are placed in the lib/$product_name directory // bin/ // main // lib/ // $product_name/ // assets/ if let Some(product_name) = dioxus_cli_config::product_name() { let lib_asset_path = || { let path = cur_exe.parent()?.parent()?.join("lib").join(product_name); path.exists().then_some(path) }; if let Some(asset_dir) = lib_asset_path() { return asset_dir; } } } // For all others, the structure looks like this: // app.(exe/appimage) // main.exe // assets/ cur_exe.parent().unwrap().to_path_buf() } /// Get the mime type from a path-like string fn get_mime_from_path(asset: &Path) -> std::io::Result<&'static str> { if asset.extension().is_some_and(|ext| ext == "svg") { return Ok("image/svg+xml"); } match infer::get_from_path(asset)?.map(|f| f.mime_type()) { Some(f) if f != "text/plain" => Ok(f), _other => Ok(get_mime_by_ext(asset)), } } /// Get the mime type from a URI using its extension fn get_mime_by_ext(trimmed: &Path) -> &'static str { let ext = trimmed.extension().as_ref().and_then(|ext| ext.to_str()); get_mime_from_ext(ext) } /// Get the mime type from a URI using its extension pub fn get_mime_from_ext(ext: Option<&str>) -> &'static str { match ext { // The common assets are all utf-8 encoded Some("js") => "text/javascript; charset=utf-8", Some("css") => "text/css; charset=utf-8", Some("json") => "application/json; charset=utf-8", Some("svg") => "image/svg+xml; charset=utf-8", Some("html") => "text/html; charset=utf-8", // the rest... idk? probably not Some("mjs") => "text/javascript; charset=utf-8", Some("bin") => "application/octet-stream", Some("csv") => "text/csv", Some("ico") => "image/vnd.microsoft.icon", Some("jsonld") => "application/ld+json", Some("rtf") => "application/rtf", Some("mp4") => "video/mp4", // Assume HTML when a TLD is found for eg. `dioxus:://dioxuslabs.app` | `dioxus://hello.com` Some(_) => "text/html; charset=utf-8", // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types // using octet stream according to this: None => "application/octet-stream", } } #[cfg(target_os = "android")] pub(crate) fn to_java_load_asset(filepath: &str) -> Option<Vec<u8>> { let normalized = filepath .trim_start_matches("/assets/") .trim_start_matches('/'); // in debug mode, the asset might be under `/data/local/tmp/dx/` - attempt to read it from there if it exists #[cfg(debug_assertions)] { let path = dioxus_cli_config::android_session_cache_dir().join(normalized); if path.exists() { return std::fs::read(path).ok(); } } use std::ptr::NonNull; let ctx = ndk_context::android_context(); let vm = unsafe { jni::JavaVM::from_raw(ctx.vm().cast()) }.unwrap(); let mut env = vm.attach_current_thread().unwrap(); // Query the Asset Manager let asset_manager_ptr = env .call_method( unsafe { jni::objects::JObject::from_raw(ctx.context().cast()) }, "getAssets", "()Landroid/content/res/AssetManager;", &[], ) .expect("Failed to get asset manager") .l() .expect("Failed to get asset manager as object"); unsafe { let asset_manager = ndk_sys::AAssetManager_fromJava(env.get_native_interface(), *asset_manager_ptr); let asset_manager = ndk::asset::AssetManager::from_ptr( NonNull::new(asset_manager).expect("Invalid asset manager"), ); let cstr = std::ffi::CString::new(normalized).unwrap(); let mut asset = asset_manager.open(&cstr)?; Some(asset.buffer().unwrap().to_vec()) } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/asset-resolver/src/web.rs
packages/asset-resolver/src/web.rs
use js_sys::{ wasm_bindgen::{JsCast, JsValue}, ArrayBuffer, Uint8Array, }; use wasm_bindgen_futures::JsFuture; use web_sys::{Request, Response}; use crate::WebAssetResolveError; impl From<js_sys::Error> for WebAssetResolveError { fn from(error: js_sys::Error) -> Self { WebAssetResolveError { error } } } impl WebAssetResolveError { fn from_js_value(value: JsValue) -> Self { if let Some(error) = value.dyn_ref::<js_sys::Error>() { WebAssetResolveError::from(error.clone()) } else { unreachable!("Expected a js_sys::Error, got: {:?}", value) } } } pub(crate) async fn resolve_web_asset(path: &str) -> Result<Vec<u8>, WebAssetResolveError> { let url = if path.starts_with("/") { path.to_string() } else { format!("/{path}") }; let request = Request::new_with_str(&url).map_err(WebAssetResolveError::from_js_value)?; let window = web_sys::window().unwrap(); let response_promise = JsFuture::from(window.fetch_with_request(&request)) .await .map_err(WebAssetResolveError::from_js_value)?; let response = response_promise.unchecked_into::<Response>(); let array_buffer_promise = response .array_buffer() .map_err(WebAssetResolveError::from_js_value)?; let array_buffer: ArrayBuffer = JsFuture::from(array_buffer_promise) .await .map_err(WebAssetResolveError::from_js_value)? .unchecked_into(); let bytes = Uint8Array::new(&array_buffer); Ok(bytes.to_vec()) }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router/src/lib.rs
packages/router/src/lib.rs
#![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")] // cannot use forbid, because props derive macro generates #[allow(missing_docs)] #![deny(missing_docs)] #![allow(non_snake_case)] pub mod navigation; pub mod routable; /// Components interacting with the router. pub mod components { #[cfg(feature = "html")] mod default_errors; #[cfg(feature = "html")] pub use default_errors::*; #[cfg(feature = "html")] mod history_buttons; #[cfg(feature = "html")] pub use history_buttons::*; #[cfg(feature = "html")] mod link; #[cfg(feature = "html")] pub use link::*; mod outlet; pub use outlet::*; mod router; pub use router::*; mod history_provider; pub use history_provider::*; #[doc(hidden)] pub mod child_router; } mod contexts { pub(crate) mod navigator; pub(crate) mod outlet; pub use outlet::{use_outlet_context, OutletContext}; pub(crate) mod router; pub use navigator::*; pub(crate) use router::*; pub use router::{root_router, GenericRouterContext, ParseRouteError, RouterContext}; } mod router_cfg; /// Hooks for interacting with the router in components. pub mod hooks { mod use_router; pub use use_router::*; mod use_route; pub use use_route::*; mod use_navigator; pub use use_navigator::*; } pub use hooks::router; #[cfg(feature = "html")] pub use crate::components::{GoBackButton, GoForwardButton, HistoryButtonProps, Link, LinkProps}; pub use crate::components::{Outlet, Router, RouterProps}; pub use crate::contexts::*; pub use crate::hooks::*; pub use crate::navigation::*; pub use crate::routable::*; pub use crate::router_cfg::RouterConfig; pub use dioxus_router_macro::Routable; #[doc(hidden)] /// A component with props used in the macro pub trait HasProps { /// The props type of the component. type Props; } impl<P> HasProps for dioxus_core::Component<P> { type Props = P; } mod utils { pub(crate) mod use_router_internal; } #[doc(hidden)] pub mod exports { pub use crate::query_sets::*; pub use percent_encoding; } pub(crate) mod query_sets { //! Url percent encode sets defined [here](https://url.spec.whatwg.org/#percent-encoded-bytes) use percent_encoding::AsciiSet; /// The ASCII set that must be escaped in query strings. pub const QUERY_ASCII_SET: &AsciiSet = &percent_encoding::CONTROLS .add(b' ') .add(b'"') .add(b'#') .add(b'<') .add(b'>'); /// The ASCII set that must be escaped in path segments. pub const PATH_ASCII_SET: &AsciiSet = &QUERY_ASCII_SET .add(b'?') .add(b'^') .add(b'`') .add(b'{') .add(b'}'); /// The ASCII set that must be escaped in hash fragments. pub const FRAGMENT_ASCII_SET: &AsciiSet = &percent_encoding::CONTROLS .add(b' ') .add(b'"') .add(b'<') .add(b'>') .add(b'`'); }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router/src/router_cfg.rs
packages/router/src/router_cfg.rs
use crate::{GenericRouterContext, NavigationTarget, Routable, RoutingCallback}; use dioxus_core::Element; use std::sync::Arc; /// Global configuration options for the router. /// /// This implements [`Default`] and follows the builder pattern, so you can use it like this: /// ```rust,no_run /// # use dioxus::prelude::*; /// # use dioxus_router::RouterConfig; /// # #[component] /// # fn Index() -> Element { /// # VNode::empty() /// # } /// #[derive(Clone, Routable)] /// enum Route { /// #[route("/")] /// Index {}, /// } /// /// fn ExternalNavigationFailure() -> Element { /// rsx! { /// "Failed to navigate to external URL" /// } /// } /// /// let cfg = RouterConfig::<Route>::default().failure_external_navigation(ExternalNavigationFailure); /// ``` pub struct RouterConfig<R> { pub(crate) failure_external_navigation: fn() -> Element, pub(crate) on_update: Option<RoutingCallback<R>>, } #[cfg(not(feature = "html"))] impl<R> Default for RouterConfig<R> { fn default() -> Self { Self { failure_external_navigation: || VNode::empty(), on_update: None, } } } #[cfg(feature = "html")] impl<R> Default for RouterConfig<R> { fn default() -> Self { Self { failure_external_navigation: crate::components::FailureExternalNavigation, on_update: None, } } } impl<R> RouterConfig<R> where R: Routable, { /// A function to be called whenever the routing is updated. /// /// The callback is invoked after the routing is updated, but before components and hooks are /// updated. /// /// If the callback returns a [`NavigationTarget`] the router will replace the current location /// with it. If no navigation failure was triggered, the router will then updated dependent /// components and hooks. /// /// The callback is called no more than once per rerouting. It will not be called if a /// navigation failure occurs. /// /// Defaults to [`None`]. pub fn on_update( self, callback: impl Fn(GenericRouterContext<R>) -> Option<NavigationTarget<R>> + 'static, ) -> Self { Self { on_update: Some(Arc::new(callback)), ..self } } /// A component to render when an external navigation fails. /// #[cfg_attr( feature = "html", doc = "Defaults to [`crate::components::FailureExternalNavigation`]." )] pub fn failure_external_navigation(self, component: fn() -> Element) -> Self { Self { failure_external_navigation: component, ..self } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router/src/routable.rs
packages/router/src/routable.rs
#![allow(non_snake_case)] //! # Routable use dioxus_core::Element; use std::iter::FlatMap; use std::slice::Iter; use std::{fmt::Display, str::FromStr}; /// An error that occurs when parsing a route. #[derive(Debug, PartialEq)] pub struct RouteParseError<E: Display> { /// The attempted routes that failed to match. pub attempted_routes: Vec<E>, } impl<E: Display> Display for RouteParseError<E> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Route did not match:\nAttempted Matches:\n")?; for (i, route) in self.attempted_routes.iter().enumerate() { writeln!(f, "{}) {route}", i + 1)?; } Ok(()) } } /// Something that can be created from an entire query string. This trait must be implemented for any type that is spread into the query segment like `#[route("/?:..query")]`. /// /// /// **This trait is automatically implemented for any types that implement `From<&str>`.** /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// // FromQuery must be implemented for any types you spread into the query segment /// #[route("/?:..query")] /// Home { /// query: CustomQuery /// }, /// } /// /// #[derive(Default, Clone, PartialEq, Debug)] /// struct CustomQuery { /// count: i32, /// } /// /// // We implement From<&str> for CustomQuery so that FromQuery is implemented automatically /// impl From<&str> for CustomQuery { /// fn from(query: &str) -> Self { /// CustomQuery { /// count: query.parse().unwrap_or(0), /// } /// } /// } /// /// // We also need to implement Display for CustomQuery which will be used to format the query string into the URL /// impl std::fmt::Display for CustomQuery { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// write!(f, "{}", self.count) /// } /// } /// /// # #[component] /// # fn Home(query: CustomQuery) -> Element { /// # unimplemented!() /// # } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`FromQuery` is not implemented for `{Self}`", label = "spread query", note = "FromQuery is automatically implemented for types that implement `From<&str>`. You need to either implement From<&str> or implement FromQuery manually." ) )] pub trait FromQuery { /// Create an instance of `Self` from a query string. fn from_query(query: &str) -> Self; } impl<T: for<'a> From<&'a str>> FromQuery for T { fn from_query(query: &str) -> Self { T::from(query) } } /// Something that can be created from a query argument. This trait must be implemented for any type that is used as a query argument like `#[route("/?:query")]`. /// /// **This trait is automatically implemented for any types that implement `FromStr` and `Default`.** /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// // FromQuerySegment must be implemented for any types you use in the query segment /// // When you don't spread the query, you can parse multiple values form the query /// // This url will be in the format `/?query=123&other=456` /// #[route("/?:query&:other")] /// Home { /// query: CustomQuery, /// other: i32, /// }, /// } /// /// // We can derive Default for CustomQuery /// // If the router fails to parse the query value, it will use the default value instead /// #[derive(Default, Clone, PartialEq, Debug)] /// struct CustomQuery { /// count: i32, /// } /// /// // We implement FromStr for CustomQuery so that FromQuerySegment is implemented automatically /// impl std::str::FromStr for CustomQuery { /// type Err = <i32 as std::str::FromStr>::Err; /// /// fn from_str(query: &str) -> Result<Self, Self::Err> { /// Ok(CustomQuery { /// count: query.parse()?, /// }) /// } /// } /// /// // We also need to implement Display for CustomQuery so that ToQueryArgument is implemented automatically /// impl std::fmt::Display for CustomQuery { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// write!(f, "{}", self.count) /// } /// } /// /// # #[component] /// # fn Home(query: CustomQuery, other: i32) -> Element { /// # unimplemented!() /// # } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`FromQueryArgument` is not implemented for `{Self}`", label = "query argument", note = "FromQueryArgument is automatically implemented for types that implement `FromStr` and `Default`. You need to either implement FromStr and Default or implement FromQueryArgument manually." ) )] pub trait FromQueryArgument<P = ()>: Default { /// The error that can occur when parsing a query argument. type Err; /// Create an instance of `Self` from a query string. fn from_query_argument(argument: &str) -> Result<Self, Self::Err>; } impl<T: Default + FromStr> FromQueryArgument for T where <T as FromStr>::Err: Display, { type Err = <T as FromStr>::Err; fn from_query_argument(argument: &str) -> Result<Self, Self::Err> { match T::from_str(argument) { Ok(result) => Ok(result), Err(err) => { tracing::error!("Failed to parse query argument: {}", err); Err(err) } } } } /// A marker type for `Option<T>` to implement `FromQueryArgument`. pub struct OptionMarker; impl<T: Default + FromStr> FromQueryArgument<OptionMarker> for Option<T> where <T as FromStr>::Err: Display, { type Err = <T as FromStr>::Err; fn from_query_argument(argument: &str) -> Result<Self, Self::Err> { match T::from_str(argument) { Ok(result) => Ok(Some(result)), Err(err) => { tracing::error!("Failed to parse query argument: {}", err); Err(err) } } } } /// Something that can be formatted as a query argument. This trait must be implemented for any type that is used as a query argument like `#[route("/?:query")]`. /// /// **This trait is automatically implemented for any types that implement [`Display`].** /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// // FromQuerySegment must be implemented for any types you use in the query segment /// // When you don't spread the query, you can parse multiple values form the query /// // This url will be in the format `/?query=123&other=456` /// #[route("/?:query&:other")] /// Home { /// query: CustomQuery, /// other: i32, /// }, /// } /// /// // We can derive Default for CustomQuery /// // If the router fails to parse the query value, it will use the default value instead /// #[derive(Default, Clone, PartialEq, Debug)] /// struct CustomQuery { /// count: i32, /// } /// /// // We implement FromStr for CustomQuery so that FromQuerySegment is implemented automatically /// impl std::str::FromStr for CustomQuery { /// type Err = <i32 as std::str::FromStr>::Err; /// /// fn from_str(query: &str) -> Result<Self, Self::Err> { /// Ok(CustomQuery { /// count: query.parse()?, /// }) /// } /// } /// /// // We also need to implement Display for CustomQuery so that ToQueryArgument is implemented automatically /// impl std::fmt::Display for CustomQuery { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// write!(f, "{}", self.count) /// } /// } /// /// # #[component] /// # fn Home(query: CustomQuery, other: i32) -> Element { /// # unimplemented!() /// # } /// ``` pub trait ToQueryArgument<T = ()> { /// Display the query argument as a string. fn display_query_argument( &self, query_name: &str, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result; } impl<T> ToQueryArgument for T where T: Display, { fn display_query_argument( &self, query_name: &str, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { write!(f, "{}={}", query_name, self) } } impl<T: Display> ToQueryArgument<OptionMarker> for Option<T> { fn display_query_argument( &self, query_name: &str, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { if let Some(value) = self { write!(f, "{}={}", query_name, value) } else { Ok(()) } } } /// A type that implements [`ToQueryArgument`] along with the query name. This type implements Display and can be used to format the query argument into a string. pub struct DisplayQueryArgument<'a, T, M = ()> { /// The query name. query_name: &'a str, /// The value to format. value: &'a T, /// The `ToQueryArgument` marker type, which can be used to differentiate between different types of query arguments. _marker: std::marker::PhantomData<M>, } impl<'a, T, M> DisplayQueryArgument<'a, T, M> { /// Create a new `DisplayQueryArgument`. pub fn new(query_name: &'a str, value: &'a T) -> Self { Self { query_name, value, _marker: std::marker::PhantomData, } } } impl<T: ToQueryArgument<M>, M> Display for DisplayQueryArgument<'_, T, M> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.value.display_query_argument(self.query_name, f) } } /// Something that can be created from an entire hash fragment. This must be implemented for any type that is used as a hash fragment like `#[route("/#:hash_fragment")]`. /// /// /// **This trait is automatically implemented for any types that implement `FromStr` and `Default`.** /// /// # Example /// /// ```rust /// use dioxus::prelude::*; /// use dioxus_router::FromHashFragment; /// /// #[derive(Routable, Clone)] /// #[rustfmt::skip] /// enum Route { /// // State is stored in the url hash /// #[route("/#:url_hash")] /// Home { /// url_hash: State, /// }, /// } /// /// #[component] /// fn Home(url_hash: State) -> Element { /// unimplemented!() /// } /// /// /// #[derive(Clone, PartialEq, Default)] /// struct State { /// count: usize, /// other_count: usize /// } /// /// // The hash segment will be displayed as a string (this will be url encoded automatically) /// impl std::fmt::Display for State { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// write!(f, "{}-{}", self.count, self.other_count) /// } /// } /// /// // We need to parse the hash fragment into a struct from the string (this will be url decoded automatically) /// impl FromHashFragment for State { /// fn from_hash_fragment(hash: &str) -> Self { /// let Some((first, second)) = hash.split_once('-') else { /// // URL fragment parsing shouldn't fail. You can return a default value if you want /// return Default::default(); /// }; /// /// let first = first.parse().unwrap(); /// let second = second.parse().unwrap(); /// /// State { /// count: first, /// other_count: second, /// } /// } /// } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`FromHashFragment` is not implemented for `{Self}`", label = "hash fragment", note = "FromHashFragment is automatically implemented for types that implement `FromStr` and `Default`. You need to either implement FromStr and Default or implement FromHashFragment manually." ) )] pub trait FromHashFragment { /// Create an instance of `Self` from a hash fragment. fn from_hash_fragment(hash: &str) -> Self; } impl<T> FromHashFragment for T where T: FromStr + Default, T::Err: std::fmt::Display, { fn from_hash_fragment(hash: &str) -> Self { match T::from_str(hash) { Ok(value) => value, Err(err) => { tracing::error!("Failed to parse hash fragment: {}", err); Default::default() } } } } /// Something that can be created from a single route segment. This must be implemented for any type that is used as a route segment like `#[route("/:route_segment")]`. /// /// /// **This trait is automatically implemented for any types that implement `FromStr` and `Default`.** /// /// ```rust /// use dioxus::prelude::*; /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// // FromRouteSegment must be implemented for any types you use in the route segment /// // When you don't spread the route, you can parse multiple values from the route /// // This url will be in the format `/123/456` /// #[route("/:route_segment_one/:route_segment_two")] /// Home { /// route_segment_one: CustomRouteSegment, /// route_segment_two: i32, /// }, /// } /// /// // We can derive Default for CustomRouteSegment /// // If the router fails to parse the route segment, it will use the default value instead /// #[derive(Default, PartialEq, Clone, Debug)] /// struct CustomRouteSegment { /// count: i32, /// } /// /// // We implement FromStr for CustomRouteSegment so that FromRouteSegment is implemented automatically /// impl std::str::FromStr for CustomRouteSegment { /// type Err = <i32 as std::str::FromStr>::Err; /// /// fn from_str(route_segment: &str) -> Result<Self, Self::Err> { /// Ok(CustomRouteSegment { /// count: route_segment.parse()?, /// }) /// } /// } /// /// // We also need to implement Display for CustomRouteSegment which will be used to format the route segment into the URL /// impl std::fmt::Display for CustomRouteSegment { /// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// write!(f, "{}", self.count) /// } /// } /// /// # #[component] /// # fn Home(route_segment_one: CustomRouteSegment, route_segment_two: i32) -> Element { /// # unimplemented!() /// # } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`FromRouteSegment` is not implemented for `{Self}`", label = "route segment", note = "FromRouteSegment is automatically implemented for types that implement `FromStr` and `Default`. You need to either implement FromStr and Default or implement FromRouteSegment manually." ) )] pub trait FromRouteSegment: Sized { /// The error that can occur when parsing a route segment. type Err; /// Create an instance of `Self` from a route segment. fn from_route_segment(route: &str) -> Result<Self, Self::Err>; } impl<T: FromStr> FromRouteSegment for T where <T as FromStr>::Err: Display, { type Err = <T as FromStr>::Err; fn from_route_segment(route: &str) -> Result<Self, Self::Err> { T::from_str(route) } } #[test] fn full_circle() { let route = "testing 1234 hello world"; assert_eq!(String::from_route_segment(route).unwrap(), route); } /// Something that can be converted into multiple route segments. This must be implemented for any type that is spread into the route segment like `#[route("/:..route_segments")]`. /// /// /// **This trait is automatically implemented for any types that implement `IntoIterator<Item=impl Display>`.** /// /// ```rust /// use dioxus::prelude::*; /// use dioxus_router::{ToRouteSegments, FromRouteSegments}; /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// // FromRouteSegments must be implemented for any types you use in the route segment /// // When you spread the route, you can parse multiple values from the route /// // This url will be in the format `/123/456/789` /// #[route("/:..numeric_route_segments")] /// Home { /// numeric_route_segments: NumericRouteSegments, /// }, /// } /// /// // We can derive Default for NumericRouteSegments /// // If the router fails to parse the route segment, it will use the default value instead /// #[derive(Default, PartialEq, Clone, Debug)] /// struct NumericRouteSegments { /// numbers: Vec<i32>, /// } /// /// // Implement ToRouteSegments for NumericRouteSegments so that we can display the route segments /// impl ToRouteSegments for NumericRouteSegments { /// fn display_route_segments(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// for number in &self.numbers { /// write!(f, "/{}", number)?; /// } /// Ok(()) /// } /// } /// /// // We also need to parse the route segments with `FromRouteSegments` /// impl FromRouteSegments for NumericRouteSegments { /// type Err = <i32 as std::str::FromStr>::Err; /// /// fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err> { /// let mut numbers = Vec::new(); /// for segment in segments { /// numbers.push(segment.parse()?); /// } /// Ok(NumericRouteSegments { numbers }) /// } /// } /// /// # #[component] /// # fn Home(numeric_route_segments: NumericRouteSegments) -> Element { /// # unimplemented!() /// # } /// ``` pub trait ToRouteSegments { /// Display the route segments with each route segment separated by a `/`. This should not start with a `/`. /// fn display_route_segments(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result; } // Implement ToRouteSegments for any type that can turn &self into an iterator of &T where T: Display impl<I, T: Display> ToRouteSegments for I where for<'a> &'a I: IntoIterator<Item = &'a T>, { fn display_route_segments(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for segment in self { write!(f, "/")?; let segment = segment.to_string(); let encoded = percent_encoding::utf8_percent_encode(&segment, crate::query_sets::PATH_ASCII_SET); write!(f, "{}", encoded)?; } Ok(()) } } #[test] fn to_route_segments() { struct DisplaysRoute; impl Display for DisplaysRoute { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let segments = vec!["hello", "world"]; segments.display_route_segments(f) } } assert_eq!(DisplaysRoute.to_string(), "/hello/world"); } /// Something that can be created from multiple route segments. This must be implemented for any type that is spread into the route segment like `#[route("/:..route_segments")]`. /// /// /// **This trait is automatically implemented for any types that implement `FromIterator<impl Display>`.** /// /// ```rust /// use dioxus::prelude::*; /// use dioxus_router::{ToRouteSegments, FromRouteSegments}; /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// // FromRouteSegments must be implemented for any types you use in the route segment /// // When you spread the route, you can parse multiple values from the route /// // This url will be in the format `/123/456/789` /// #[route("/:..numeric_route_segments")] /// Home { /// numeric_route_segments: NumericRouteSegments, /// }, /// } /// /// // We can derive Default for NumericRouteSegments /// // If the router fails to parse the route segment, it will use the default value instead /// #[derive(Default, Clone, PartialEq, Debug)] /// struct NumericRouteSegments { /// numbers: Vec<i32>, /// } /// /// // Implement ToRouteSegments for NumericRouteSegments so that we can display the route segments /// impl ToRouteSegments for NumericRouteSegments { /// fn display_route_segments(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { /// for number in &self.numbers { /// write!(f, "/{}", number)?; /// } /// Ok(()) /// } /// } /// /// // We also need to parse the route segments with `FromRouteSegments` /// impl FromRouteSegments for NumericRouteSegments { /// type Err = <i32 as std::str::FromStr>::Err; /// /// fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err> { /// let mut numbers = Vec::new(); /// for segment in segments { /// numbers.push(segment.parse()?); /// } /// Ok(NumericRouteSegments { numbers }) /// } /// } /// /// # #[component] /// # fn Home(numeric_route_segments: NumericRouteSegments) -> Element { /// # unimplemented!() /// # } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`FromRouteSegments` is not implemented for `{Self}`", label = "spread route segments", note = "FromRouteSegments is automatically implemented for types that implement `FromIterator` with an `Item` type that implements `Display`. You need to either implement FromIterator or implement FromRouteSegments manually." ) )] pub trait FromRouteSegments: Sized { /// The error that can occur when parsing route segments. type Err: std::fmt::Display; /// Create an instance of `Self` from route segments. /// /// NOTE: This method must parse the output of `ToRouteSegments::display_route_segments` into the type `Self`. fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err>; } impl<I: std::iter::FromIterator<String>> FromRouteSegments for I { type Err = <String as FromRouteSegment>::Err; fn from_route_segments(segments: &[&str]) -> Result<Self, Self::Err> { segments .iter() .map(|s| String::from_route_segment(s)) .collect() } } /// A flattened version of [`Routable::SITE_MAP`]. /// This essentially represents a `Vec<Vec<SegmentType>>`, which you can collect it into. type SiteMapFlattened<'a> = FlatMap< Iter<'a, SiteMapSegment>, Vec<Vec<SegmentType>>, fn(&SiteMapSegment) -> Vec<Vec<SegmentType>>, >; /// The Routable trait is implemented for types that can be converted to and from a route and be rendered as a page. /// /// A Routable object is something that can be: /// 1. Converted from a route. /// 2. Converted to a route. /// 3. Rendered as a component. /// /// This trait should generally be derived using the [`dioxus_router_macro::Routable`] macro which has more information about the syntax. /// /// ## Example /// ```rust /// use dioxus::prelude::*; /// /// fn App() -> Element { /// rsx! { /// Router::<Route> { } /// } /// } /// /// // Routes are generally enums that derive `Routable` /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// // Each enum has an associated url /// #[route("/")] /// Home {}, /// // Routes can include dynamic segments that are parsed from the url /// #[route("/blog/:blog_id")] /// Blog { blog_id: usize }, /// // Or query segments that are parsed from the url /// #[route("/edit?:blog_id")] /// Edit { blog_id: usize }, /// // Or hash segments that are parsed from the url /// #[route("/hashtag/#:hash")] /// Hash { hash: String }, /// } /// /// // Each route variant defaults to rendering a component of the same name /// #[component] /// fn Home() -> Element { /// rsx! { /// h1 { "Home" } /// } /// } /// /// // If the variant has dynamic parameters, those are passed to the component /// #[component] /// fn Blog(blog_id: usize) -> Element { /// rsx! { /// h1 { "Blog" } /// } /// } /// /// #[component] /// fn Edit(blog_id: usize) -> Element { /// rsx! { /// h1 { "Edit" } /// } /// } /// /// #[component] /// fn Hash(hash: String) -> Element { /// rsx! { /// h1 { "Hashtag #{hash}" } /// } /// } /// ``` #[rustversion::attr( since(1.78.0), diagnostic::on_unimplemented( message = "`Routable` is not implemented for `{Self}`", label = "Route", note = "Routable should generally be derived using the `#[derive(Routable)]` macro." ) )] pub trait Routable: FromStr<Err: Display> + Display + Clone + 'static { /// The error that can occur when parsing a route. const SITE_MAP: &'static [SiteMapSegment]; /// Render the route at the given level fn render(&self, level: usize) -> Element; /// Checks if this route is a child of the given route. /// /// # Example /// ```rust /// use dioxus::prelude::*; /// /// #[component] /// fn Home() -> Element { VNode::empty() } /// #[component] /// fn About() -> Element { VNode::empty() } /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// #[route("/")] /// Home {}, /// #[route("/about")] /// About {}, /// } /// /// let route = Route::About {}; /// let parent = Route::Home {}; /// assert!(route.is_child_of(&parent)); /// ``` fn is_child_of(&self, other: &Self) -> bool { let self_str = self.to_string(); let self_str = self_str .split_once('#') .map(|(route, _)| route) .unwrap_or(&self_str); let self_str = self_str .split_once('?') .map(|(route, _)| route) .unwrap_or(self_str); let self_str = self_str.trim_end_matches('/'); let other_str = other.to_string(); let other_str = other_str .split_once('#') .map(|(route, _)| route) .unwrap_or(&other_str); let other_str = other_str .split_once('?') .map(|(route, _)| route) .unwrap_or(other_str); let other_str = other_str.trim_end_matches('/'); let mut self_segments = self_str.split('/'); let mut other_segments = other_str.split('/'); loop { match (self_segments.next(), other_segments.next()) { // If the two routes are the same length, or this route has less segments, then this segment // cannot be the child of the other segment (None, Some(_)) | (None, None) => { return false; } // If two segments are not the same, then this segment cannot be the child of the other segment (Some(self_seg), Some(other_seg)) => { if self_seg != other_seg { return false; } } // If the other route has less segments, then this route is the child of the other route (Some(_), None) => break, } } true } /// Get the parent route of this route. /// /// # Example /// ```rust /// use dioxus::prelude::*; /// /// #[component] /// fn Home() -> Element { VNode::empty() } /// #[component] /// fn About() -> Element { VNode::empty() } /// /// #[derive(Routable, Clone, PartialEq, Debug)] /// enum Route { /// #[route("/home")] /// Home {}, /// #[route("/home/about")] /// About {}, /// } /// /// let route = Route::About {}; /// let parent = route.parent().unwrap(); /// assert_eq!(parent, Route::Home {}); /// ``` fn parent(&self) -> Option<Self> { let as_str = self.to_string(); let (route_and_query, _) = as_str.split_once('#').unwrap_or((&as_str, "")); let (route, _) = route_and_query .split_once('?') .unwrap_or((route_and_query, "")); let route = route.trim_end_matches('/'); let segments = route.split_inclusive('/'); let segment_count = segments.clone().count(); let new_route: String = segments.take(segment_count.saturating_sub(1)).collect(); Self::from_str(&new_route).ok() } /// Returns a flattened version of [`Self::SITE_MAP`]. fn flatten_site_map<'a>() -> SiteMapFlattened<'a> { Self::SITE_MAP.iter().flat_map(SiteMapSegment::flatten) } /// Gets a list of all the static routes. /// Example static route: `#[route("/static/route")]` fn static_routes() -> Vec<Self> { Self::flatten_site_map() .filter_map(|segments| { let mut route = String::new(); for segment in segments.iter() { match segment { SegmentType::Static(s) => { route.push('/'); route.push_str(s) } SegmentType::Child => {} _ => return None, } } route.parse().ok() }) .collect() } } /// A type erased map of the site structure. #[derive(Debug, Clone, PartialEq)] pub struct SiteMapSegment { /// The type of the route segment. pub segment_type: SegmentType, /// The children of the route segment. pub children: &'static [SiteMapSegment], } impl SiteMapSegment { /// Take a map of the site structure and flatten it into a vector of routes. pub fn flatten(&self) -> Vec<Vec<SegmentType>> { let mut routes = Vec::new(); self.flatten_inner(&mut routes, Vec::new()); routes } fn flatten_inner(&self, routes: &mut Vec<Vec<SegmentType>>, current: Vec<SegmentType>) { let mut current = current; current.push(self.segment_type.clone()); if self.children.is_empty() { routes.push(current); } else { for child in self.children { child.flatten_inner(routes, current.clone()); } } } } /// The type of a route segment. #[derive(Debug, Clone, PartialEq)] #[non_exhaustive] pub enum SegmentType { /// A static route segment. Static(&'static str), /// A dynamic route segment. Dynamic(&'static str), /// A catch all route segment. CatchAll(&'static str), /// A child router. Child, } impl SegmentType { /// Try to convert this segment into a static segment. pub fn to_static(&self) -> Option<&'static str> { match self { SegmentType::Static(s) => Some(*s), _ => None, } } /// Try to convert this segment into a dynamic segment. pub fn to_dynamic(&self) -> Option<&'static str> { match self { SegmentType::Dynamic(s) => Some(*s), _ => None, } } /// Try to convert this segment into a catch all segment. pub fn to_catch_all(&self) -> Option<&'static str> { match self { SegmentType::CatchAll(s) => Some(*s), _ => None, } } /// Try to convert this segment into a child segment. pub fn to_child(&self) -> Option<()> { match self { SegmentType::Child => Some(()), _ => None, } } } impl Display for SegmentType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self { SegmentType::Static(s) => write!(f, "/{}", s), SegmentType::Child => Ok(()), SegmentType::Dynamic(s) => write!(f, "/:{}", s), SegmentType::CatchAll(s) => write!(f, "/:..{}", s), } } } // /// Routable is implemented for String to allow stringly-typed apps. // impl Routable for String { // const SITE_MAP: &'static [SiteMapSegment] = &[]; // #[doc = " Render the route at the given level"] // fn render(&self, _level: usize) -> Element { // unimplemented!("String routes cannot be rendered as components") // } // }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router/src/navigation.rs
packages/router/src/navigation.rs
//! Types pertaining to navigation. use std::{ fmt::{Debug, Display}, str::FromStr, }; use url::{ParseError, Url}; use crate::{ components::child_router::consume_child_route_mapping, hooks::try_router, routable::Routable, }; impl<R: Routable> From<R> for NavigationTarget { fn from(value: R) -> Self { // If this is a child route, map it to the root route first let mapping = consume_child_route_mapping(); match mapping.as_ref() { Some(mapping) => NavigationTarget::Internal(mapping.format_route_as_root_route(value)), // Otherwise, just use the internal route None => NavigationTarget::Internal(value.to_string()), } } } /// A target for the router to navigate to. #[derive(Clone, PartialEq, Eq, Debug)] pub enum NavigationTarget<R = String> { /// An internal path that the router can navigate to by itself. /// /// ```rust /// # use dioxus::prelude::*; /// # use dioxus_router::navigation::NavigationTarget; /// # #[component] /// # fn Index() -> Element { /// # unreachable!() /// # } /// #[derive(Clone, Routable, PartialEq, Debug)] /// enum Route { /// #[route("/")] /// Index {}, /// } /// let explicit = NavigationTarget::Internal(Route::Index {}); /// let implicit: NavigationTarget::<Route> = "/".parse().unwrap(); /// assert_eq!(explicit, implicit); /// ``` Internal(R), /// An external target that the router doesn't control. /// /// ```rust /// # use dioxus::prelude::*; /// # use dioxus_router::navigation::NavigationTarget; /// # #[component] /// # fn Index() -> Element { /// # unreachable!() /// # } /// #[derive(Clone, Routable, PartialEq, Debug)] /// enum Route { /// #[route("/")] /// Index {}, /// } /// let explicit = NavigationTarget::<Route>::External(String::from("https://dioxuslabs.com/")); /// let implicit: NavigationTarget::<Route> = "https://dioxuslabs.com/".parse().unwrap(); /// assert_eq!(explicit, implicit); /// ``` External(String), } impl<R: Routable> From<&str> for NavigationTarget<R> { fn from(value: &str) -> Self { value .parse() .unwrap_or_else(|_| Self::External(value.to_string())) } } impl<R: Routable> From<&String> for NavigationTarget<R> { fn from(value: &String) -> Self { value.as_str().into() } } impl<R: Routable> From<String> for NavigationTarget<R> { fn from(value: String) -> Self { value.as_str().into() } } impl<R: Routable> From<R> for NavigationTarget<R> { fn from(value: R) -> Self { Self::Internal(value) } } impl From<&str> for NavigationTarget { fn from(value: &str) -> Self { match try_router() { Some(router) => match router.internal_route(value) { true => NavigationTarget::Internal(value.to_string()), false => NavigationTarget::External(value.to_string()), }, None => NavigationTarget::External(value.to_string()), } } } impl From<String> for NavigationTarget { fn from(value: String) -> Self { match try_router() { Some(router) => match router.internal_route(&value) { true => NavigationTarget::Internal(value), false => NavigationTarget::External(value), }, None => NavigationTarget::External(value.to_string()), } } } impl<R: Routable> From<NavigationTarget<R>> for NavigationTarget { fn from(value: NavigationTarget<R>) -> Self { match value { NavigationTarget::Internal(r) => r.into(), NavigationTarget::External(s) => Self::External(s), } } } impl<R: Routable> Display for NavigationTarget<R> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { NavigationTarget::Internal(r) => write!(f, "{}", r), NavigationTarget::External(s) => write!(f, "{}", s), } } } /// An error that can occur when parsing a [`NavigationTarget`]. pub enum NavigationTargetParseError<R: Routable> { /// A URL that is not valid. InvalidUrl(ParseError), /// An internal URL that is not valid. InvalidInternalURL(<R as FromStr>::Err), } impl<R: Routable> Debug for NavigationTargetParseError<R> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { NavigationTargetParseError::InvalidUrl(e) => write!(f, "Invalid URL: {}", e), NavigationTargetParseError::InvalidInternalURL(_) => { write!(f, "Invalid internal URL") } } } } impl<R: Routable> FromStr for NavigationTarget<R> { type Err = NavigationTargetParseError<R>; fn from_str(s: &str) -> Result<Self, Self::Err> { match Url::parse(s) { Ok(_) => Ok(Self::External(s.to_string())), Err(ParseError::RelativeUrlWithoutBase) => { Ok(Self::Internal(R::from_str(s).map_err(|e| { NavigationTargetParseError::InvalidInternalURL(e) })?)) } Err(e) => Err(NavigationTargetParseError::InvalidUrl(e)), } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router/src/hooks/use_router.rs
packages/router/src/hooks/use_router.rs
use crate::{utils::use_router_internal::use_router_internal, RouterContext}; #[deprecated = "prefer the `router()` function or `use_route` functions"] #[must_use] /// A hook that provides access to information about the router. pub fn use_router() -> RouterContext { use_router_internal().expect("use_route must have access to a router") } /// Acquire the router without subscribing to updates. #[doc(alias = "url")] pub fn router() -> RouterContext { dioxus_core::consume_context() } /// Try to acquire the router without subscribing to updates. #[doc(alias = "url")] pub fn try_router() -> Option<RouterContext> { dioxus_core::try_consume_context() }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false
DioxusLabs/dioxus
https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/router/src/hooks/use_route.rs
packages/router/src/hooks/use_route.rs
use crate::utils::use_router_internal::use_router_internal; use crate::Routable; /// A hook that provides access to information about the current routing location. /// /// > The Routable macro will define a version of this hook with an explicit type. /// /// # Panic /// - When the calling component is not nested within a [`crate::Router`] component. /// /// # Example /// ```rust /// # use dioxus::prelude::*; /// /// #[derive(Clone, Routable)] /// enum Route { /// #[route("/")] /// Index {}, /// } /// /// #[component] /// fn App() -> Element { /// rsx! { /// h1 { "App" } /// Router::<Route> {} /// } /// } /// /// #[component] /// fn Index() -> Element { /// let path: Route = use_route(); /// rsx! { /// h2 { "Current Path" } /// p { "{path}" } /// } /// } /// # /// # let mut vdom = VirtualDom::new(App); /// # vdom.rebuild_in_place(); /// # assert_eq!(dioxus_ssr::render(&vdom), "<h1>App</h1><h2>Current Path</h2><p>/</p>") /// ``` #[doc(alias = "use_url")] #[must_use] pub fn use_route<R: Routable + Clone>() -> R { match use_router_internal() { Some(r) => r.current(), None => { panic!("`use_route` must be called in a descendant of a Router component") } } }
rust
Apache-2.0
ec8f31dece5c75371177bf080bab46dff54ffd0e
2026-01-04T15:32:28.012891Z
false