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/document/src/elements/meta.rs | packages/document/src/elements/meta.rs | use super::*;
use crate::document;
use dioxus_core::{use_hook, VNode};
use dioxus_html as dioxus_elements;
#[non_exhaustive]
/// Props for the [`Meta`] component
#[derive(Clone, Props, PartialEq)]
pub struct MetaProps {
pub property: Option<String>,
pub name: Option<String>,
pub charset: Option<String>,
pub http_equiv: Option<String>,
pub content: Option<String>,
pub data: Option<String>,
#[props(extends = meta, extends = GlobalAttributes)]
pub additional_attributes: Vec<Attribute>,
}
impl MetaProps {
/// Get all the attributes for the meta tag
pub fn attributes(&self) -> Vec<(&'static str, String)> {
let mut attributes = Vec::new();
extend_attributes(&mut attributes, &self.additional_attributes);
if let Some(property) = &self.property {
attributes.push(("property", property.clone()));
}
if let Some(name) = &self.name {
attributes.push(("name", name.clone()));
}
if let Some(charset) = &self.charset {
attributes.push(("charset", charset.clone()));
}
if let Some(http_equiv) = &self.http_equiv {
attributes.push(("http-equiv", http_equiv.clone()));
}
if let Some(content) = &self.content {
attributes.push(("content", content.clone()));
}
if let Some(data) = &self.data {
attributes.push(("data", data.clone()));
}
attributes
}
}
/// Render a [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/meta) tag into the head of the page.
///
/// # Example
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// fn RedirectToDioxusHomepageWithoutJS() -> Element {
/// rsx! {
/// // You can use the meta component to render a meta tag into the head of the page
/// // This meta tag will redirect the user to the dioxuslabs homepage in 10 seconds
/// document::Meta {
/// http_equiv: "refresh",
/// content: "10;url=https://dioxuslabs.com",
/// }
/// }
/// }
/// ```
///
/// <div class="warning">
///
/// Any updates to the props after the first render will not be reflected in the head.
///
/// </div>
#[component]
#[doc(alias = "<meta>")]
pub fn Meta(props: MetaProps) -> Element {
use_update_warning(&props, "Meta {}");
use_hook(|| {
let document = document();
let insert_link = document.create_head_component();
if !insert_link {
return;
}
document.create_meta(props);
});
VNode::empty()
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/document/src/elements/script.rs | packages/document/src/elements/script.rs | use super::*;
use crate::document;
use dioxus_core::{use_hook, VNode};
use dioxus_html as dioxus_elements;
#[non_exhaustive]
#[derive(Clone, Props, PartialEq)]
pub struct ScriptProps {
/// The contents of the script tag. If present, the children must be a single text node.
pub children: Element,
/// Scripts are deduplicated by their src attribute
pub src: Option<String>,
pub defer: Option<bool>,
pub crossorigin: Option<String>,
pub fetchpriority: Option<String>,
pub integrity: Option<String>,
pub nomodule: Option<bool>,
pub nonce: Option<String>,
pub referrerpolicy: Option<String>,
pub r#type: Option<String>,
#[props(extends = script, extends = GlobalAttributes)]
pub additional_attributes: Vec<Attribute>,
}
impl ScriptProps {
/// Get all the attributes for the script tag
pub fn attributes(&self) -> Vec<(&'static str, String)> {
let mut attributes = Vec::new();
extend_attributes(&mut attributes, &self.additional_attributes);
if let Some(defer) = &self.defer {
attributes.push(("defer", defer.to_string()));
}
if let Some(crossorigin) = &self.crossorigin {
attributes.push(("crossorigin", crossorigin.clone()));
}
if let Some(fetchpriority) = &self.fetchpriority {
attributes.push(("fetchpriority", fetchpriority.clone()));
}
if let Some(integrity) = &self.integrity {
attributes.push(("integrity", integrity.clone()));
}
if let Some(nomodule) = &self.nomodule {
attributes.push(("nomodule", nomodule.to_string()));
}
if let Some(nonce) = &self.nonce {
attributes.push(("nonce", nonce.clone()));
}
if let Some(referrerpolicy) = &self.referrerpolicy {
attributes.push(("referrerpolicy", referrerpolicy.clone()));
}
if let Some(r#type) = &self.r#type {
attributes.push(("type", r#type.clone()));
}
if let Some(src) = &self.src {
attributes.push(("src", src.clone()));
}
attributes
}
pub fn script_contents(&self) -> Result<String, ExtractSingleTextNodeError<'_>> {
extract_single_text_node(&self.children)
}
}
/// Render a [`<script>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script) tag into the head of the page.
///
///
/// If present, the children of the script component must be a single static or formatted string. If there are more children or the children contain components, conditionals, loops, or fragments, the script will not be added.
///
///
/// Any scripts you add will be deduplicated by their `src` attribute (if present).
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// fn LoadScript() -> Element {
/// rsx! {
/// // You can use the Script component to render a script tag into the head of the page
/// document::Script {
/// src: asset!("/assets/script.js"),
/// }
/// }
/// }
/// ```
///
/// <div class="warning">
///
/// Any updates to the props after the first render will not be reflected in the head.
///
/// </div>
#[component]
pub fn Script(props: ScriptProps) -> Element {
use_update_warning(&props, "Script {}");
use_hook(|| {
let document = document();
let mut insert_script = document.create_head_component();
if let Some(src) = &props.src {
if !should_insert_script(src) {
insert_script = false;
}
}
if !insert_script {
return;
}
// Make sure the props are in a valid form - they must either have a source or children
if let (None, Err(err)) = (&props.src, props.script_contents()) {
// If the script has neither contents nor src, log an error
err.log("Script")
}
document.create_script(props);
});
VNode::empty()
}
#[derive(Default, Clone)]
struct ScriptContext(DeduplicationContext);
fn should_insert_script(src: &str) -> bool {
get_or_insert_root_context::<ScriptContext>()
.0
.should_insert(src)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores-macro/src/lib.rs | packages/stores-macro/src/lib.rs | use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput, ItemImpl};
use crate::extend::ExtendArgs;
mod derive;
mod extend;
/// # `derive(Store)`
///
/// The `Store` macro is used to create an extension trait for stores that makes it possible to access the fields or variants
/// of an item as stores.
///
/// ## Expansion
///
/// The macro expands to two different items:
/// - An extension trait which is implemented for `Store<YourType, W>` with methods to access fields and variants for your type.
/// - A transposed version of your type which contains the fields or variants as stores.
///
/// ### Structs
///
/// For structs, the store macro generates methods for each field that returns a store scoped to that field and a `transpose` method that returns a struct with all fields as stores:
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_stores::*;
///
/// #[derive(Store)]
/// struct TodoItem {
/// checked: bool,
/// contents: String,
/// }
///
/// let store = use_store(|| TodoItem {
/// checked: false,
/// contents: "Learn about stores".to_string(),
/// });
///
/// // The store macro creates an extension trait with methods for each field
/// // that returns a store scoped to that field.
/// let checked: Store<bool, _> = store.checked();
/// let contents: Store<String, _> = store.contents();
///
/// // It also generates a `transpose` method returns a variant of your structure
/// // with stores wrapping each of your data types. This can be very useful when destructuring
/// // or matching your type
/// let TodoItemStoreTransposed { checked, contents } = store.transpose();
/// let checked: bool = checked();
/// let contents: String = contents();
/// ```
///
///
/// ### Enums
///
/// For enums, the store macro generates methods for each variant that checks if the store is that variant. It also generates a `transpose` method that returns an enum with all fields as stores.
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_stores::*;
///
/// #[derive(Store, PartialEq, Clone, Debug)]
/// enum Enum {
/// Foo(String),
/// Bar { foo: i32, bar: String },
/// }
///
/// let store = use_store(|| Enum::Foo("Hello".to_string()));
/// // The store macro creates an extension trait with methods for each variant to check
/// // if the store is that variant.
/// let foo: bool = store.is_foo();
/// let bar: bool = store.is_bar();
///
/// // If there is only one field in the variant, it also generates a method to try
/// // to downcast the store to that variant.
/// let foo: Option<Store<String, _>> = store.foo();
/// if let Some(foo) = foo {
/// println!("Foo: {foo}");
/// }
///
/// // It also generates a `transpose` method that returns a variant of your enum where all
/// // the fields are stores. You can use this to match your enum
/// let transposed = store.transpose();
/// use EnumStoreTransposed::*;
/// match transposed {
/// EnumStoreTransposed::Foo(foo) => println!("Foo: {foo}"),
/// EnumStoreTransposed::Bar { foo, bar } => {
/// let foo: i32 = foo();
/// let bar: String = bar();
/// println!("Bar: foo = {foo}, bar = {bar}");
/// }
/// }
/// ```
#[proc_macro_derive(Store)]
pub fn derive_store(input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let input = parse_macro_input!(input as DeriveInput);
let expanded = match derive::derive_store(input) {
Ok(tokens) => tokens,
Err(err) => {
// If there was an error, return it as a compile error
return err.to_compile_error().into();
}
};
// Hand the output tokens back to the compiler
TokenStream::from(expanded)
}
/// # `#[store]`
///
/// The `store` attribute macro is used to create an extension trait for store implementations. The extension traits lets you add
/// methods to the store even though the type is not defined in your crate.
///
/// ## Arguments
///
/// - `pub`: Makes the generated extension trait public. If not provided, the trait will be private.
/// - `name = YourExtensionName`: The name of the extension trait. If not provided, it will be generated based on the type name.
///
/// ## Bounds
///
/// The generated extension trait will have bounds on the lens generic parameter to ensure it implements `Readable` or `Writable` as needed.
///
/// - If a method accepts `&self`, the lens will require `Readable` which lets you read the value of the store.
/// - If a method accepts `&mut self`, the lens will require `Writable` which lets you change the value of the store.
///
/// ## Example
///
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_stores::*;
///
/// #[derive(Store)]
/// struct TodoItem {
/// checked: bool,
/// contents: String,
/// }
///
/// // You can use the store attribute macro to add methods to your stores
/// #[store]
/// impl<Lens> Store<TodoItem, Lens> {
/// // Since this method takes &mut self, the lens will require Writable automatically. It cannot be used
/// // with ReadStore<TodoItem>
/// fn toggle_checked(&mut self) {
/// self.checked().toggle();
/// }
///
/// // Since this method takes &self, the lens will require Readable automatically
/// fn checked_contents(&self) -> Option<String> {
/// self.checked().cloned().then(|| self.contents().to_string())
/// }
/// }
///
/// let mut store = use_store(|| TodoItem {
/// checked: false,
/// contents: "Learn about stores".to_string(),
/// });
///
/// // You can use the methods defined in the extension trait
/// store.toggle_checked();
/// let contents: Option<String> = store.checked_contents();
/// ```
#[proc_macro_attribute]
pub fn store(args: TokenStream, input: TokenStream) -> TokenStream {
// Parse the input tokens into a syntax tree
let args = parse_macro_input!(args as ExtendArgs);
let input = parse_macro_input!(input as ItemImpl);
let expanded = match extend::extend_store(args, input) {
Ok(tokens) => tokens,
Err(err) => {
// If there was an error, return it as a compile error
return err.to_compile_error().into();
}
};
// Hand the output tokens back to the compiler
TokenStream::from(expanded)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores-macro/src/extend.rs | packages/stores-macro/src/extend.rs | use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::Parse;
use syn::spanned::Spanned;
use syn::{
parse_quote, Ident, ImplItem, ImplItemConst, ImplItemType, ItemImpl, PathArguments, Type,
WherePredicate,
};
pub(crate) fn extend_store(args: ExtendArgs, mut input: ItemImpl) -> syn::Result<TokenStream> {
// Extract the type name the store is generic over
let store_type = &*input.self_ty;
let store = parse_store_type(store_type)?;
let store_path = &store.store_path;
let item = store.store_generic;
let lens_generic = store.store_lens;
let visibility = args
.visibility
.unwrap_or_else(|| syn::Visibility::Inherited);
if input.trait_.is_some() {
return Err(syn::Error::new_spanned(
input.trait_.unwrap().1,
"The `store` attribute can only be used on `impl Store<T> { ... }` blocks, not trait implementations.",
));
}
let extension_name = match args.name {
Some(attr) => attr,
None => {
// Otherwise, generate a name based on the type name
let type_name = stringify_type(&item)?;
Ident::new(&format!("{}StoreImplExt", type_name), item.span())
}
};
// Go through each method in the impl block and add extra bounds to lens as needed
let immutable_bounds: WherePredicate = parse_quote!(#lens_generic: dioxus_stores::macro_helpers::dioxus_signals::Readable<Target = #item> + ::std::marker::Copy + 'static);
let mutable_bounds: WherePredicate = parse_quote!(#lens_generic: dioxus_stores::macro_helpers::dioxus_signals::Writable<Target = #item> + ::std::marker::Copy + 'static);
for item in &mut input.items {
let ImplItem::Fn(func) = item else {
continue; // Only process function items
};
// Only add bounds if the function has a self argument
let Some(receiver) = func.sig.inputs.iter().find_map(|arg| {
if let syn::FnArg::Receiver(receiver) = arg {
Some(receiver)
} else {
None
}
}) else {
continue;
};
let extra_bounds = match (&receiver.reference, &receiver.mutability) {
// The function takes &self
(Some(_), None) => &immutable_bounds,
// The function takes &mut self
(Some(_), Some(_)) => &mutable_bounds,
_ => {
// If the function doesn't take &self or &mut self, we don't need to add any bounds
continue;
}
};
func.sig
.generics
.make_where_clause()
.predicates
.push(extra_bounds.clone());
}
// Push a __Lens generic to the impl if it doesn't already exist
let contains_lens_generic = input.generics.params.iter().any(|param| {
if let syn::GenericParam::Type(ty) = param {
ty.ident == lens_generic
} else {
false
}
});
if !contains_lens_generic {
input
.generics
.params
.push(parse_quote!(#lens_generic: ::std::marker::Copy + 'static));
}
// quote as the trait definition
let trait_definition = impl_to_trait_body(&extension_name, &input, &visibility)?;
// Reformat the type to be generic over the lens
input.self_ty = Box::new(parse_quote!(#store_path<#item, #lens_generic>));
// Change the standalone impl block to a trait impl block
let (_, trait_generics, _) = input.generics.split_for_impl();
input.trait_ = Some((
None,
parse_quote!(#extension_name #trait_generics),
parse_quote!(for),
));
Ok(quote! {
#trait_definition
#input
})
}
fn stringify_type(ty: &Type) -> syn::Result<String> {
match ty {
Type::Array(type_array) => {
let elem = stringify_type(&type_array.elem)?;
Ok(format!("Array{elem}"))
}
Type::Slice(type_slice) => {
let elem = stringify_type(&type_slice.elem)?;
Ok(format!("Slice{elem}"))
}
Type::Paren(type_paren) => stringify_type(&type_paren.elem),
Type::Path(type_path) => {
let last_segment = type_path.path.segments.last().ok_or_else(|| {
syn::Error::new_spanned(type_path, "Type path must have at least one segment")
})?;
let ident = &last_segment.ident;
Ok(ident.to_string())
}
_ => Err(syn::Error::new_spanned(
ty,
"Unsupported type in store implementation",
)),
}
}
fn impl_to_trait_body(
trait_name: &Ident,
item: &ItemImpl,
visibility: &syn::Visibility,
) -> syn::Result<TokenStream> {
let ItemImpl {
attrs,
defaultness,
unsafety,
items,
..
} = item;
let generics = &item.generics;
let items = items
.iter()
.map(item_to_trait_definition)
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
#(#attrs)*
#visibility #defaultness #unsafety trait #trait_name #generics {
#(#items)*
}
})
}
fn item_to_trait_definition(item: &syn::ImplItem) -> syn::Result<proc_macro2::TokenStream> {
match item {
syn::ImplItem::Fn(func) => {
let sig = &func.sig;
Ok(quote! {
#sig;
})
}
syn::ImplItem::Const(impl_item_const) => {
let ImplItemConst {
attrs,
const_token,
ident,
generics,
colon_token,
ty,
semi_token,
..
} = impl_item_const;
Ok(quote! {
#(#attrs)*
#const_token #ident #generics #colon_token #ty #semi_token
})
}
syn::ImplItem::Type(impl_item_type) => {
let ImplItemType {
attrs,
type_token,
ident,
generics,
eq_token,
ty,
semi_token,
..
} = impl_item_type;
Ok(quote! {
#(#attrs)*
#type_token #ident #generics #eq_token #ty #semi_token
})
}
_ => Err(syn::Error::new_spanned(item, "Unsupported item type")),
}
}
fn argument_as_type(arg: &syn::GenericArgument) -> Option<Type> {
if let syn::GenericArgument::Type(ty) = arg {
Some(ty.clone())
} else {
None
}
}
struct StorePath {
store_path: syn::Path,
store_generic: syn::Type,
store_lens: syn::Ident,
}
fn parse_store_type(store_type: &Type) -> syn::Result<StorePath> {
if let Type::Path(type_path) = store_type {
if let Some(segment) = type_path.path.segments.last() {
if let PathArguments::AngleBracketed(args) = &segment.arguments {
if let Some(store_generics) = args.args.first().and_then(argument_as_type) {
let store_lens = args
.args
.iter()
.nth(1)
.and_then(argument_as_type)
.unwrap_or_else(|| parse_quote!(__Lens));
let store_lens = parse_quote!(#store_lens);
let mut path_without_generics = type_path.path.clone();
for segment in &mut path_without_generics.segments {
segment.arguments = PathArguments::None;
}
return Ok(StorePath {
store_path: path_without_generics,
store_generic: store_generics,
store_lens,
});
}
}
}
}
Err(syn::Error::new_spanned(
store_type,
"The implementation must be in the form `impl Store<T> {...}`",
))
}
/// The args the `#[store]` attribute macro accepts
pub(crate) struct ExtendArgs {
/// The name of the extension trait generated
name: Option<Ident>,
/// The visibility of the extension trait
visibility: Option<syn::Visibility>,
}
impl Parse for ExtendArgs {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
// Try to parse visibility if it exists
let visibility = if input.peek(syn::Token![pub]) {
let vis: syn::Visibility = input.parse()?;
Some(vis)
} else {
None
};
// Try to parse name = ident if it exists
let name = if input.peek(Ident) && input.peek2(syn::Token![=]) {
let ident: Ident = input.parse()?;
if ident != "name" {
return Err(syn::Error::new_spanned(ident, "Expected `name` argument"));
}
let _eq_token: syn::Token![=] = input.parse()?;
let ident: Ident = input.parse()?;
Some(ident)
} else {
None
};
Ok(ExtendArgs { name, visibility })
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores-macro/src/derive.rs | packages/stores-macro/src/derive.rs | use convert_case::{Case, Casing};
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote, ToTokens};
use syn::{
parse_quote, spanned::Spanned, DataEnum, DataStruct, DeriveInput, Field, Fields, Generics,
Ident, Index, LitInt,
};
pub(crate) fn derive_store(input: DeriveInput) -> syn::Result<TokenStream2> {
let item_name = &input.ident;
let extension_trait_name = format_ident!("{}StoreExt", item_name);
let transposed_name = format_ident!("{}StoreTransposed", item_name);
// Create generics for the extension trait and transposed struct. Both items need the original generics
// and bounds plus an extra __Lens type used in the store generics
let generics = &input.generics;
let mut extension_generics = generics.clone();
extension_generics.params.insert(0, parse_quote!(__Lens));
match &input.data {
syn::Data::Struct(data_struct) => derive_store_struct(
&input,
data_struct,
extension_trait_name,
transposed_name,
extension_generics,
),
syn::Data::Enum(data_enum) => derive_store_enum(
&input,
data_enum,
extension_trait_name,
transposed_name,
extension_generics,
),
syn::Data::Union(_) => Err(syn::Error::new(
input.span(),
"Store macro does not support unions",
)),
}
}
// For structs, we derive two items:
// - An extension trait with methods to access the fields of the struct as stores and a `transpose` method
// - A transposed version of the struct with all fields wrapped in stores
fn derive_store_struct(
input: &DeriveInput,
structure: &DataStruct,
extension_trait_name: Ident,
transposed_name: Ident,
extension_generics: Generics,
) -> syn::Result<TokenStream2> {
let struct_name = &input.ident;
let fields = &structure.fields;
let visibility = &input.vis;
// We don't need to do anything if there are no fields
if fields.is_empty() {
return Ok(quote! {});
}
let generics = &input.generics;
let (_, ty_generics, _) = generics.split_for_impl();
let (extension_impl_generics, extension_ty_generics, extension_where_clause) =
extension_generics.split_for_impl();
// We collect the definitions and implementations for the extension trait methods along with the types of the fields in the transposed struct
let mut implementations = Vec::new();
let mut definitions = Vec::new();
let mut transposed_fields = Vec::new();
for (field_index, field) in fields.iter().enumerate() {
generate_field_methods(
field_index,
field,
struct_name,
&ty_generics,
&mut transposed_fields,
&mut definitions,
&mut implementations,
);
}
// Add a transpose method to turn the stored struct into a struct with all fields as stores
// We need the copy bound here because the store will be copied into the selector for each field
let definition = quote! {
fn transpose(
self,
) -> #transposed_name #extension_ty_generics where Self: ::std::marker::Copy;
};
definitions.push(definition);
let field_names = fields
.iter()
.enumerate()
.map(|(i, field)| function_name_from_field(i, field))
.collect::<Vec<_>>();
// Construct the transposed struct with the fields as stores from the field variables in scope
let construct = match &structure.fields {
Fields::Named(_) => {
quote! { #transposed_name { #(#field_names),* } }
}
Fields::Unnamed(_) => {
quote! { #transposed_name(#(#field_names),*) }
}
Fields::Unit => {
quote! { #transposed_name }
}
};
let implementation = quote! {
fn transpose(
self,
) -> #transposed_name #extension_ty_generics where Self: ::std::marker::Copy {
// Convert each field into the corresponding store
#(
let #field_names = self.#field_names();
)*
#construct
}
};
implementations.push(implementation);
// Generate the transposed struct definition
let transposed_struct = transposed_struct(
visibility,
struct_name,
&transposed_name,
structure,
generics,
&extension_generics,
&transposed_fields,
);
// Expand to the extension trait and its implementation for the store alongside the transposed struct
Ok(quote! {
#visibility trait #extension_trait_name #extension_impl_generics #extension_where_clause {
#(
#definitions
)*
}
impl #extension_impl_generics #extension_trait_name #extension_ty_generics for dioxus_stores::Store<#struct_name #ty_generics, __Lens> #extension_where_clause {
#(
#implementations
)*
}
#transposed_struct
})
}
fn field_type_generic(field: &Field, generics: &syn::Generics) -> bool {
generics.type_params().any(|param| {
matches!(&field.ty, syn::Type::Path(type_path) if type_path.path.is_ident(¶m.ident))
})
}
fn transposed_struct(
visibility: &syn::Visibility,
struct_name: &Ident,
transposed_name: &Ident,
structure: &DataStruct,
generics: &syn::Generics,
extension_generics: &syn::Generics,
transposed_fields: &[TokenStream2],
) -> TokenStream2 {
let (extension_impl_generics, _, extension_where_clause) = extension_generics.split_for_impl();
// Only use a type alias if:
// - There are no bounds on the type generics
// - All fields are generic types
let use_type_alias = generics.type_params().all(|param| param.bounds.is_empty())
&& structure
.fields
.iter()
.all(|field| field_type_generic(field, generics));
if use_type_alias {
let generics = transpose_generics(struct_name, generics);
return quote! {#visibility type #transposed_name #extension_impl_generics = #struct_name #generics;};
}
match &structure.fields {
Fields::Named(fields) => {
let fields = fields.named.iter();
let fields = fields.zip(transposed_fields.iter()).map(|(f, t)| {
let vis = &f.vis;
let ident = &f.ident;
let colon = f.colon_token.as_ref();
quote! { #vis #ident #colon #t }
});
quote! {
#visibility struct #transposed_name #extension_impl_generics #extension_where_clause {
#(
#fields
),*
}
}
}
Fields::Unnamed(fields) => {
let fields = fields.unnamed.iter();
let fields = fields.zip(transposed_fields.iter()).map(|(f, t)| {
let vis = &f.vis;
quote! { #vis #t }
});
quote! {
#visibility struct #transposed_name #extension_impl_generics (
#(
#fields
),*
)
#extension_where_clause;
}
}
Fields::Unit => {
quote! {#visibility struct #transposed_name #extension_impl_generics #extension_where_clause}
}
}
}
fn generate_field_methods(
field_index: usize,
field: &syn::Field,
struct_name: &Ident,
ty_generics: &syn::TypeGenerics,
transposed_fields: &mut Vec<TokenStream2>,
definitions: &mut Vec<TokenStream2>,
implementations: &mut Vec<TokenStream2>,
) {
let field_name = &field.ident;
// When we map the field, we need to use either the field name for named fields or the index for unnamed fields.
let field_accessor = field_name.as_ref().map_or_else(
|| Index::from(field_index).to_token_stream(),
|name| name.to_token_stream(),
);
let function_name = function_name_from_field(field_index, field);
let field_type = &field.ty;
let store_type = mapped_type(struct_name, ty_generics, field_type);
transposed_fields.push(store_type.clone());
// Each field gets its own reactive scope within the child based on the field's index
let ordinal = LitInt::new(&field_index.to_string(), field.span());
let definition = quote! {
fn #function_name(
self,
) -> #store_type;
};
definitions.push(definition);
let implementation = quote! {
fn #function_name(
self,
) -> #store_type {
let __map_field: fn(&#struct_name #ty_generics) -> &#field_type = |value| &value.#field_accessor;
let __map_mut_field: fn(&mut #struct_name #ty_generics) -> &mut #field_type = |value| &mut value.#field_accessor;
// Map the field into a child selector that tracks the field
let scope = self.into_selector().child(
#ordinal,
__map_field,
__map_mut_field,
);
// Convert the selector into a store
::std::convert::Into::into(scope)
}
};
implementations.push(implementation);
}
// For enums, we derive two items:
// - An extension trait with methods to check if the store is a specific variant and a method
// to access the field of that variant if there is only one field
// - A transposed version of the enum with all fields wrapped in stores
fn derive_store_enum(
input: &DeriveInput,
structure: &DataEnum,
extension_trait_name: Ident,
transposed_name: Ident,
extension_generics: Generics,
) -> syn::Result<TokenStream2> {
let enum_name = &input.ident;
let variants = &structure.variants;
let visibility = &input.vis;
let generics = &input.generics;
let (_, ty_generics, _) = generics.split_for_impl();
let (extension_impl_generics, extension_ty_generics, extension_where_clause) =
extension_generics.split_for_impl();
// We collect the definitions and implementations for the extension trait methods along with the types of the fields in the transposed enum
// and the match arms for the transposed enum.
let mut implementations = Vec::new();
let mut definitions = Vec::new();
let mut transposed_variants = Vec::new();
let mut transposed_match_arms = Vec::new();
// The generated items that check the variant of the enum need to read the enum which requires these extra bounds
let readable_bounds = quote! { __Lens: dioxus_stores::macro_helpers::dioxus_signals::Readable<Target = #enum_name #ty_generics>, #enum_name #ty_generics: 'static };
for variant in variants {
let variant_name = &variant.ident;
let snake_case_variant = format_ident!("{}", variant_name.to_string().to_case(Case::Snake));
let is_fn = format_ident!("is_{}", snake_case_variant);
generate_is_variant_method(
&is_fn,
variant_name,
enum_name,
readable_bounds.clone(),
&mut definitions,
&mut implementations,
);
let mut transposed_fields = Vec::new();
let mut transposed_field_selectors = Vec::new();
let fields = &variant.fields;
for (i, field) in fields.iter().enumerate() {
let field_type = &field.ty;
let store_type = mapped_type(enum_name, &ty_generics, field_type);
// Push the field for the transposed enum
transposed_fields.push(store_type.clone());
// Generate the code to get Store<Field, W> from the enum
let select_field = select_enum_variant_field(
enum_name,
&ty_generics,
variant_name,
field,
i,
fields.len(),
);
// If there is only one field, generate a field() -> Option<Store<O, W>> method
if fields.len() == 1 {
generate_as_variant_method(
&is_fn,
&snake_case_variant,
&select_field,
&store_type,
&readable_bounds,
&mut definitions,
&mut implementations,
);
}
transposed_field_selectors.push(select_field);
}
// Now that we have the types for the field selectors within the variant,
// we can construct the transposed variant and the logic to turn the normal
// version of that variant into the store version
let field_names = fields
.iter()
.enumerate()
.map(|(i, field)| function_name_from_field(i, field))
.collect::<Vec<_>>();
// Turn each field into its store
let construct_fields = field_names
.iter()
.zip(transposed_field_selectors.iter())
.map(|(name, selector)| {
quote! { let #name = { #selector }; }
});
// Merge the stores into the variant
let construct_variant = match &fields {
Fields::Named(_) => {
quote! { #transposed_name::#variant_name { #(#field_names),* } }
}
Fields::Unnamed(_) => {
quote! { #transposed_name::#variant_name(#(#field_names),*) }
}
Fields::Unit => {
quote! { #transposed_name::#variant_name }
}
};
let match_arm = quote! {
#enum_name::#variant_name { .. } => {
#(#construct_fields)*
#construct_variant
},
};
transposed_match_arms.push(match_arm);
// Push the type definition of the variant to the transposed enum
let transposed_variant = match &fields {
Fields::Named(named) => {
let fields = named.named.iter();
let fields = fields.zip(transposed_fields.iter()).map(|(f, t)| {
let vis = &f.vis;
let ident = &f.ident;
let colon = f.colon_token.as_ref();
quote! { #vis #ident #colon #t }
});
quote! { #variant_name {
#(
#fields
),*
} }
}
Fields::Unnamed(unnamed) => {
let fields = unnamed.unnamed.iter();
let fields = fields.zip(transposed_fields.iter()).map(|(f, t)| {
let vis = &f.vis;
quote! { #vis #t }
});
quote! { #variant_name (
#(
#fields
),*
) }
}
Fields::Unit => {
quote! { #variant_name }
}
};
transposed_variants.push(transposed_variant);
}
let definition = quote! {
fn transpose(
self,
) -> #transposed_name #extension_ty_generics where #readable_bounds, Self: ::std::marker::Copy;
};
definitions.push(definition);
let implementation = quote! {
fn transpose(
self,
) -> #transposed_name #extension_ty_generics where #readable_bounds, Self: ::std::marker::Copy {
// We only do a shallow read of the store to get the current variant. We only need to rerun
// this match when the variant changes, not when the fields change
self.selector().track_shallow();
let read = dioxus_stores::macro_helpers::dioxus_signals::ReadableExt::peek(self.selector());
match &*read {
#(#transposed_match_arms)*
// The enum may be #[non_exhaustive]
#[allow(unreachable)]
_ => unreachable!(),
}
}
};
implementations.push(implementation);
// Only use a type alias if:
// - There are no bounds on the type generics
// - All fields are generic types
let use_type_alias = generics.type_params().all(|param| param.bounds.is_empty())
&& structure
.variants
.iter()
.flat_map(|variant| variant.fields.iter())
.all(|field| field_type_generic(field, generics));
let transposed_enum = if use_type_alias {
let generics = transpose_generics(enum_name, generics);
quote! {#visibility type #transposed_name #extension_generics = #enum_name #generics;}
} else {
quote! { #visibility enum #transposed_name #extension_impl_generics #extension_where_clause {#(#transposed_variants),*} }
};
// Expand to the extension trait and its implementation for the store alongside the transposed enum
Ok(quote! {
#visibility trait #extension_trait_name #extension_impl_generics #extension_where_clause {
#(
#definitions
)*
}
impl #extension_impl_generics #extension_trait_name #extension_ty_generics for dioxus_stores::Store<#enum_name #ty_generics, __Lens> #extension_where_clause {
#(
#implementations
)*
}
#transposed_enum
})
}
fn generate_is_variant_method(
is_fn: &Ident,
variant_name: &Ident,
enum_name: &Ident,
readable_bounds: TokenStream2,
definitions: &mut Vec<TokenStream2>,
implementations: &mut Vec<TokenStream2>,
) {
// Generate a is_variant method that checks if the store is a specific variant
let definition = quote! {
fn #is_fn(
&self,
) -> bool where #readable_bounds;
};
definitions.push(definition);
let implementation = quote! {
fn #is_fn(
&self,
) -> bool where #readable_bounds {
// Reading the current variant only tracks the shallow value of the store. Writing to a specific
// variant will not cause the variant to change, so we don't need to subscribe deeply
self.selector().track_shallow();
let ref_self = dioxus_stores::macro_helpers::dioxus_signals::ReadableExt::peek(self.selector());
matches!(&*ref_self, #enum_name::#variant_name { .. })
}
};
implementations.push(implementation);
}
/// Generate a method to turn Store<Enum, W> into Option<Store<VariantField, W>> if the variant only has one field.
fn generate_as_variant_method(
is_fn: &Ident,
snake_case_variant: &Ident,
select_field: &TokenStream2,
store_type: &TokenStream2,
readable_bounds: &TokenStream2,
definitions: &mut Vec<TokenStream2>,
implementations: &mut Vec<TokenStream2>,
) {
let definition = quote! {
fn #snake_case_variant(
self,
) -> Option<#store_type> where #readable_bounds;
};
definitions.push(definition);
let implementation = quote! {
fn #snake_case_variant(
self,
) -> Option<#store_type> where #readable_bounds {
self.#is_fn().then(|| {
#select_field
})
}
};
implementations.push(implementation);
}
fn select_enum_variant_field(
enum_name: &Ident,
ty_generics: &syn::TypeGenerics,
variant_name: &Ident,
field: &Field,
field_index: usize,
field_count: usize,
) -> TokenStream2 {
// Generate the match arm for the field
let function_name = function_name_from_field(field_index, field);
let field_type = &field.ty;
let match_field = if field.ident.is_none() {
let ignore_before = (0..field_index).map(|_| quote!(_));
let ignore_after = (field_index + 1..field_count).map(|_| quote!(_));
quote!( ( #(#ignore_before,)* #function_name, #(#ignore_after),* ) )
} else {
quote!( { #function_name, .. })
};
let ordinal = LitInt::new(&field_index.to_string(), variant_name.span());
quote! {
let __map_field: fn(&#enum_name #ty_generics) -> &#field_type = |value| match value {
#enum_name::#variant_name #match_field => #function_name,
_ => panic!("Selector that was created to match {} read after variant changed", stringify!(#variant_name)),
};
let __map_mut_field: fn(&mut #enum_name #ty_generics) -> &mut #field_type = |value| match value {
#enum_name::#variant_name #match_field => #function_name,
_ => panic!("Selector that was created to match {} written after variant changed", stringify!(#variant_name)),
};
// Each field within the variant gets its own reactive scope. Writing to one field will not notify the enum or
// other fields
let scope = self.into_selector().child(
#ordinal,
__map_field,
__map_mut_field,
);
::std::convert::Into::into(scope)
}
}
fn function_name_from_field(index: usize, field: &syn::Field) -> Ident {
// Generate a function name from the field's identifier or index
field
.ident
.as_ref()
.map_or_else(|| format_ident!("field_{index}"), |name| name.clone())
}
fn mapped_type(
item: &Ident,
ty_generics: &syn::TypeGenerics,
field_type: &syn::Type,
) -> TokenStream2 {
// The zoomed in store type is a MappedMutSignal with function pointers to map the reference to the enum into a reference to the field
let write_type = quote! { dioxus_stores::macro_helpers::dioxus_signals::MappedMutSignal<#field_type, __Lens, fn(&#item #ty_generics) -> &#field_type, fn(&mut #item #ty_generics) -> &mut #field_type> };
quote! { dioxus_stores::Store<#field_type, #write_type> }
}
/// Take the generics from the original type with only generic fields into the generics for the transposed type
fn transpose_generics(name: &Ident, generics: &syn::Generics) -> TokenStream2 {
let (_, ty_generics, _) = generics.split_for_impl();
let mut transposed_generics = generics.clone();
let mut generics = Vec::new();
for gen in transposed_generics.params.iter_mut() {
match gen {
// Map type generics into Store<Type, MappedMutSignal<...>>
syn::GenericParam::Type(type_param) => {
let ident = &type_param.ident;
let ty = mapped_type(name, &ty_generics, &parse_quote!(#ident));
generics.push(ty);
}
// Forward const and lifetime generics as-is
syn::GenericParam::Const(const_param) => {
let ident = &const_param.ident;
generics.push(quote! { #ident });
}
syn::GenericParam::Lifetime(lt_param) => {
let ident = <_param.lifetime;
generics.push(quote! { #ident });
}
}
}
quote!(<#(#generics),*> )
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-macro/src/lib.rs | packages/manganis/manganis-macro/src/lib.rs | #![doc = include_str!("../README.md")]
#![deny(missing_docs)]
use std::path::PathBuf;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{quote, ToTokens};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input, ItemStruct,
};
pub(crate) mod asset;
pub(crate) mod css_module;
pub(crate) mod linker;
use linker::generate_link_section;
use crate::css_module::{expand_css_module_struct, CssModuleAttribute};
/// The asset macro collects assets that will be included in the final binary
///
/// # Files
///
/// The file builder collects an arbitrary file. Relative paths are resolved relative to the package root
/// ```rust
/// # use manganis::{asset, Asset};
/// const _: Asset = asset!("/assets/asset.txt");
/// ```
/// Macros like `concat!` and `env!` are supported in the asset path.
/// ```rust
/// # use manganis::{asset, Asset};
/// const _: Asset = asset!(concat!("/assets/", env!("CARGO_CRATE_NAME"), ".dat"));
/// ```
///
/// # Images
///
/// You can collect images which will be automatically optimized with the image builder:
/// ```rust
/// # use manganis::{asset, Asset};
/// const _: Asset = asset!("/assets/image.png");
/// ```
/// Resize the image at compile time to make the assets file size smaller:
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageSize};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_size(ImageSize::Manual { width: 52, height: 52 }));
/// ```
/// Or convert the image at compile time to a web friendly format:
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageSize, ImageFormat};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_format(ImageFormat::Avif));
/// ```
/// You can mark images as preloaded to make them load faster in your app
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_preload(true));
/// ```
#[proc_macro]
pub fn asset(input: TokenStream) -> TokenStream {
let asset = parse_macro_input!(input as asset::AssetParser);
quote! { #asset }.into_token_stream().into()
}
/// Resolve an asset at compile time, returning `None` if the asset does not exist.
///
/// This behaves like the `asset!` macro when the asset can be resolved, but mirrors
/// [`option_env!`](core::option_env) by returning an `Option` instead of emitting a compile error
/// when the asset is missing.
///
/// ```rust
/// # use manganis::{asset, option_asset, Asset};
/// const REQUIRED: Asset = asset!("/assets/style.css");
/// const OPTIONAL: Option<Asset> = option_asset!("/assets/maybe.css");
/// ```
#[proc_macro]
pub fn option_asset(input: TokenStream) -> TokenStream {
let asset = parse_macro_input!(input as asset::AssetParser);
asset.expand_option_tokens().into()
}
/// Generate type-safe styles with scoped CSS class names.
///
/// The `css_module` attribute macro creates scoped CSS modules that prevent class name collisions
/// by making each class globally unique. It expands the annotated struct to provide type-safe
/// identifiers for your CSS classes, allowing you to reference styles in your Rust code with
/// compile-time guarantees.
///
/// # Syntax
///
/// The `css_module` attribute takes:
/// - The asset string path - the absolute path (from the crate root) to your CSS file.
/// - Optional `AssetOptions` to configure the processing of your CSS module.
///
/// It must be applied to a unit struct:
/// ```rust, ignore
/// #[css_module("/assets/my-styles.css")]
/// struct Styles;
///
/// #[css_module("/assets/my-styles.css", AssetOptions::css_module().with_minify(true))]
/// struct Styles;
/// ```
///
/// # Generation
///
/// The `css_module` attribute macro does two things:
/// - It generates an asset and automatically inserts it as a stylesheet link in the document.
/// - It expands the annotated struct with snake-case associated constants for your CSS class names.
///
/// ```rust, ignore
/// // This macro usage:
/// #[css_module("/assets/mycss.css")]
/// struct Styles;
///
/// // Will expand the struct to (simplified):
/// struct Styles {}
///
/// impl Styles {
/// // Snake-cased class names can be accessed like this:
/// pub const your_class: &str = "your_class-a1b2c3";
/// }
/// ```
///
/// # CSS Class Name Scoping
///
/// **The macro only processes CSS class selectors (`.class-name`).** Other selectors like IDs (`#id`),
/// element selectors (`div`, `p`), attribute selectors, etc. are left unchanged and not exposed as
/// Rust constants.
///
/// The macro collects all class selectors in your CSS file and transforms them to be globally unique
/// by appending a hash. For example, `.myClass` becomes `.myClass-a1b2c3` where `a1b2c3` is a hash
/// of the file path.
///
/// Class names are converted to snake_case for the Rust constants. For example:
/// - `.fooBar` becomes `Styles::foo_bar`
/// - `.my-class` becomes `Styles::my_class`
///
/// To prevent a class from being scoped, wrap it in `:global()`:
/// ```css
/// /* This class will be scoped */
/// .my-class { color: blue; }
///
/// /* This class will NOT be scoped (no hash added) */
/// :global(.global-class) { color: red; }
///
/// /* Element selectors and other CSS remain unchanged */
/// div { margin: 0; }
/// #my-id { padding: 10px; }
/// ```
///
/// # Using Multiple CSS Modules
///
/// Multiple `css_module` attributes can be used in the same scope by applying them to different structs:
/// ```rust, ignore
/// // First CSS module
/// #[css_module("/assets/styles1.css")]
/// struct Styles;
///
/// // Second CSS module with a different struct name
/// #[css_module("/assets/styles2.css")]
/// struct OtherStyles;
///
/// // Access classes from both:
/// rsx! {
/// div { class: Styles::container }
/// div { class: OtherStyles::button }
/// }
/// ```
///
/// # Asset Options
///
/// Similar to the `asset!()` macro, you can pass optional `AssetOptions` to configure processing:
/// ```rust, ignore
/// #[css_module(
/// "/assets/mycss.css",
/// AssetOptions::css_module()
/// .with_minify(true)
/// .with_preload(false)
/// )]
/// struct Styles;
/// ```
///
/// # Example
///
/// First create a CSS file:
/// ```css
/// /* assets/styles.css */
///
/// .container {
/// padding: 20px;
/// }
///
/// .button {
/// background-color: #373737;
/// }
///
/// :global(.global-text) {
/// font-weight: bold;
/// }
/// ```
///
/// Then use the `css_module` attribute:
/// ```rust, ignore
/// use dioxus::prelude::*;
///
/// fn app() -> Element {
/// #[css_module("/assets/styles.css")]
/// struct Styles;
///
/// rsx! {
/// div { class: Styles::container,
/// button { class: Styles::button, "Click me" }
/// span { class: Styles::global_text, "This uses global class" }
/// }
/// }
/// }
/// ```
#[proc_macro_attribute]
pub fn css_module(input: TokenStream, item: TokenStream) -> TokenStream {
let attribute = parse_macro_input!(input as CssModuleAttribute);
let item_struct = parse_macro_input!(item as ItemStruct);
let mut tokens = proc_macro2::TokenStream::new();
expand_css_module_struct(&mut tokens, &attribute, &item_struct);
tokens.into()
}
fn resolve_path(raw: &str, span: Span) -> Result<PathBuf, AssetParseError> {
// Get the location of the root of the crate which is where all assets are relative to
//
// IE
// /users/dioxus/dev/app/
// is the root of
// /users/dioxus/dev/app/assets/blah.css
let manifest_dir = dunce::canonicalize(
std::env::var("CARGO_MANIFEST_DIR")
.map(PathBuf::from)
.unwrap(),
)
.unwrap();
// 1. the input file should be a pathbuf
let input = PathBuf::from(raw);
let path = if raw.starts_with('.') {
if let Some(local_folder) = span.local_file().as_ref().and_then(|f| f.parent()) {
local_folder.join(raw)
} else {
// If we are running in rust analyzer, just assume the path is valid and return an error when
// we compile if it doesn't exist
if looks_like_rust_analyzer(&span) {
return Ok(
"The asset macro was expanded under Rust Analyzer which doesn't support paths or local assets yet"
.into(),
);
}
// Otherwise, return an error about the version of rust required for relative assets
return Err(AssetParseError::RelativeAssetPath);
}
} else {
manifest_dir.join(raw.trim_start_matches('/'))
};
// 2. absolute path to the asset
let Ok(path) = std::path::absolute(path) else {
return Err(AssetParseError::InvalidPath {
path: input.clone(),
});
};
// 3. Ensure the path exists
let Ok(path) = dunce::canonicalize(path) else {
return Err(AssetParseError::AssetDoesntExist {
path: input.clone(),
});
};
// 4. Ensure the path doesn't escape the crate dir
//
// - Note: since we called canonicalize on both paths, we can safely compare the parent dirs.
// On windows, we can only compare the prefix if both paths are canonicalized (not just absolute)
// https://github.com/rust-lang/rust/issues/42869
if path == manifest_dir || !path.starts_with(manifest_dir) {
return Err(AssetParseError::InvalidPath { path });
}
Ok(path)
}
/// Parse `T`, while also collecting the tokens it was parsed from.
fn parse_with_tokens<T: Parse>(input: ParseStream) -> syn::Result<(T, proc_macro2::TokenStream)> {
let begin = input.cursor();
let t: T = input.parse()?;
let end = input.cursor();
let mut cursor = begin;
let mut tokens = proc_macro2::TokenStream::new();
while cursor != end {
let (tt, next) = cursor.token_tree().unwrap();
tokens.extend(std::iter::once(tt));
cursor = next;
}
Ok((t, tokens))
}
#[derive(Debug)]
enum AssetParseError {
AssetDoesntExist { path: PathBuf },
InvalidPath { path: PathBuf },
RelativeAssetPath,
}
impl std::fmt::Display for AssetParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AssetParseError::AssetDoesntExist { path } => {
write!(f, "Asset at {} doesn't exist", path.display())
}
AssetParseError::InvalidPath { path } => {
write!(
f,
"Asset path {} is invalid. Make sure the asset exists within this crate.",
path.display()
)
}
AssetParseError::RelativeAssetPath => write!(f, "Failed to resolve relative asset path. Relative assets are only supported in rust 1.88+."),
}
}
}
/// Rust analyzer doesn't provide a stable way to detect if macros are running under it.
/// This function uses heuristics to determine if we are running under rust analyzer for better error
/// messages.
fn looks_like_rust_analyzer(span: &Span) -> bool {
// Rust analyzer spans have a struct debug impl compared to rustcs custom debug impl
// RA Example: SpanData { range: 45..58, anchor: SpanAnchor(EditionedFileId(0, Edition2024), ErasedFileAstId { kind: Fn, index: 0, hash: 9CD8 }), ctx: SyntaxContext(4294967036) }
// Rustc Example: #0 bytes(70..83)
let looks_like_rust_analyzer_span = format!("{:?}", span).contains("ctx:");
// The rust analyzer macro expander runs under RUST_ANALYZER_INTERNALS_DO_NOT_USE
let looks_like_rust_analyzer_env = std::env::var("RUST_ANALYZER_INTERNALS_DO_NOT_USE").is_ok();
// The rust analyzer executable is named rust-analyzer-proc-macro-srv
let looks_like_rust_analyzer_exe = std::env::current_exe().ok().is_some_and(|p| {
p.file_stem()
.and_then(|s| s.to_str())
.is_some_and(|s| s.contains("rust-analyzer"))
});
looks_like_rust_analyzer_span || looks_like_rust_analyzer_env || looks_like_rust_analyzer_exe
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-macro/src/css_module.rs | packages/manganis/manganis-macro/src/css_module.rs | use crate::{asset::AssetParser, resolve_path};
use macro_string::MacroString;
use manganis_core::{create_module_hash, get_class_mappings};
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream},
spanned::Spanned,
token::Comma,
Ident, ItemStruct,
};
pub(crate) struct CssModuleAttribute {
asset_parser: AssetParser,
}
impl Parse for CssModuleAttribute {
fn parse(input: ParseStream) -> syn::Result<Self> {
// Asset path "/path.css"
let (MacroString(src), path_expr) = input.call(crate::parse_with_tokens)?;
let asset = resolve_path(&src, path_expr.span());
let _comma = input.parse::<Comma>();
// Optional options
let mut options = input.parse::<TokenStream>()?;
if options.is_empty() {
options = quote! { manganis::AssetOptions::css_module() }
}
let asset_parser = AssetParser {
path_expr,
asset,
options,
};
Ok(Self { asset_parser })
}
}
pub(crate) fn expand_css_module_struct(
tokens: &mut proc_macro2::TokenStream,
attribute: &CssModuleAttribute,
item_struct: &ItemStruct,
) {
if !item_struct.fields.is_empty() {
let err = syn::Error::new(
item_struct.fields.span(),
"css_module can only be applied to unit structs",
)
.into_compile_error();
tokens.append_all(err);
return;
}
if !item_struct.generics.params.is_empty() {
let err = syn::Error::new(
item_struct.generics.span(),
"css_module cannot be applied to generic structs",
)
.into_compile_error();
tokens.append_all(err);
return;
}
let struct_vis = &item_struct.vis;
let struct_name = &item_struct.ident;
let struct_name_private = format_ident!("__{}", struct_name);
// Use the regular asset parser to generate the linker bridge.
let mut linker_tokens = quote! {
/// Auto-generated Manganis asset for css modules.
#[allow(missing_docs)]
const ASSET: manganis::Asset =
};
attribute.asset_parser.to_tokens(&mut linker_tokens);
let asset = match attribute.asset_parser.asset.as_ref() {
Ok(path) => path,
Err(err) => {
let err = err.to_string();
tokens.append_all(quote! { compile_error!(#err) });
return;
}
};
let css = std::fs::read_to_string(asset).expect("Unable to read css module file");
let mut values = Vec::new();
let hash = create_module_hash(asset);
let class_mappings = get_class_mappings(css.as_str(), hash.as_str()).expect("Invalid css");
// Generate class struct field tokens.
for (old_class, new_class) in class_mappings.iter() {
let as_snake = to_snake_case(old_class);
let ident = Ident::new(&as_snake, Span::call_site());
values.push(quote! {
pub const #ident: #struct_name_private::__CssIdent = #struct_name_private::__CssIdent { inner: #new_class };
});
}
// We use a PhantomData to prevent Rust from complaining about an unused lifetime if a css module without any idents is used.
tokens.extend(quote! {
#[doc(hidden)]
#[allow(missing_docs, non_snake_case)]
mod #struct_name_private {
use dioxus::prelude::*;
#linker_tokens;
// Css ident class for deref stylesheet inclusion.
pub struct __CssIdent { pub inner: &'static str }
use std::ops::Deref;
use std::sync::OnceLock;
use dioxus::document::{document, LinkProps};
impl Deref for __CssIdent {
type Target = str;
fn deref(&self) -> &Self::Target {
static CELL: OnceLock<()> = OnceLock::new();
CELL.get_or_init(move || {
let doc = document();
doc.create_link(
LinkProps::builder()
.rel(Some("stylesheet".to_string()))
.href(Some(ASSET.to_string()))
.build(),
);
});
self.inner
}
}
impl std::fmt::Display for __CssIdent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
self.deref().fmt(f)
}
}
}
/// Auto-generated idents struct for CSS modules.
#[allow(missing_docs, non_snake_case)]
#struct_vis struct #struct_name {}
impl #struct_name {
#( #values )*
}
impl dioxus::core::IntoAttributeValue for #struct_name_private::__CssIdent {
fn into_value(self) -> dioxus::core::AttributeValue {
dioxus::core::AttributeValue::Text(self.to_string())
}
}
})
}
/// Convert camel and kebab case to snake case.
///
/// This can fail sometimes, for example `myCss-Class`` is `my_css__class`
fn to_snake_case(input: &str) -> String {
let mut new = String::new();
for (i, c) in input.chars().enumerate() {
if c.is_uppercase() && i != 0 {
new.push('_');
}
new.push(c.to_ascii_lowercase());
}
new.replace('-', "_")
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-macro/src/asset.rs | packages/manganis/manganis-macro/src/asset.rs | use crate::{resolve_path, AssetParseError};
use macro_string::MacroString;
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, ToTokens};
use std::{
hash::{DefaultHasher, Hash, Hasher},
path::{Path, PathBuf},
};
use syn::{
parse::{Parse, ParseStream},
spanned::Spanned as _,
Token,
};
pub struct AssetParser {
/// The token(s) of the source string, for error reporting
pub(crate) path_expr: proc_macro2::TokenStream,
/// The asset itself
pub(crate) asset: Result<PathBuf, AssetParseError>,
/// The source of the trailing options
pub(crate) options: TokenStream2,
}
impl Parse for AssetParser {
// we can take
//
// This gives you the Asset type - it's generic and basically unrefined
// ```
// asset!("/assets/myfile.png")
// ```
//
// To narrow the type, use a method call to get the refined type
// ```
// asset!(
// "/assets/myfile.png",
// AssetOptions::image()
// .format(ImageFormat::Jpg)
// .size(512, 512)
// )
// ```
//
// But we need to decide the hint first before parsing the options
fn parse(input: ParseStream) -> syn::Result<Self> {
// And then parse the options
let (MacroString(src), path_expr) = input.call(crate::parse_with_tokens)?;
let asset = resolve_path(&src, path_expr.span());
let _comma = input.parse::<Token![,]>();
let options = input.parse()?;
Ok(Self {
path_expr,
asset,
options,
})
}
}
impl ToTokens for AssetParser {
// The manganis macro outputs info to two different places:
// 1) The crate the macro was invoked in
// - It needs the hashed contents of the file, the file path, and the file options
// - Most of this is just forwarding the input, the only thing that the macro needs to do is hash the file contents
// 2) A bundler that supports manganis (currently just dioxus-cli)
// - The macro needs to output the absolute path to the asset for the bundler to find later
// - It also needs to serialize the bundled asset along with the asset options for the bundler to use later
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
match self.asset.as_ref() {
Ok(asset) => tokens.extend(self.expand_asset_tokens(asset)),
Err(err) => tokens.extend(self.error_tokens(err)),
}
}
}
impl AssetParser {
pub(crate) fn expand_asset_tokens(&self, asset: &Path) -> proc_macro2::TokenStream {
let asset_string = asset.to_string_lossy();
let mut asset_str = proc_macro2::Literal::string(&asset_string);
asset_str.set_span(self.path_expr.span());
let mut hash = DefaultHasher::new();
format!("{:?}", self.options.span()).hash(&mut hash);
format!("{:?}", self.options.to_string()).hash(&mut hash);
asset_string.hash(&mut hash);
let asset_hash = format!("{:016x}", hash.finish());
// Generate the link section for the asset. The link section includes the source path and the
// output path of the asset. We force the asset to be included in the binary even if it is unused
// if the asset is unhashed
let link_section = crate::generate_link_section(quote!(__ASSET), &asset_hash);
// generate the asset::new method to deprecate the `./assets/blah.css` syntax
let constructor = if asset.is_relative() {
quote! { create_bundled_asset_relative }
} else {
quote! { create_bundled_asset }
};
let options = if self.options.is_empty() {
quote! { manganis::AssetOptions::builder() }
} else {
self.options.clone()
};
quote! {
{
// The source is used by the CLI to copy the asset
const __ASSET_SOURCE_PATH: &'static str = #asset_str;
// The options give the CLI info about how to process the asset
// Note: into_asset_options is not a trait, so we cannot accept the options directly
// in the constructor. Stable rust doesn't have support for constant functions in traits
const __ASSET_OPTIONS: manganis::AssetOptions = #options.into_asset_options();
// The input token hash is used to uniquely identify the link section for this asset
const __ASSET_HASH: &'static str = #asset_hash;
// Create the asset that the crate will use. This is used both in the return value and
// added to the linker for the bundler to copy later
const __ASSET: manganis::BundledAsset = manganis::macro_helpers::#constructor(__ASSET_SOURCE_PATH, __ASSET_OPTIONS);
#link_section
manganis::Asset::new(
|| unsafe { std::ptr::read_volatile(&__LINK_SECTION) },
|| unsafe { std::ptr::read_volatile(&__LEGACY_LINK_SECTION) }
)
}
}
}
pub(crate) fn expand_option_tokens(&self) -> proc_macro2::TokenStream {
match self.asset.as_ref() {
Ok(asset) => {
let asset_tokens = self.expand_asset_tokens(asset);
quote! { ::core::option::Option::Some(#asset_tokens) }
}
Err(AssetParseError::AssetDoesntExist { .. }) => {
quote! { ::core::option::Option::<manganis::Asset>::None }
}
Err(err) => self.error_tokens(err),
}
}
fn error_tokens(&self, err: &AssetParseError) -> proc_macro2::TokenStream {
let err = err.to_string();
quote! { compile_error!(#err) }
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-macro/src/linker.rs | packages/manganis/manganis-macro/src/linker.rs | use proc_macro2::TokenStream as TokenStream2;
use quote::ToTokens;
/// We store description of the assets an application uses in the executable.
/// We use the `link_section` attribute embed an extra section in the executable.
/// We force rust to store a serialized representation of the asset description
/// inside a particular region of the binary, with the label "manganis".
/// After linking, the "manganis" sections of the different object files will be merged.
pub fn generate_link_section(asset: impl ToTokens, asset_hash: &str) -> TokenStream2 {
let position = proc_macro2::Span::call_site();
let export_name = syn::LitStr::new(&format!("__ASSETS__{}", asset_hash), position);
let legacy_export_name = syn::LitStr::new(&format!("__MANGANIS__{}", asset_hash), position);
quote::quote! {
// We bundle both the legacy and new link sections for compatibility with older CLIs
static __LEGACY_LINK_SECTION: &'static [u8] = {
// First serialize the asset into a constant sized buffer
const __BUFFER: manganis::macro_helpers::const_serialize_07::ConstVec<u8> = manganis::macro_helpers::serialize_asset_07(&#asset);
// Then pull out the byte slice
const __BYTES: &[u8] = __BUFFER.as_ref();
// And the length of the byte slice
const __LEN: usize = __BYTES.len();
// Now that we have the size of the asset, copy the bytes into a static array
#[unsafe(export_name = #legacy_export_name)]
static __LINK_SECTION: [u8; __LEN] = manganis::macro_helpers::copy_bytes(__BYTES);
&__LINK_SECTION
};
static __LINK_SECTION: &'static [u8] = {
// First serialize the asset into a constant sized buffer
const __BUFFER: manganis::macro_helpers::const_serialize::ConstVec<u8> = manganis::macro_helpers::serialize_asset(&#asset);
// Then pull out the byte slice
const __BYTES: &[u8] = __BUFFER.as_ref();
// And the length of the byte slice
const __LEN: usize = __BYTES.len();
// Now that we have the size of the asset, copy the bytes into a static array
#[unsafe(export_name = #export_name)]
static __LINK_SECTION: [u8; __LEN] = manganis::macro_helpers::copy_bytes(__BYTES);
&__LINK_SECTION
};
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-macro/tests/option_asset.rs | packages/manganis/manganis-macro/tests/option_asset.rs | use manganis::{asset, option_asset, Asset};
#[test]
fn resolves_existing_asset() {
const REQUIRED: Asset = asset!("/assets/asset.txt");
const OPTIONAL: Option<Asset> = option_asset!("/assets/asset.txt");
let optional = OPTIONAL.expect("option_asset! should return Some for existing assets");
assert_eq!(optional.to_string(), REQUIRED.to_string());
}
#[test]
fn missing_asset_returns_none() {
const OPTIONAL: Option<Asset> = option_asset!("/assets/does_not_exist.txt");
assert!(OPTIONAL.is_none());
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/css.rs | packages/manganis/manganis-core/src/css.rs | use crate::{AssetOptions, AssetOptionsBuilder, AssetVariant};
use const_serialize_07 as const_serialize;
use const_serialize_08::SerializeConst;
/// Options for a css asset
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
pub struct CssAssetOptions {
minify: bool,
preload: bool,
static_head: bool,
}
impl Default for CssAssetOptions {
fn default() -> Self {
Self::default()
}
}
impl CssAssetOptions {
/// Create a new css asset using the builder
pub const fn new() -> AssetOptionsBuilder<CssAssetOptions> {
AssetOptions::css()
}
/// Create a default css asset options
pub const fn default() -> Self {
Self {
preload: false,
minify: true,
static_head: false,
}
}
/// Check if the asset is preloaded
pub const fn preloaded(&self) -> bool {
self.preload
}
/// Check if the asset is statically created
pub const fn static_head(&self) -> bool {
self.static_head
}
/// Check if the asset is minified
pub const fn minified(&self) -> bool {
self.minify
}
}
impl AssetOptions {
/// Create a new css asset builder
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/style.css", AssetOptions::css());
/// ```
pub const fn css() -> AssetOptionsBuilder<CssAssetOptions> {
AssetOptionsBuilder::variant(CssAssetOptions::default())
}
}
impl AssetOptionsBuilder<CssAssetOptions> {
/// Sets whether the css should be minified (default: true)
///
/// Minifying the css can make your site load faster by loading less data
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/style.css", AssetOptions::css().with_minify(false));
/// ```
pub const fn with_minify(mut self, minify: bool) -> Self {
self.variant.minify = minify;
self
}
/// Make the asset statically inserted (default: false)
///
/// Statically insert the file at compile time.
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/style.css", AssetOptions::css().with_static_head(true));
/// ```
#[allow(unused)]
pub const fn with_static_head(mut self, static_head: bool) -> Self {
self.variant.static_head = static_head;
self
}
/// Make the asset preloaded
///
/// Preloading css will make the file start to load as soon as possible. This is useful for css that is used soon after the page loads or css that may not be used immediately, but should start loading sooner
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/style.css", AssetOptions::css().with_preload(true));
/// ```
pub const fn with_preload(mut self, preload: bool) -> Self {
self.variant.preload = preload;
self
}
/// Convert the options into options for a generic asset
pub const fn into_asset_options(self) -> AssetOptions {
AssetOptions {
add_hash: true,
variant: AssetVariant::Css(self.variant),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/lib.rs | packages/manganis/manganis-core/src/lib.rs | mod folder;
pub use folder::*;
mod images;
pub use images::*;
mod options;
pub use options::*;
mod css;
pub use css::*;
mod js;
pub use js::*;
mod asset;
pub use asset::*;
mod css_module;
pub use css_module::*;
mod css_module_parser;
pub use css_module_parser::*;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/css_module.rs | packages/manganis/manganis-core/src/css_module.rs | use std::{
collections::HashSet,
hash::{DefaultHasher, Hash, Hasher},
path::Path,
};
use crate::{AssetOptions, AssetOptionsBuilder, AssetVariant};
use const_serialize_07 as const_serialize;
use const_serialize_08::SerializeConst;
/// Options for a css module asset
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
#[non_exhaustive]
#[doc(hidden)]
pub struct CssModuleAssetOptions {
minify: bool,
preload: bool,
}
impl Default for CssModuleAssetOptions {
fn default() -> Self {
Self::default()
}
}
impl CssModuleAssetOptions {
/// Create a new css asset using the builder
pub const fn new() -> AssetOptionsBuilder<CssModuleAssetOptions> {
AssetOptions::css_module()
}
/// Create a default css module asset options
pub const fn default() -> Self {
Self {
preload: false,
minify: true,
}
}
/// Check if the asset is minified
pub const fn minified(&self) -> bool {
self.minify
}
/// Check if the asset is preloaded
pub const fn preloaded(&self) -> bool {
self.preload
}
}
impl AssetOptions {
/// Create a new css module asset builder
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/style.css", AssetOptions::css_module());
/// ```
pub const fn css_module() -> AssetOptionsBuilder<CssModuleAssetOptions> {
AssetOptionsBuilder::variant(CssModuleAssetOptions::default())
}
}
impl AssetOptionsBuilder<CssModuleAssetOptions> {
/// Sets whether the css should be minified (default: true)
///
/// Minifying the css can make your site load faster by loading less data
pub const fn with_minify(mut self, minify: bool) -> Self {
self.variant.minify = minify;
self
}
/// Make the asset preloaded
///
/// Preloading css will make the image start to load as soon as possible. This is useful for css that is used soon after the page loads or css that may not be used immediately, but should start loading sooner
pub const fn with_preload(mut self, preload: bool) -> Self {
self.variant.preload = preload;
self
}
/// Convert the options into options for a generic asset
pub const fn into_asset_options(self) -> AssetOptions {
AssetOptions {
add_hash: self.add_hash,
variant: AssetVariant::CssModule(self.variant),
}
}
}
/// Create a hash for a css module based on the file path
pub fn create_module_hash(css_path: &Path) -> String {
let path_string = css_path.to_string_lossy();
let mut hasher = DefaultHasher::new();
path_string.hash(&mut hasher);
let hash = hasher.finish();
format!("{:016x}", hash)[..8].to_string()
}
/// Collect CSS classes & ids.
///
/// This is a rudementary css classes & ids collector.
/// Idents used only in media queries will not be collected. (not support yet)
///
/// There are likely a number of edge cases that will show up.
///
/// Returns `(HashSet<Classes>, HashSet<Ids>)`
#[deprecated(
since = "0.7.3",
note = "This function is no longer used by the css module system and will be removed in a future release."
)]
pub fn collect_css_idents(css: &str) -> (HashSet<String>, HashSet<String>) {
const ALLOWED: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
let mut classes = HashSet::new();
let mut ids = HashSet::new();
// Collected ident name and true for ids.
let mut start: Option<(String, bool)> = None;
// True if we have the first comment start delimiter `/`
let mut comment_start = false;
// True if we have the first comment end delimiter '*'
let mut comment_end = false;
// True if we're in a comment scope.
let mut in_comment_scope = false;
// True if we're in a block scope: `#hi { this is block scope }`
let mut in_block_scope = false;
// If we are currently collecting an ident:
// - Check if the char is allowed, put it into the ident string.
// - If not allowed, finalize the ident string and reset start.
// Otherwise:
// Check if character is a `.` or `#` representing a class or string, and start collecting.
for (_byte_index, c) in css.char_indices() {
if let Some(ident) = start.as_mut() {
if ALLOWED.find(c).is_some() {
// CSS ignore idents that start with a number.
// 1. Difficult to process
// 2. Avoid false positives (transition: 0.5s)
if ident.0.is_empty() && c.is_numeric() {
start = None;
continue;
}
ident.0.push(c);
} else {
match ident.1 {
true => ids.insert(ident.0.clone()),
false => classes.insert(ident.0.clone()),
};
start = None;
}
} else {
// Handle entering an exiting scopede.
match c {
// Mark as comment scope if we have comment start: /*
'*' if comment_start => {
comment_start = false;
in_comment_scope = true;
}
// Mark start of comment end if in comment scope: */
'*' if in_comment_scope => comment_end = true,
// Mark as comment start if not in comment scope and no comment start, mark comment_start
'/' if !in_comment_scope => {
comment_start = true;
}
// If we get the closing delimiter, mark as non-comment scope.
'/' if comment_end => {
in_comment_scope = false;
comment_start = false;
comment_end = false;
}
// Entering & Exiting block scope.
'{' => in_block_scope = true,
'}' => in_block_scope = false,
// Any other character, reset comment start and end if not in scope.
_ => {
comment_start = false;
comment_end = false;
}
}
// No need to process this char if in bad scope.
if in_comment_scope || in_block_scope {
continue;
}
match c {
'.' => start = Some((String::new(), false)),
'#' => start = Some((String::new(), true)),
_ => {}
}
}
}
(classes, ids)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/css_module_parser.rs | packages/manganis/manganis-core/src/css_module_parser.rs | use std::borrow::Cow;
use winnow::{
combinator::{alt, cut_err, delimited, opt, peek, preceded, repeat, terminated},
error::{ContextError, ErrMode, ParseError},
prelude::*,
stream::{AsChar, ContainsToken, Range},
token::{none_of, one_of, take_till, take_until, take_while},
};
/// ```text
/// v----v inner span
/// :global(.class)
/// ^-------------^ outer span
/// ```
#[derive(Debug, PartialEq)]
pub struct Global<'s> {
pub inner: &'s str,
pub outer: &'s str,
}
#[derive(Debug, PartialEq)]
pub enum CssFragment<'s> {
Class(&'s str),
Global(Global<'s>),
}
//************************************************************************//
/// Parses and rewrites CSS class selectors with the hash applied.
/// Does not modify `:global(...)` selectors.
pub fn transform_css<'a>(
css: &'a str,
hash: &str,
) -> Result<String, ParseError<&'a str, ContextError>> {
let fragments = parse_css(css)?;
let mut new_css = String::with_capacity(css.len() * 2);
let mut cursor = css;
for fragment in fragments {
let (span, replace) = match fragment {
CssFragment::Class(class) => (class, Cow::Owned(apply_hash(class, hash))),
CssFragment::Global(Global { inner, outer }) => (outer, Cow::Borrowed(inner)),
};
let (before, after) = cursor.split_at(span.as_ptr() as usize - cursor.as_ptr() as usize);
cursor = &after[span.len()..];
new_css.push_str(before);
new_css.push_str(&replace);
}
new_css.push_str(cursor);
Ok(new_css)
}
/// Gets all the classes in the css files and their rewritten names.
/// Includes `:global(...)` classes where the name is not changed.
#[allow(clippy::type_complexity)]
pub fn get_class_mappings<'a>(
css: &'a str,
hash: &str,
) -> Result<Vec<(&'a str, Cow<'a, str>)>, ParseError<&'a str, ContextError>> {
let fragments = parse_css(css)?;
let mut result = Vec::new();
for c in fragments {
match c {
CssFragment::Class(class) => {
result.push((class, Cow::Owned(apply_hash(class, hash))));
}
CssFragment::Global(global) => {
let global_classes = resolve_global_inner_classes(global)?;
result.extend(
global_classes
.into_iter()
.map(|class| (class, Cow::Borrowed(class))),
);
}
}
}
result.sort_by_key(|e| e.0);
result.dedup_by_key(|e| e.0);
Ok(result)
}
fn resolve_global_inner_classes<'a>(
global: Global<'a>,
) -> Result<Vec<&'a str>, ParseError<&'a str, ContextError>> {
let input = global.inner;
let fragments = selector.parse(input)?;
let mut result = Vec::new();
for c in fragments {
match c {
CssFragment::Class(class) => result.push(class),
CssFragment::Global(_) => {
unreachable!("Top level parser should have already errored if globals are nested")
}
}
}
Ok(result)
}
fn apply_hash(class: &str, hash: &str) -> String {
format!("{}-{}", class, hash)
}
//************************************************************************//
pub fn parse_css(input: &str) -> Result<Vec<CssFragment<'_>>, ParseError<&str, ContextError>> {
style_rule_block_contents.parse(input)
}
fn recognize_repeat<'s, O>(
range: impl Into<Range>,
f: impl Parser<&'s str, O, ErrMode<ContextError>>,
) -> impl Parser<&'s str, &'s str, ErrMode<ContextError>> {
repeat(range, f).fold(|| (), |_, _| ()).take()
}
fn ws<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
recognize_repeat(
0..,
alt((
line_comment,
block_comment,
take_while(1.., (AsChar::is_space, '\n', '\r')),
)),
)
.parse_next(input)
}
fn line_comment<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
("//", take_while(0.., |c| c != '\n'))
.take()
.parse_next(input)
}
fn block_comment<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
("/*", cut_err(terminated(take_until(0.., "*/"), "*/")))
.take()
.parse_next(input)
}
// matches a sass interpolation of the form #{...}
fn sass_interpolation<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
(
"#{",
cut_err(terminated(take_till(1.., ('{', '}', '\n')), '}')),
)
.take()
.parse_next(input)
}
fn identifier<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
(
one_of(('_', '-', AsChar::is_alpha)),
take_while(0.., ('_', '-', AsChar::is_alphanum)),
)
.take()
.parse_next(input)
}
fn class<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
preceded('.', identifier).parse_next(input)
}
fn global<'s>(input: &mut &'s str) -> ModalResult<Global<'s>> {
let (inner, outer) = preceded(
":global(",
cut_err(terminated(
stuff_till(0.., (')', '(', '{')), // inner
')',
)),
)
.with_taken() // outer
.parse_next(input)?;
Ok(Global { inner, outer })
}
fn string_dq<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
let str_char = alt((none_of(['"']).void(), "\\\"".void()));
let str_chars = recognize_repeat(0.., str_char);
preceded('"', cut_err(terminated(str_chars, '"'))).parse_next(input)
}
fn string_sq<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
let str_char = alt((none_of(['\'']).void(), "\\'".void()));
let str_chars = recognize_repeat(0.., str_char);
preceded('\'', cut_err(terminated(str_chars, '\''))).parse_next(input)
}
fn string<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
alt((string_dq, string_sq)).parse_next(input)
}
/// Behaves like take_till except it finds and parses strings and
/// comments (allowing those to contain the end condition characters).
fn stuff_till<'s>(
range: impl Into<Range>,
list: impl ContainsToken<char>,
) -> impl Parser<&'s str, &'s str, ErrMode<ContextError>> {
recognize_repeat(
range,
alt((
string.void(),
block_comment.void(),
line_comment.void(),
sass_interpolation.void(),
'/'.void(),
'#'.void(),
take_till(1.., ('\'', '"', '/', '#', list)).void(),
)),
)
}
fn selector<'s>(input: &mut &'s str) -> ModalResult<Vec<CssFragment<'s>>> {
repeat(
1..,
alt((
class.map(|c| Some(CssFragment::Class(c))),
global.map(|g| Some(CssFragment::Global(g))),
':'.map(|_| None),
stuff_till(1.., ('.', ';', '{', '}', ':')).map(|_| None),
)),
)
.fold(Vec::new, |mut acc, item| {
if let Some(item) = item {
acc.push(item);
}
acc
})
.parse_next(input)
}
fn declaration<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
(
(opt('$'), identifier),
ws,
':',
terminated(
stuff_till(1.., (';', '{', '}')),
alt((';', peek('}'))), // semicolon is optional if it's the last element in a rule block
),
)
.take()
.parse_next(input)
}
fn style_rule_block_statement<'s>(input: &mut &'s str) -> ModalResult<Vec<CssFragment<'s>>> {
let content = alt((
declaration.map(|_| Vec::new()), //
at_rule,
style_rule,
));
delimited(ws, content, ws).parse_next(input)
}
fn style_rule_block_contents<'s>(input: &mut &'s str) -> ModalResult<Vec<CssFragment<'s>>> {
repeat(0.., style_rule_block_statement)
.fold(Vec::new, |mut acc, mut item| {
acc.append(&mut item);
acc
})
.parse_next(input)
}
fn style_rule_block<'s>(input: &mut &'s str) -> ModalResult<Vec<CssFragment<'s>>> {
preceded(
'{',
cut_err(terminated(style_rule_block_contents, (ws, '}'))),
)
.parse_next(input)
}
fn style_rule<'s>(input: &mut &'s str) -> ModalResult<Vec<CssFragment<'s>>> {
let (mut classes, mut nested_classes) = (selector, style_rule_block).parse_next(input)?;
classes.append(&mut nested_classes);
Ok(classes)
}
fn at_rule<'s>(input: &mut &'s str) -> ModalResult<Vec<CssFragment<'s>>> {
let (identifier, char) = preceded(
'@',
cut_err((
terminated(identifier, stuff_till(0.., ('{', '}', ';'))),
alt(('{', ';', peek('}'))),
)),
)
.parse_next(input)?;
if char != '{' {
return Ok(vec![]);
}
match identifier {
"media" | "layer" | "container" | "include" => {
cut_err(terminated(style_rule_block_contents, '}')).parse_next(input)
}
_ => {
cut_err(terminated(unknown_block_contents, '}')).parse_next(input)?;
Ok(vec![])
}
}
}
fn unknown_block_contents<'s>(input: &mut &'s str) -> ModalResult<&'s str> {
recognize_repeat(
0..,
alt((
stuff_till(1.., ('{', '}')).void(),
('{', cut_err((unknown_block_contents, '}'))).void(),
)),
)
.parse_next(input)
}
//************************************************************************//
#[test]
fn test_class() {
let mut input = "._x1a2b Hello";
let r = class.parse_next(&mut input);
assert_eq!(r, Ok("_x1a2b"));
}
#[test]
fn test_selector() {
let mut input = ".foo.bar [value=\"fa.sdasd\"] /* .banana */ // .apple \n \t .cry {";
let r = selector.parse_next(&mut input);
assert_eq!(
r,
Ok(vec![
CssFragment::Class("foo"),
CssFragment::Class("bar"),
CssFragment::Class("cry")
])
);
let mut input = "{";
let r = selector.take().parse_next(&mut input);
assert!(r.is_err());
}
#[test]
fn test_declaration() {
let mut input = "background-color \t : red;";
let r = declaration.parse_next(&mut input);
assert_eq!(r, Ok("background-color \t : red;"));
let r = declaration.parse_next(&mut input);
assert!(r.is_err());
}
#[test]
fn test_style_rule() {
let mut input = ".foo.bar {
background-color: red;
.baz {
color: blue;
}
$some-scss-var: 10px;
@some-at-rule blah blah;
@media blah .blah {
.moo {
color: red;
}
}
@container (width > 700px) {
.zoo {
color: blue;
}
}
}END";
let r = style_rule.parse_next(&mut input);
assert_eq!(
r,
Ok(vec![
CssFragment::Class("foo"),
CssFragment::Class("bar"),
CssFragment::Class("baz"),
CssFragment::Class("moo"),
CssFragment::Class("zoo")
])
);
assert_eq!(input, "END");
}
#[test]
fn test_at_rule_simple() {
let mut input = "@simple-rule blah \"asd;asd\" blah;";
let r = at_rule.parse_next(&mut input);
assert_eq!(r, Ok(vec![]));
assert!(input.is_empty());
}
#[test]
fn test_at_rule_unknown() {
let mut input = "@unknown blah \"asdasd\" blah {
bunch of stuff {
// things inside {
blah
' { '
}
.bar {
color: blue;
.baz {
color: green;
}
}
}";
let r = at_rule.parse_next(&mut input);
assert_eq!(r, Ok(vec![]));
assert!(input.is_empty());
}
#[test]
fn test_at_rule_media() {
let mut input = "@media blah \"asdasd\" blah {
.foo {
background-color: red;
}
.bar {
color: blue;
.baz {
color: green;
}
}
}";
let r = at_rule.parse_next(&mut input);
assert_eq!(
r,
Ok(vec![
CssFragment::Class("foo"),
CssFragment::Class("bar"),
CssFragment::Class("baz")
])
);
assert!(input.is_empty());
}
#[test]
fn test_at_rule_layer() {
let mut input = "@layer test {
.foo {
background-color: red;
}
.bar {
color: blue;
.baz {
color: green;
}
}
}";
let r = at_rule.parse_next(&mut input);
assert_eq!(
r,
Ok(vec![
CssFragment::Class("foo"),
CssFragment::Class("bar"),
CssFragment::Class("baz")
])
);
assert!(input.is_empty());
}
#[test]
fn test_top_level() {
let mut input = "// tool.module.scss
.default_border {
border-color: lch(100% 10 10);
border-style: dashed double;
border-radius: 30px;
}
@media testing {
.media-foo {
color: red;
}
}
@layer {
.layer-foo {
color: blue;
}
}
@include mixin {
border: none;
.include-foo {
color: green;
}
}
@layer foo;
@debug 1+2 * 3==1+(2 * 3); // true
.container {
padding: 1em;
border: 2px solid;
border-color: lch(100% 10 10);
border-style: dashed double;
border-radius: 30px;
margin: 1em;
background-color: lch(45% 9.5 140.4);
.bar {
color: red;
}
}
@debug 1+2 * 3==1+(2 * 3); // true
";
let r = style_rule_block_contents.parse_next(&mut input);
assert_eq!(
r,
Ok(vec![
CssFragment::Class("default_border"),
CssFragment::Class("media-foo"),
CssFragment::Class("layer-foo"),
CssFragment::Class("include-foo"),
CssFragment::Class("container"),
CssFragment::Class("bar"),
])
);
println!("{input}");
assert!(input.is_empty());
}
#[test]
fn test_sass_interpolation() {
let mut input = "#{$test-test}END";
let r = sass_interpolation.parse_next(&mut input);
assert_eq!(r, Ok("#{$test-test}"));
assert_eq!(input, "END");
let mut input = "#{$test-test
}END";
let r = sass_interpolation.parse_next(&mut input);
assert!(r.is_err());
let mut input = "#{$test-test";
let r = sass_interpolation.parse_next(&mut input);
assert!(r.is_err());
let mut input = "#{$test-te{st}";
let r = sass_interpolation.parse_next(&mut input);
assert!(r.is_err());
}
#[test]
fn test_get_class_mappings() {
let css = r#".foo.bar {
background-color: red;
:global(.baz) {
color: blue;
}
:global(.bag .biz) {
color: blue;
}
.zig {
}
.bong {}
.zig {
color: blue;
}
}"#;
let hash = "abc1234";
let mappings = get_class_mappings(css, hash).unwrap();
let expected = [
("bag", "bag"),
("bar", "bar-abc1234"),
("baz", "baz"),
("biz", "biz"),
("bong", "bong-abc1234"),
("foo", "foo-abc1234"),
("zig", "zig-abc1234"),
];
if mappings.len() != expected.len() {
panic!(
"Expected {} mappings, got {}",
expected.len(),
mappings.len()
);
}
for (i, (original, hashed)) in mappings.iter().enumerate() {
assert_eq!(expected[i].0, *original);
assert_eq!(expected[i].1, *hashed);
}
}
#[test]
fn test_parser_error_on_nested_globals() {
let css = r#".foo :global(.bar .baz) {
color: blue;
}"#;
let result = parse_css(css);
assert!(result.is_ok());
let css = r#".foo :global(.bar :global(.baz)) {
color: blue;
}"#;
let result = parse_css(css);
assert!(result.is_err());
}
#[test]
#[should_panic]
fn test_resolve_global_inner_classes_nested() {
let global = Global {
inner: ".foo :global(.bar)",
outer: ":global(.foo :global(.bar))",
};
let _ = resolve_global_inner_classes(global);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/asset.rs | packages/manganis/manganis-core/src/asset.rs | use crate::AssetOptions;
use const_serialize_07 as const_serialize;
use const_serialize_08::{deserialize_const, ConstStr, SerializeConst};
use std::{fmt::Debug, hash::Hash, path::PathBuf};
/// An asset that should be copied by the bundler with some options. This type will be
/// serialized into the binary.
/// CLIs that support manganis, should pull out the assets from the link section, optimize,
/// and write them to the filesystem at [`BundledAsset::bundled_path`] for the application
/// to use.
#[derive(
Debug,
Eq,
Clone,
Copy,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
pub struct BundledAsset {
/// The absolute path of the asset
absolute_source_path: ConstStr,
/// The bundled path of the asset
bundled_path: ConstStr,
/// The options for the asset
options: AssetOptions,
}
impl PartialEq for BundledAsset {
fn eq(&self, other: &Self) -> bool {
self.absolute_source_path == other.absolute_source_path
&& self.bundled_path == other.bundled_path
&& self.options == other.options
}
}
impl PartialOrd for BundledAsset {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
match self
.absolute_source_path
.partial_cmp(&other.absolute_source_path)
{
Some(core::cmp::Ordering::Equal) => {}
ord => return ord,
}
match self.bundled_path.partial_cmp(&other.bundled_path) {
Some(core::cmp::Ordering::Equal) => {}
ord => return ord,
}
self.options.partial_cmp(&other.options)
}
}
impl Hash for BundledAsset {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.absolute_source_path.hash(state);
self.bundled_path.hash(state);
self.options.hash(state);
}
}
impl BundledAsset {
pub const PLACEHOLDER_HASH: &str = "This should be replaced by dx as part of the build process. If you see this error, make sure you are using a matching version of dx and dioxus and you are not stripping symbols from your binary.";
#[doc(hidden)]
/// This should only be called from the macro
/// Create a new asset
pub const fn new(
absolute_source_path: &str,
bundled_path: &str,
options: AssetOptions,
) -> Self {
Self {
absolute_source_path: ConstStr::new(absolute_source_path),
bundled_path: ConstStr::new(bundled_path),
options,
}
}
/// Get the bundled name of the asset. This identifier cannot be used to read the asset directly
pub fn bundled_path(&self) -> &str {
self.bundled_path.as_str()
}
/// Get the absolute path of the asset source. This path will not be available when the asset is bundled
pub fn absolute_source_path(&self) -> &str {
self.absolute_source_path.as_str()
}
/// Get the options for the asset
pub const fn options(&self) -> &AssetOptions {
&self.options
}
}
/// A bundled asset with some options. The asset can be used in rsx! to reference the asset.
/// It should not be read directly with [`std::fs::read`] because the path needs to be resolved
/// relative to the bundle
///
/// ```rust, ignore
/// # use manganis::{asset, Asset};
/// # use dioxus::prelude::*;
/// const ASSET: Asset = asset!("/assets/image.png");
/// rsx! {
/// img { src: ASSET }
/// };
/// ```
#[allow(unpredictable_function_pointer_comparisons)]
#[derive(PartialEq, Clone, Copy)]
pub struct Asset {
/// A function that returns a pointer to the bundled asset. This will be resolved after the linker has run and
/// put into the lazy asset. We use a function instead of using the pointer directly to force the compiler to
/// read the static __LINK_SECTION at runtime which will be offset by the hot reloading engine instead
/// of at compile time which can't be offset
///
/// WARNING: Don't read this directly. Reads can get optimized away at compile time before
/// the data for this is filled in by the CLI after the binary is built. Instead, use
/// [`std::ptr::read_volatile`] to read the data.
bundled: fn() -> &'static [u8],
/// The legacy version of [`Self::bundled`]. This is only used for backwards compatibility with older versions of the CLI
legacy: fn() -> &'static [u8],
}
impl Debug for Asset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.resolve().fmt(f)
}
}
unsafe impl Send for Asset {}
unsafe impl Sync for Asset {}
impl Asset {
#[doc(hidden)]
/// This should only be called from the macro
/// Create a new asset from the bundled form of the asset and the link section
pub const fn new(
bundled: extern "Rust" fn() -> &'static [u8],
legacy: extern "Rust" fn() -> &'static [u8],
) -> Self {
Self { bundled, legacy }
}
/// Get the bundled asset
pub fn bundled(&self) -> BundledAsset {
// Read the slice using volatile reads to prevent the compiler from optimizing
// away the read at compile time
fn read_slice_volatile(bundled: &'static [u8]) -> const_serialize_07::ConstVec<u8> {
let ptr = bundled as *const [u8] as *const u8;
let len = bundled.len();
if ptr.is_null() {
panic!("Tried to use an asset that was not bundled. Make sure you are compiling dx as the linker");
}
let mut bytes = const_serialize_07::ConstVec::new();
for byte in 0..len {
// SAFETY: We checked that the pointer was not null above. The pointer is valid for reads and
// since we are reading a u8 there are no alignment requirements
let byte = unsafe { std::ptr::read_volatile(ptr.add(byte)) };
bytes = bytes.push(byte);
}
bytes
}
let bundled = (self.bundled)();
let bytes = read_slice_volatile(bundled);
let read = bytes.as_ref();
let asset = deserialize_const!(BundledAsset, read).expect("Failed to deserialize asset. Make sure you built with the matching version of the Dioxus CLI").1;
// If the asset wasn't bundled with the newer format, try the legacy format
if asset.bundled_path() == BundledAsset::PLACEHOLDER_HASH {
let bundled = (self.legacy)();
let bytes = read_slice_volatile(bundled);
let read = bytes.read();
let asset = const_serialize_07::deserialize_const!(BundledAsset, read).expect("Failed to deserialize asset. Make sure you built with the matching version of the Dioxus CLI").1;
asset
} else {
asset
}
}
/// Return a canonicalized path to the asset
///
/// Attempts to resolve it against an `assets` folder in the current directory.
/// If that doesn't exist, it will resolve against the cargo manifest dir
pub fn resolve(&self) -> PathBuf {
#[cfg(feature = "dioxus")]
// If the asset is relative, we resolve the asset at the current directory
if !dioxus_core_types::is_bundled_app() {
return PathBuf::from(self.bundled().absolute_source_path.as_str());
}
#[cfg(feature = "dioxus")]
let bundle_root = {
let base_path = dioxus_cli_config::base_path();
let base_path = base_path
.as_deref()
.map(|base_path| {
let trimmed = base_path.trim_matches('/');
format!("/{trimmed}")
})
.unwrap_or_default();
PathBuf::from(format!("{base_path}/assets/"))
};
#[cfg(not(feature = "dioxus"))]
let bundle_root = PathBuf::from("/assets/");
// Otherwise presumably we're bundled and we can use the bundled path
bundle_root.join(PathBuf::from(
self.bundled().bundled_path.as_str().trim_start_matches('/'),
))
}
}
impl From<Asset> for String {
fn from(value: Asset) -> Self {
value.to_string()
}
}
impl From<Asset> for Option<String> {
fn from(value: Asset) -> Self {
Some(value.to_string())
}
}
impl std::fmt::Display for Asset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.resolve().display())
}
}
#[cfg(feature = "dioxus")]
impl dioxus_core_types::DioxusFormattable for Asset {
fn format(&self) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Owned(self.to_string())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/js.rs | packages/manganis/manganis-core/src/js.rs | use const_serialize_07 as const_serialize;
use const_serialize_08::SerializeConst;
use crate::{AssetOptions, AssetOptionsBuilder, AssetVariant};
/// Options for a javascript asset
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
pub struct JsAssetOptions {
minify: bool,
preload: bool,
static_head: bool,
}
impl Default for JsAssetOptions {
fn default() -> Self {
Self::default()
}
}
impl JsAssetOptions {
/// Create a new js asset options builder
pub const fn new() -> AssetOptionsBuilder<JsAssetOptions> {
AssetOptions::js()
}
/// Create a default js asset options
pub const fn default() -> Self {
Self {
preload: false,
minify: true,
static_head: false,
}
}
/// Check if the asset is preloaded
pub const fn preloaded(&self) -> bool {
self.preload
}
/// Check if the asset is statically created
pub const fn static_head(&self) -> bool {
self.static_head
}
/// Check if the asset is minified
pub const fn minified(&self) -> bool {
self.minify
}
}
impl AssetOptions {
/// Create a new js asset builder
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/script.js", AssetOptions::js());
/// ```
pub const fn js() -> AssetOptionsBuilder<JsAssetOptions> {
AssetOptionsBuilder::variant(JsAssetOptions::default())
}
}
impl AssetOptionsBuilder<JsAssetOptions> {
/// Sets whether the js should be minified (default: true)
///
/// Minifying the js can make your site load faster by loading less data
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/script.js", AssetOptions::js().with_minify(false));
/// ```
#[allow(unused)]
pub const fn with_minify(mut self, minify: bool) -> Self {
self.variant.minify = minify;
self
}
/// Make the asset statically inserted (default: false)
///
/// Statically insert the file at compile time.
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/script.js", AssetOptions::js().with_static_head(true));
/// ```
#[allow(unused)]
pub const fn with_static_head(mut self, static_head: bool) -> Self {
self.variant.static_head = static_head;
self
}
/// Make the asset preloaded
///
/// Preloading the javascript will make the javascript start to load as soon as possible. This is useful for javascript that will be used soon after the page loads or javascript that may not be used immediately, but should start loading sooner
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/script.js", AssetOptions::js().with_preload(true));
/// ```
#[allow(unused)]
pub const fn with_preload(mut self, preload: bool) -> Self {
self.variant.preload = preload;
self
}
/// Convert the builder into asset options with the given variant
pub const fn into_asset_options(self) -> AssetOptions {
AssetOptions {
add_hash: self.add_hash,
variant: AssetVariant::Js(self.variant),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/options.rs | packages/manganis/manganis-core/src/options.rs | use const_serialize_07 as const_serialize;
use const_serialize_08::SerializeConst;
use crate::{
CssAssetOptions, CssModuleAssetOptions, FolderAssetOptions, ImageAssetOptions, JsAssetOptions,
};
/// Settings for a generic asset
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
#[non_exhaustive]
pub struct AssetOptions {
/// If a hash should be added to the asset path
pub(crate) add_hash: bool,
/// The variant of the asset
pub(crate) variant: AssetVariant,
}
impl AssetOptions {
/// Create a new asset options builder
pub const fn builder() -> AssetOptionsBuilder<()> {
AssetOptionsBuilder::new()
}
/// Get the variant of the asset
pub const fn variant(&self) -> &AssetVariant {
&self.variant
}
/// Check if a hash should be added to the asset path
pub const fn hash_suffix(&self) -> bool {
self.add_hash
}
/// Try to get the extension for the asset. If the asset options don't define an extension, this will return None
pub const fn extension(&self) -> Option<&'static str> {
match self.variant {
AssetVariant::Image(image) => image.extension(),
AssetVariant::Css(_) => Some("css"),
AssetVariant::CssModule(_) => Some("css"),
AssetVariant::Js(_) => Some("js"),
AssetVariant::Folder(_) => None,
AssetVariant::Unknown => None,
}
}
/// Convert the options into options for a generic asset
pub const fn into_asset_options(self) -> AssetOptions {
self
}
}
/// A builder for [`AssetOptions`]
///
/// ```rust
/// # use manganis::{AssetOptions, Asset, asset};
/// static ASSET: Asset = asset!(
/// "/assets/style.css",
/// AssetOptions::builder()
/// .with_hash_suffix(false)
/// );
/// ```
pub struct AssetOptionsBuilder<T> {
/// If a hash should be added to the asset path
pub(crate) add_hash: bool,
/// The variant of the asset
pub(crate) variant: T,
}
impl Default for AssetOptionsBuilder<()> {
fn default() -> Self {
Self::default()
}
}
impl AssetOptionsBuilder<()> {
/// Create a new asset options builder with an unknown variant
pub const fn new() -> Self {
Self {
add_hash: true,
variant: (),
}
}
/// Create a default asset options builder
pub const fn default() -> Self {
Self::new()
}
/// Convert the builder into asset options with the given variant
pub const fn into_asset_options(self) -> AssetOptions {
AssetOptions {
add_hash: self.add_hash,
variant: AssetVariant::Unknown,
}
}
}
impl<T> AssetOptionsBuilder<T> {
/// Create a new asset options builder with the given variant
pub const fn variant(variant: T) -> Self {
Self {
add_hash: true,
variant,
}
}
/// Set whether a hash should be added to the asset path. Manganis adds hashes to asset paths by default
/// for [cache busting](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching#cache_busting).
/// With hashed assets, you can serve the asset with a long expiration time, and when the asset changes,
/// the hash in the path will change, causing the browser to fetch the new version.
///
/// This method will only effect if the hash is added to the bundled asset path. If you are using the asset
/// macro, the asset struct still needs to be used in your rust code to ensure the asset is included in the binary.
///
/// <div class="warning">
///
/// If you are using an asset outside of rust code where you know what the asset hash will be, you must use the
/// `#[used]` attribute to ensure the asset is included in the binary even if it is not referenced in the code.
///
/// ```rust
/// #[used]
/// static ASSET: manganis::Asset = manganis::asset!(
/// "/assets/style.css",
/// manganis::AssetOptions::builder()
/// .with_hash_suffix(false)
/// );
/// ```
///
/// </div>
pub const fn with_hash_suffix(mut self, add_hash: bool) -> Self {
self.add_hash = add_hash;
self
}
}
/// Settings for a specific type of asset
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
#[repr(C, u8)]
#[non_exhaustive]
pub enum AssetVariant {
/// An image asset
Image(ImageAssetOptions),
/// A folder asset
Folder(FolderAssetOptions),
/// A css asset
Css(CssAssetOptions),
/// A css module asset
CssModule(CssModuleAssetOptions),
/// A javascript asset
Js(JsAssetOptions),
/// An unknown asset
Unknown,
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/folder.rs | packages/manganis/manganis-core/src/folder.rs | use const_serialize_07 as const_serialize;
use const_serialize_08::SerializeConst;
use crate::{AssetOptions, AssetOptionsBuilder};
/// The builder for a folder asset.
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
pub struct FolderAssetOptions {}
impl Default for FolderAssetOptions {
fn default() -> Self {
Self::default()
}
}
impl FolderAssetOptions {
/// Create a new folder asset builder
pub const fn new() -> AssetOptionsBuilder<FolderAssetOptions> {
AssetOptions::folder()
}
/// Create a default folder asset options
pub const fn default() -> Self {
Self {}
}
}
impl AssetOptions {
/// Create a new folder asset builder
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets", AssetOptions::folder());
/// ```
pub const fn folder() -> AssetOptionsBuilder<FolderAssetOptions> {
AssetOptionsBuilder::variant(FolderAssetOptions::default())
}
}
impl AssetOptionsBuilder<FolderAssetOptions> {
/// Convert the options into options for a generic asset
pub const fn into_asset_options(self) -> AssetOptions {
AssetOptions {
add_hash: false,
variant: crate::AssetVariant::Folder(self.variant),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis-core/src/images.rs | packages/manganis/manganis-core/src/images.rs | use const_serialize_07 as const_serialize;
use const_serialize_08::SerializeConst;
use crate::{AssetOptions, AssetOptionsBuilder, AssetVariant};
/// The type of an image. You can read more about the tradeoffs between image formats [here](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types)
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
#[repr(u8)]
pub enum ImageFormat {
/// A png image. Png images cannot contain transparency and tend to compress worse than other formats
Png,
/// A jpg image. Jpg images can contain transparency and tend to compress better than png images
Jpg,
/// A webp image. Webp images can contain transparency and tend to compress better than jpg images
Webp,
/// An avif image. Avif images can compress slightly better than webp images but are not supported by all browsers
Avif,
/// An unknown image type
Unknown,
}
/// The size of an image asset
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
#[repr(C, u8)]
pub enum ImageSize {
/// A manual size in pixels
Manual {
/// The width of the image in pixels
width: u32,
/// The height of the image in pixels
height: u32,
},
/// The size will be automatically determined from the image source
Automatic,
}
/// Options for an image asset
#[derive(
Debug,
Eq,
PartialEq,
PartialOrd,
Clone,
Copy,
Hash,
SerializeConst,
const_serialize::SerializeConst,
serde::Serialize,
serde::Deserialize,
)]
#[const_serialize(crate = const_serialize_08)]
pub struct ImageAssetOptions {
ty: ImageFormat,
low_quality_preview: bool,
size: ImageSize,
preload: bool,
}
impl Default for ImageAssetOptions {
fn default() -> Self {
Self::default()
}
}
impl ImageAssetOptions {
/// Create a new builder for image asset options
pub const fn new() -> AssetOptionsBuilder<ImageAssetOptions> {
AssetOptions::image()
}
/// Create a default image asset options
pub const fn default() -> Self {
Self {
ty: ImageFormat::Unknown,
low_quality_preview: false,
size: ImageSize::Automatic,
preload: false,
}
}
/// Check if the asset is preloaded
pub const fn preloaded(&self) -> bool {
self.preload
}
/// Get the format of the image
pub const fn format(&self) -> ImageFormat {
self.ty
}
/// Get the size of the image
pub const fn size(&self) -> ImageSize {
self.size
}
pub(crate) const fn extension(&self) -> Option<&'static str> {
match self.ty {
ImageFormat::Png => Some("png"),
ImageFormat::Jpg => Some("jpg"),
ImageFormat::Webp => Some("webp"),
ImageFormat::Avif => Some("avif"),
ImageFormat::Unknown => None,
}
}
}
impl AssetOptions {
/// Create a new image asset builder
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image());
/// ```
pub const fn image() -> AssetOptionsBuilder<ImageAssetOptions> {
AssetOptionsBuilder::variant(ImageAssetOptions::default())
}
}
impl AssetOptionsBuilder<ImageAssetOptions> {
/// Make the asset preloaded
///
/// Preloading an image will make the image start to load as soon as possible. This is useful for images that will be displayed soon after the page loads or images that may not be visible immediately, but should start loading sooner
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_preload(true));
/// ```
pub const fn with_preload(mut self, preload: bool) -> Self {
self.variant.preload = preload;
self
}
/// Sets the format of the image
///
/// Choosing the right format can make your site load much faster. Webp and avif images tend to be a good default for most images
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageFormat};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_format(ImageFormat::Webp));
/// ```
pub const fn with_format(mut self, format: ImageFormat) -> Self {
self.variant.ty = format;
self
}
/// Sets the format of the image to [`ImageFormat::Avif`]
///
/// Avif images tend to be a good default for most images rendered in browser because
/// they compress images well
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageFormat};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_avif());
/// ```
pub const fn with_avif(self) -> Self {
self.with_format(ImageFormat::Avif)
}
/// Sets the format of the image to [`ImageFormat::Webp`]
///
/// Webp images tend to be a good default for most images rendered in browser because
/// they compress images well
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageFormat};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_webp());
/// ```
pub const fn with_webp(self) -> Self {
self.with_format(ImageFormat::Webp)
}
/// Sets the format of the image to [`ImageFormat::Jpg`]
///
/// Jpeg images compress much better than [`ImageFormat::Png`], but worse than [`ImageFormat::Webp`] or [`ImageFormat::Avif`]
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageFormat};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_jpg());
/// ```
pub const fn with_jpg(self) -> Self {
self.with_format(ImageFormat::Jpg)
}
/// Sets the format of the image to [`ImageFormat::Png`]
///
/// Png images don't compress very well, so they are not recommended for large images
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageFormat};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_png());
/// ```
pub const fn with_png(self) -> Self {
self.with_format(ImageFormat::Png)
}
/// Sets the size of the image
///
/// If you only use the image in one place, you can set the size of the image to the size it will be displayed at. This will make the image load faster
///
/// ```rust
/// # use manganis::{asset, Asset, AssetOptions, ImageSize};
/// const _: Asset = asset!("/assets/image.png", AssetOptions::image().with_size(ImageSize::Manual { width: 512, height: 512 }));
/// ```
pub const fn with_size(mut self, size: ImageSize) -> Self {
self.variant.size = size;
self
}
/// Convert the options into options for a generic asset
pub const fn into_asset_options(self) -> AssetOptions {
AssetOptions {
add_hash: self.add_hash,
variant: AssetVariant::Image(self.variant),
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis/src/lib.rs | packages/manganis/manganis/src/lib.rs | #![doc = include_str!("../README.md")]
#![deny(missing_docs)]
#[doc(hidden)]
pub mod macro_helpers;
pub use manganis_macro::asset;
pub use manganis_macro::css_module;
pub use manganis_macro::option_asset;
pub use manganis_core::{
Asset, AssetOptions, AssetVariant, BundledAsset, CssAssetOptions, CssModuleAssetOptions,
FolderAssetOptions, ImageAssetOptions, ImageFormat, ImageSize, JsAssetOptions,
};
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/manganis/manganis/src/macro_helpers.rs | packages/manganis/manganis/src/macro_helpers.rs | pub use const_serialize;
use const_serialize::{serialize_const, ConstVec, SerializeConst};
pub use const_serialize_07;
use const_serialize_07::{
serialize_const as serialize_const_07, ConstVec as ConstVec07,
SerializeConst as SerializeConst07,
};
use manganis_core::{AssetOptions, BundledAsset};
/// Create a bundled asset from the input path, the content hash, and the asset options
pub const fn create_bundled_asset(input_path: &str, asset_config: AssetOptions) -> BundledAsset {
BundledAsset::new(input_path, BundledAsset::PLACEHOLDER_HASH, asset_config)
}
/// Create a bundled asset from the input path, the content hash, and the asset options with a relative asset deprecation warning
///
/// This method is deprecated and will be removed in a future release.
#[deprecated(
note = "Relative asset!() paths are not supported. Use a path like `/assets/myfile.png` instead of `./assets/myfile.png`"
)]
pub const fn create_bundled_asset_relative(
input_path: &str,
asset_config: AssetOptions,
) -> BundledAsset {
create_bundled_asset(input_path, asset_config)
}
/// Serialize an asset to a const buffer
pub const fn serialize_asset(asset: &BundledAsset) -> ConstVec<u8> {
let data = ConstVec::new();
let mut data = serialize_const(asset, data);
// Reserve the maximum size of the asset
while data.len() < <BundledAsset as SerializeConst>::MEMORY_LAYOUT.size() {
data = data.push(0);
}
data
}
/// Serialize an asset to a const buffer in the legacy 0.7 format
pub const fn serialize_asset_07(asset: &BundledAsset) -> ConstVec07<u8> {
let data = ConstVec07::new();
let mut data = serialize_const_07(asset, data);
// Reserve the maximum size of the asset
while data.len() < <BundledAsset as SerializeConst07>::MEMORY_LAYOUT.size() {
data = data.push(0);
}
data
}
/// Deserialize a const buffer into a BundledAsset
pub const fn deserialize_asset(bytes: &[u8]) -> BundledAsset {
match const_serialize::deserialize_const!(BundledAsset, bytes) {
Some((_, asset)) => asset,
None => panic!("Failed to deserialize asset. This may be caused by a mismatch between your dioxus and dioxus-cli versions"),
}
}
/// Copy a slice into a constant sized buffer at compile time
pub const fn copy_bytes<const N: usize>(bytes: &[u8]) -> [u8; N] {
let mut out = [0; N];
let mut i = 0;
while i < N {
out[i] = bytes[i];
i += 1;
}
out
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/config-macro/src/lib.rs | packages/config-macro/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")]
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
macro_rules! define_config_macro {
($name:ident if $($cfg:tt)+) => {
#[proc_macro]
pub fn $name(input: TokenStream) -> TokenStream {
if cfg!($($cfg)+) {
let input = TokenStream2::from(input);
quote! {
{
#input
}
}
} else {
quote! {
()
}
}
.into()
}
};
}
define_config_macro!(server_only if any(feature = "ssr", feature = "liveview"));
define_config_macro!(client if any(feature = "desktop", feature = "web", feature = "mobile"));
define_config_macro!(web if feature = "web");
define_config_macro!(desktop if feature = "desktop");
define_config_macro!(mobile if feature = "mobile");
define_config_macro!(fullstack if feature = "fullstack");
define_config_macro!(ssr if feature = "ssr");
define_config_macro!(liveview if feature = "liveview");
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/src/lib.rs | packages/generational-box/src/lib.rs | #![doc = include_str!("../README.md")]
#![warn(missing_docs)]
use parking_lot::Mutex;
use std::{
fmt::Debug,
marker::PhantomData,
num::NonZeroU64,
ops::{Deref, DerefMut},
sync::Arc,
};
pub use error::*;
pub use references::*;
pub use sync::SyncStorage;
pub use unsync::UnsyncStorage;
mod entry;
mod error;
mod references;
mod sync;
mod unsync;
/// The type erased id of a generational box.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct GenerationalBoxId {
data_ptr: *const (),
generation: NonZeroU64,
}
// Safety: GenerationalBoxId is Send and Sync because there is no way to access the pointer.
unsafe impl Send for GenerationalBoxId {}
unsafe impl Sync for GenerationalBoxId {}
impl Debug for GenerationalBoxId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("{:?}@{:?}", self.data_ptr, self.generation))?;
Ok(())
}
}
/// The core Copy state type. The generational box will be dropped when the [Owner] is dropped.
pub struct GenerationalBox<T, S: 'static = UnsyncStorage> {
raw: GenerationalPointer<S>,
_marker: PhantomData<T>,
}
impl<T, S: AnyStorage> Debug for GenerationalBox<T, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.raw.fmt(f)
}
}
impl<T, S: Storage<T>> GenerationalBox<T, S> {
/// Create a new generational box by leaking a value into the storage. This is useful for creating
/// a box that needs to be manually dropped with no owners.
#[track_caller]
pub fn leak(value: T, location: &'static std::panic::Location<'static>) -> Self {
let location = S::new(value, location);
Self {
raw: location,
_marker: PhantomData,
}
}
/// Create a new reference counted generational box by leaking a value into the storage. This is useful for creating
/// a box that needs to be manually dropped with no owners.
#[track_caller]
pub fn leak_rc(value: T, location: &'static std::panic::Location<'static>) -> Self {
let location = S::new_rc(value, location);
Self {
raw: location,
_marker: PhantomData,
}
}
/// Get the raw pointer to the value.
pub fn raw_ptr(&self) -> *const () {
self.raw.storage.data_ptr()
}
/// Get the id of the generational box.
pub fn id(&self) -> GenerationalBoxId {
self.raw.id()
}
/// Try to read the value. Returns an error if the value is no longer valid.
#[track_caller]
pub fn try_read(&self) -> Result<S::Ref<'static, T>, BorrowError> {
self.raw.try_read()
}
/// Read the value. Panics if the value is no longer valid.
#[track_caller]
pub fn read(&self) -> S::Ref<'static, T> {
self.try_read().unwrap()
}
/// Try to write the value. Returns None if the value is no longer valid.
#[track_caller]
pub fn try_write(&self) -> Result<S::Mut<'static, T>, BorrowMutError> {
self.raw.try_write()
}
/// Write the value. Panics if the value is no longer valid.
#[track_caller]
pub fn write(&self) -> S::Mut<'static, T> {
self.try_write().unwrap()
}
/// Set the value. Panics if the value is no longer valid.
#[track_caller]
pub fn set(&self, value: T)
where
T: 'static,
{
*self.write() = value;
}
/// Drop the value out of the generational box and invalidate the generational box.
pub fn manually_drop(&self)
where
T: 'static,
{
self.raw.recycle();
}
/// Get a reference to the value
#[track_caller]
pub fn leak_reference(&self) -> BorrowResult<GenerationalBox<T, S>> {
Ok(Self {
raw: S::new_reference(self.raw)?,
_marker: std::marker::PhantomData,
})
}
/// Change this box to point to another generational box
pub fn point_to(&self, other: GenerationalBox<T, S>) -> BorrowResult {
S::change_reference(self.raw, other.raw)
}
}
impl<T, S> GenerationalBox<T, S> {
/// Returns true if the pointer is equal to the other pointer.
pub fn ptr_eq(&self, other: &Self) -> bool
where
S: AnyStorage,
{
self.raw == other.raw
}
/// Try to get the location the generational box was created at. In release mode this will always return None.
pub fn created_at(&self) -> Option<&'static std::panic::Location<'static>> {
self.raw.location.created_at()
}
}
impl<T, S> Copy for GenerationalBox<T, S> {}
impl<T, S> Clone for GenerationalBox<T, S> {
fn clone(&self) -> Self {
*self
}
}
/// A trait for a storage backing type. (RefCell, RwLock, etc.)
pub trait Storage<Data = ()>: AnyStorage {
/// Try to read the value. Returns None if the value is no longer valid.
fn try_read(pointer: GenerationalPointer<Self>) -> BorrowResult<Self::Ref<'static, Data>>;
/// Try to write the value. Returns None if the value is no longer valid.
fn try_write(pointer: GenerationalPointer<Self>) -> BorrowMutResult<Self::Mut<'static, Data>>;
/// Create a new memory location. This will either create a new memory location or recycle an old one.
fn new(
value: Data,
caller: &'static std::panic::Location<'static>,
) -> GenerationalPointer<Self>;
/// Create a new reference counted memory location. This will either create a new memory location or recycle an old one.
fn new_rc(
value: Data,
caller: &'static std::panic::Location<'static>,
) -> GenerationalPointer<Self>;
/// Reference another location if the location is valid
///
/// This method may return an error if the other box is no longer valid or it is already borrowed mutably.
fn new_reference(inner: GenerationalPointer<Self>) -> BorrowResult<GenerationalPointer<Self>>;
/// Change the reference a signal is pointing to
///
/// This method may return an error if the other box is no longer valid or it is already borrowed mutably.
fn change_reference(
pointer: GenerationalPointer<Self>,
rc_pointer: GenerationalPointer<Self>,
) -> BorrowResult;
}
/// A trait for any storage backing type.
pub trait AnyStorage: Default {
/// The reference this storage type returns.
type Ref<'a, T: ?Sized + 'a>: Deref<Target = T>;
/// The mutable reference this storage type returns.
type Mut<'a, T: ?Sized + 'a>: DerefMut<Target = T>;
/// Downcast a reference in a Ref to a more specific lifetime
///
/// This function enforces the variance of the lifetime parameter `'a` in Ref. Rust will typically infer this cast with a concrete type, but it cannot with a generic type.
fn downcast_lifetime_ref<'a: 'b, 'b, T: ?Sized + 'a>(
ref_: Self::Ref<'a, T>,
) -> Self::Ref<'b, T>;
/// Downcast a mutable reference in a RefMut to a more specific lifetime
///
/// This function enforces the variance of the lifetime parameter `'a` in Mut. Rust will typically infer this cast with a concrete type, but it cannot with a generic type.
fn downcast_lifetime_mut<'a: 'b, 'b, T: ?Sized + 'a>(
mut_: Self::Mut<'a, T>,
) -> Self::Mut<'b, T>;
/// Try to map the mutable ref.
fn try_map_mut<T: ?Sized, U: ?Sized>(
mut_ref: Self::Mut<'_, T>,
f: impl FnOnce(&mut T) -> Option<&mut U>,
) -> Option<Self::Mut<'_, U>>;
/// Map the mutable ref.
fn map_mut<T: ?Sized, U: ?Sized>(
mut_ref: Self::Mut<'_, T>,
f: impl FnOnce(&mut T) -> &mut U,
) -> Self::Mut<'_, U> {
Self::try_map_mut(mut_ref, |v| Some(f(v))).unwrap()
}
/// Try to map the ref.
fn try_map<T: ?Sized, U: ?Sized>(
ref_: Self::Ref<'_, T>,
f: impl FnOnce(&T) -> Option<&U>,
) -> Option<Self::Ref<'_, U>>;
/// Map the ref.
fn map<T: ?Sized, U: ?Sized>(
ref_: Self::Ref<'_, T>,
f: impl FnOnce(&T) -> &U,
) -> Self::Ref<'_, U> {
Self::try_map(ref_, |v| Some(f(v))).unwrap()
}
/// Get the data pointer. No guarantees are made about the data pointer. It should only be used for debugging.
fn data_ptr(&self) -> *const ();
/// Recycle a memory location. This will drop the memory location and return it to the runtime.
fn recycle(location: GenerationalPointer<Self>);
/// Create a new owner. The owner will be responsible for dropping all of the generational boxes that it creates.
fn owner() -> Owner<Self>
where
Self: 'static,
{
Owner(Arc::new(Mutex::new(OwnerInner {
owned: Default::default(),
})))
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct GenerationalLocation {
/// The generation this location is associated with. Using the location after this generation is invalidated will return errors.
generation: NonZeroU64,
#[cfg(any(debug_assertions, feature = "debug_ownership"))]
created_at: &'static std::panic::Location<'static>,
}
impl GenerationalLocation {
pub(crate) fn created_at(&self) -> Option<&'static std::panic::Location<'static>> {
#[cfg(debug_assertions)]
{
Some(self.created_at)
}
#[cfg(not(debug_assertions))]
{
None
}
}
}
/// A pointer to a specific generational box and generation in that box.
pub struct GenerationalPointer<S: 'static = UnsyncStorage> {
/// The storage that is backing this location
storage: &'static S,
/// The location of the data
location: GenerationalLocation,
}
impl<S: AnyStorage + 'static> PartialEq for GenerationalPointer<S> {
fn eq(&self, other: &Self) -> bool {
self.storage.data_ptr() == other.storage.data_ptr()
&& self.location.generation == other.location.generation
}
}
impl<S: AnyStorage + 'static> Debug for GenerationalPointer<S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{:?}@{:?}",
self.storage.data_ptr(),
self.location.generation
))
}
}
impl<S: 'static> Clone for GenerationalPointer<S> {
fn clone(&self) -> Self {
*self
}
}
impl<S: 'static> Copy for GenerationalPointer<S> {}
impl<S> GenerationalPointer<S> {
#[track_caller]
fn try_read<T>(self) -> Result<S::Ref<'static, T>, BorrowError>
where
S: Storage<T>,
{
S::try_read(self)
}
#[track_caller]
fn try_write<T>(self) -> Result<S::Mut<'static, T>, BorrowMutError>
where
S: Storage<T>,
{
S::try_write(self)
}
fn recycle(self)
where
S: AnyStorage,
{
S::recycle(self);
}
fn id(&self) -> GenerationalBoxId
where
S: AnyStorage,
{
GenerationalBoxId {
data_ptr: self.storage.data_ptr(),
generation: self.location.generation,
}
}
}
struct OwnerInner<S: AnyStorage + 'static> {
owned: Vec<GenerationalPointer<S>>,
}
impl<S: AnyStorage> Drop for OwnerInner<S> {
fn drop(&mut self) {
for location in self.owned.drain(..) {
location.recycle();
}
}
}
/// Owner: Handles dropping generational boxes. The owner acts like a runtime lifetime guard. Any states that you create with an owner will be dropped when that owner is dropped.
pub struct Owner<S: AnyStorage + 'static = UnsyncStorage>(Arc<Mutex<OwnerInner<S>>>);
impl<S: AnyStorage> Default for Owner<S> {
fn default() -> Self {
S::owner()
}
}
impl<S: AnyStorage> Clone for Owner<S> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<S: AnyStorage> Owner<S> {
/// Insert a value into the store. The value will be dropped when the owner is dropped.
#[track_caller]
pub fn insert<T>(&self, value: T) -> GenerationalBox<T, S>
where
S: Storage<T>,
{
self.insert_with_caller(value, std::panic::Location::caller())
}
/// Create a new reference counted box. The box will be dropped when all references are dropped.
#[track_caller]
pub fn insert_rc<T>(&self, value: T) -> GenerationalBox<T, S>
where
S: Storage<T>,
{
self.insert_rc_with_caller(value, std::panic::Location::caller())
}
/// Insert a value into the store with a specific location blamed for creating the value. The value will be dropped when the owner is dropped.
pub fn insert_rc_with_caller<T>(
&self,
value: T,
caller: &'static std::panic::Location<'static>,
) -> GenerationalBox<T, S>
where
S: Storage<T>,
{
let location = S::new_rc(value, caller);
self.0.lock().owned.push(location);
GenerationalBox {
raw: location,
_marker: std::marker::PhantomData,
}
}
/// Insert a value into the store with a specific location blamed for creating the value. The value will be dropped when the owner is dropped.
pub fn insert_with_caller<T>(
&self,
value: T,
caller: &'static std::panic::Location<'static>,
) -> GenerationalBox<T, S>
where
S: Storage<T>,
{
let location = S::new(value, caller);
self.0.lock().owned.push(location);
GenerationalBox {
raw: location,
_marker: PhantomData,
}
}
/// Create a new reference to an existing box. The reference will be dropped when the owner is dropped.
///
/// This method may return an error if the other box is no longer valid or it is already borrowed mutably.
#[track_caller]
pub fn insert_reference<T>(
&self,
other: GenerationalBox<T, S>,
) -> BorrowResult<GenerationalBox<T, S>>
where
S: Storage<T>,
{
let location = other.leak_reference()?;
self.0.lock().owned.push(location.raw);
Ok(location)
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/src/unsync.rs | packages/generational-box/src/unsync.rs | use crate::{
entry::{MemoryLocationBorrowInfo, RcStorageEntry, StorageEntry},
error,
references::{GenerationalRef, GenerationalRefMut},
AnyStorage, BorrowError, BorrowMutError, BorrowMutResult, BorrowResult, GenerationalLocation,
GenerationalPointer, Storage, ValueDroppedError,
};
use std::{
any::Any,
cell::{Ref, RefCell, RefMut},
fmt::Debug,
num::NonZeroU64,
};
type RefCellStorageEntryRef = Ref<'static, StorageEntry<RefCellStorageEntryData>>;
type RefCellStorageEntryMut = RefMut<'static, StorageEntry<RefCellStorageEntryData>>;
type AnyRef = Ref<'static, Box<dyn Any>>;
type AnyRefMut = RefMut<'static, Box<dyn Any>>;
thread_local! {
static UNSYNC_RUNTIME: RefCell<Vec<&'static UnsyncStorage>> = const { RefCell::new(Vec::new()) };
}
#[derive(Default)]
pub(crate) enum RefCellStorageEntryData {
Reference(GenerationalPointer<UnsyncStorage>),
Rc(RcStorageEntry<Box<dyn Any>>),
Data(Box<dyn Any>),
#[default]
Empty,
}
impl Debug for RefCellStorageEntryData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Reference(pointer) => write!(f, "Reference({:?})", pointer.location),
Self::Rc(_) => write!(f, "Rc"),
Self::Data(_) => write!(f, "Data"),
Self::Empty => write!(f, "Empty"),
}
}
}
/// A unsync storage. This is the default storage type.
#[derive(Default)]
pub struct UnsyncStorage {
borrow_info: MemoryLocationBorrowInfo,
data: RefCell<StorageEntry<RefCellStorageEntryData>>,
}
impl UnsyncStorage {
pub(crate) fn read(
pointer: GenerationalPointer<Self>,
) -> BorrowResult<(AnyRef, GenerationalPointer<Self>)> {
Self::get_split_ref(pointer).map(|(resolved, guard)| {
(
Ref::map(guard, |data| match &data.data {
RefCellStorageEntryData::Data(data) => data,
RefCellStorageEntryData::Rc(data) => &data.data,
_ => unreachable!(),
}),
resolved,
)
})
}
pub(crate) fn get_split_ref(
mut pointer: GenerationalPointer<Self>,
) -> BorrowResult<(GenerationalPointer<Self>, RefCellStorageEntryRef)> {
loop {
let borrow = pointer
.storage
.data
.try_borrow()
.map_err(|_| pointer.storage.borrow_info.borrow_error())?;
if !borrow.valid(&pointer.location) {
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
pointer.location,
)));
}
match &borrow.data {
// If this is a reference, keep traversing the pointers
RefCellStorageEntryData::Reference(data) => {
pointer = *data;
}
// Otherwise return the value
RefCellStorageEntryData::Rc(_) | RefCellStorageEntryData::Data(_) => {
return Ok((pointer, borrow));
}
RefCellStorageEntryData::Empty => {
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
pointer.location,
)));
}
}
}
}
pub(crate) fn write(
pointer: GenerationalPointer<Self>,
) -> BorrowMutResult<(AnyRefMut, GenerationalPointer<Self>)> {
Self::get_split_mut(pointer).map(|(resolved, guard)| {
(
RefMut::map(guard, |data| match &mut data.data {
RefCellStorageEntryData::Data(data) => data,
RefCellStorageEntryData::Rc(data) => &mut data.data,
_ => unreachable!(),
}),
resolved,
)
})
}
pub(crate) fn get_split_mut(
mut pointer: GenerationalPointer<Self>,
) -> BorrowMutResult<(GenerationalPointer<Self>, RefCellStorageEntryMut)> {
loop {
let borrow = pointer
.storage
.data
.try_borrow_mut()
.map_err(|_| pointer.storage.borrow_info.borrow_mut_error())?;
if !borrow.valid(&pointer.location) {
return Err(BorrowMutError::Dropped(
ValueDroppedError::new_for_location(pointer.location),
));
}
match &borrow.data {
// If this is a reference, keep traversing the pointers
RefCellStorageEntryData::Reference(data) => {
pointer = *data;
}
// Otherwise return the value
RefCellStorageEntryData::Data(_) | RefCellStorageEntryData::Rc(_) => {
return Ok((pointer, borrow));
}
RefCellStorageEntryData::Empty => {
return Err(BorrowMutError::Dropped(
ValueDroppedError::new_for_location(pointer.location),
));
}
}
}
}
fn create_new(
value: RefCellStorageEntryData,
#[allow(unused)] caller: &'static std::panic::Location<'static>,
) -> GenerationalPointer<Self> {
UNSYNC_RUNTIME.with(|runtime| match runtime.borrow_mut().pop() {
Some(storage) => {
let mut write = storage.data.borrow_mut();
let location = GenerationalLocation {
generation: write.generation(),
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
created_at: caller,
};
write.data = value;
GenerationalPointer { storage, location }
}
None => {
let storage: &'static Self = &*Box::leak(Box::new(Self {
borrow_info: Default::default(),
data: RefCell::new(StorageEntry::new(value)),
}));
let location = GenerationalLocation {
generation: NonZeroU64::MIN,
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
created_at: caller,
};
GenerationalPointer { storage, location }
}
})
}
}
impl AnyStorage for UnsyncStorage {
type Ref<'a, R: ?Sized + 'a> = GenerationalRef<Ref<'a, R>>;
type Mut<'a, W: ?Sized + 'a> = GenerationalRefMut<RefMut<'a, W>>;
fn downcast_lifetime_ref<'a: 'b, 'b, T: ?Sized + 'a>(
ref_: Self::Ref<'a, T>,
) -> Self::Ref<'b, T> {
ref_
}
fn downcast_lifetime_mut<'a: 'b, 'b, T: ?Sized + 'a>(
mut_: Self::Mut<'a, T>,
) -> Self::Mut<'b, T> {
mut_
}
fn map<T: ?Sized, U: ?Sized>(
ref_: Self::Ref<'_, T>,
f: impl FnOnce(&T) -> &U,
) -> Self::Ref<'_, U> {
ref_.map(|inner| Ref::map(inner, f))
}
fn map_mut<T: ?Sized, U: ?Sized>(
mut_ref: Self::Mut<'_, T>,
f: impl FnOnce(&mut T) -> &mut U,
) -> Self::Mut<'_, U> {
mut_ref.map(|inner| RefMut::map(inner, f))
}
fn try_map<I: ?Sized, U: ?Sized>(
_self: Self::Ref<'_, I>,
f: impl FnOnce(&I) -> Option<&U>,
) -> Option<Self::Ref<'_, U>> {
_self.try_map(|inner| Ref::filter_map(inner, f).ok())
}
fn try_map_mut<I: ?Sized, U: ?Sized>(
mut_ref: Self::Mut<'_, I>,
f: impl FnOnce(&mut I) -> Option<&mut U>,
) -> Option<Self::Mut<'_, U>> {
mut_ref.try_map(|inner| RefMut::filter_map(inner, f).ok())
}
fn data_ptr(&self) -> *const () {
self.data.as_ptr() as *const ()
}
fn recycle(pointer: GenerationalPointer<Self>) {
let mut borrow_mut = pointer.storage.data.borrow_mut();
// First check if the generation is still valid
if !borrow_mut.valid(&pointer.location) {
return;
}
borrow_mut.increment_generation();
// Then decrement the reference count or drop the value if it's the last reference
match &mut borrow_mut.data {
// If this is the original reference, drop the value
RefCellStorageEntryData::Data(_) => borrow_mut.data = RefCellStorageEntryData::Empty,
// If this is a rc, just ignore the drop
RefCellStorageEntryData::Rc(_) => {}
// If this is a reference, decrement the reference count
RefCellStorageEntryData::Reference(reference) => {
let reference = *reference;
drop(borrow_mut);
drop_ref(reference);
}
RefCellStorageEntryData::Empty => {}
}
UNSYNC_RUNTIME.with(|runtime| runtime.borrow_mut().push(pointer.storage));
}
}
fn drop_ref(pointer: GenerationalPointer<UnsyncStorage>) {
let mut borrow_mut = pointer.storage.data.borrow_mut();
// First check if the generation is still valid
if !borrow_mut.valid(&pointer.location) {
return;
}
if let RefCellStorageEntryData::Rc(entry) = &mut borrow_mut.data {
// Decrement the reference count
if entry.drop_ref() {
// If the reference count is now zero, drop the value
borrow_mut.data = RefCellStorageEntryData::Empty;
UNSYNC_RUNTIME.with(|runtime| runtime.borrow_mut().push(pointer.storage));
}
} else {
unreachable!("References should always point to a data entry directly",);
}
}
impl<T: 'static> Storage<T> for UnsyncStorage {
#[track_caller]
fn try_read(
pointer: GenerationalPointer<Self>,
) -> Result<Self::Ref<'static, T>, error::BorrowError> {
let (read, pointer) = Self::read(pointer)?;
let ref_ = Ref::filter_map(read, |any| {
// Then try to downcast
any.downcast_ref()
});
match ref_ {
Ok(guard) => Ok(GenerationalRef::new(
guard,
pointer.storage.borrow_info.borrow_guard(),
)),
Err(_) => Err(error::BorrowError::Dropped(
error::ValueDroppedError::new_for_location(pointer.location),
)),
}
}
#[track_caller]
fn try_write(
pointer: GenerationalPointer<Self>,
) -> Result<Self::Mut<'static, T>, error::BorrowMutError> {
let (write, pointer) = Self::write(pointer)?;
let ref_mut = RefMut::filter_map(write, |any| {
// Then try to downcast
any.downcast_mut()
});
match ref_mut {
Ok(guard) => Ok(GenerationalRefMut::new(
guard,
pointer.storage.borrow_info.borrow_mut_guard(),
)),
Err(_) => Err(error::BorrowMutError::Dropped(
error::ValueDroppedError::new_for_location(pointer.location),
)),
}
}
fn new(value: T, caller: &'static std::panic::Location<'static>) -> GenerationalPointer<Self> {
Self::create_new(RefCellStorageEntryData::Data(Box::new(value)), caller)
}
fn new_rc(
value: T,
caller: &'static std::panic::Location<'static>,
) -> GenerationalPointer<Self> {
// Create the data that the rc points to
let data = Self::create_new(
RefCellStorageEntryData::Rc(RcStorageEntry::new(Box::new(value))),
caller,
);
Self::create_new(RefCellStorageEntryData::Reference(data), caller)
}
fn new_reference(
pointer: GenerationalPointer<Self>,
) -> BorrowResult<GenerationalPointer<Self>> {
// Chase the reference to get the final location
let (pointer, value) = Self::get_split_ref(pointer)?;
if let RefCellStorageEntryData::Rc(data) = &value.data {
data.add_ref();
} else {
unreachable!()
}
Ok(Self::create_new(
RefCellStorageEntryData::Reference(pointer),
pointer
.location
.created_at()
.unwrap_or(std::panic::Location::caller()),
))
}
fn change_reference(
location: GenerationalPointer<Self>,
other: GenerationalPointer<Self>,
) -> BorrowResult {
if location == other {
return Ok(());
}
let (other_final, other_write) = Self::get_split_ref(other)?;
let mut write = location.storage.data.borrow_mut();
// First check if the generation is still valid
if !write.valid(&location.location) {
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
location.location,
)));
}
if let (RefCellStorageEntryData::Reference(reference), RefCellStorageEntryData::Rc(data)) =
(&mut write.data, &other_write.data)
{
if reference == &other_final {
return Ok(());
}
drop_ref(*reference);
*reference = other_final;
data.add_ref();
} else {
tracing::trace!(
"References should always point to a data entry directly found {:?} instead",
other_write.data
);
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
other_final.location,
)));
}
Ok(())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/src/sync.rs | packages/generational-box/src/sync.rs | use parking_lot::{
MappedRwLockReadGuard, MappedRwLockWriteGuard, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard,
};
use std::{
any::Any,
fmt::Debug,
num::NonZeroU64,
sync::{Arc, OnceLock},
};
use crate::{
entry::{MemoryLocationBorrowInfo, RcStorageEntry, StorageEntry},
error::{self, ValueDroppedError},
references::{GenerationalRef, GenerationalRefMut},
AnyStorage, BorrowError, BorrowMutError, BorrowMutResult, BorrowResult, GenerationalLocation,
GenerationalPointer, Storage,
};
type RwLockStorageEntryRef = RwLockReadGuard<'static, StorageEntry<RwLockStorageEntryData>>;
type RwLockStorageEntryMut = RwLockWriteGuard<'static, StorageEntry<RwLockStorageEntryData>>;
type AnyRef = MappedRwLockReadGuard<'static, Box<dyn Any + Send + Sync + 'static>>;
type AnyRefMut = MappedRwLockWriteGuard<'static, Box<dyn Any + Send + Sync + 'static>>;
#[derive(Default)]
pub(crate) enum RwLockStorageEntryData {
Reference(GenerationalPointer<SyncStorage>),
Rc(RcStorageEntry<Box<dyn Any + Send + Sync>>),
Data(Box<dyn Any + Send + Sync>),
#[default]
Empty,
}
impl Debug for RwLockStorageEntryData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Reference(location) => write!(f, "Reference({location:?})"),
Self::Rc(_) => write!(f, "Rc"),
Self::Data(_) => write!(f, "Data"),
Self::Empty => write!(f, "Empty"),
}
}
}
impl RwLockStorageEntryData {
pub const fn new_full(data: Box<dyn Any + Send + Sync>) -> Self {
Self::Data(data)
}
}
/// A thread safe storage. This is slower than the unsync storage, but allows you to share the value between threads.
#[derive(Default)]
pub struct SyncStorage {
borrow_info: MemoryLocationBorrowInfo,
data: RwLock<StorageEntry<RwLockStorageEntryData>>,
}
impl SyncStorage {
pub(crate) fn read(
pointer: GenerationalPointer<Self>,
) -> BorrowResult<(AnyRef, GenerationalPointer<Self>)> {
Self::get_split_ref(pointer).map(|(resolved, guard)| {
(
RwLockReadGuard::map(guard, |data| match &data.data {
RwLockStorageEntryData::Data(data) => data,
RwLockStorageEntryData::Rc(data) => &data.data,
_ => unreachable!(),
}),
resolved,
)
})
}
pub(crate) fn get_split_ref(
mut pointer: GenerationalPointer<Self>,
) -> BorrowResult<(GenerationalPointer<Self>, RwLockStorageEntryRef)> {
loop {
let borrow = pointer.storage.data.read();
if !borrow.valid(&pointer.location) {
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
pointer.location,
)));
}
match &borrow.data {
// If this is a reference, keep traversing the pointers
RwLockStorageEntryData::Reference(data) => {
pointer = *data;
}
// Otherwise return the value
RwLockStorageEntryData::Data(_) | RwLockStorageEntryData::Rc(_) => {
return Ok((pointer, borrow));
}
RwLockStorageEntryData::Empty => {
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
pointer.location,
)));
}
}
}
}
pub(crate) fn write(
pointer: GenerationalPointer<Self>,
) -> BorrowMutResult<(AnyRefMut, GenerationalPointer<Self>)> {
Self::get_split_mut(pointer).map(|(resolved, guard)| {
(
RwLockWriteGuard::map(guard, |data| match &mut data.data {
RwLockStorageEntryData::Data(data) => data,
RwLockStorageEntryData::Rc(data) => &mut data.data,
_ => unreachable!(),
}),
resolved,
)
})
}
pub(crate) fn get_split_mut(
mut pointer: GenerationalPointer<Self>,
) -> BorrowMutResult<(GenerationalPointer<Self>, RwLockStorageEntryMut)> {
loop {
let borrow = pointer.storage.data.write();
if !borrow.valid(&pointer.location) {
return Err(BorrowMutError::Dropped(
ValueDroppedError::new_for_location(pointer.location),
));
}
match &borrow.data {
// If this is a reference, keep traversing the pointers
RwLockStorageEntryData::Reference(data) => {
pointer = *data;
}
// Otherwise return the value
RwLockStorageEntryData::Data(_) | RwLockStorageEntryData::Rc(_) => {
return Ok((pointer, borrow));
}
RwLockStorageEntryData::Empty => {
return Err(BorrowMutError::Dropped(
ValueDroppedError::new_for_location(pointer.location),
));
}
}
}
}
fn create_new(
value: RwLockStorageEntryData,
#[allow(unused)] caller: &'static std::panic::Location<'static>,
) -> GenerationalPointer<Self> {
match sync_runtime().lock().pop() {
Some(storage) => {
let mut write = storage.data.write();
let location = GenerationalLocation {
generation: write.generation(),
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
created_at: caller,
};
write.data = value;
GenerationalPointer { storage, location }
}
None => {
let storage: &'static Self = &*Box::leak(Box::new(Self {
borrow_info: Default::default(),
data: RwLock::new(StorageEntry::new(value)),
}));
let location = GenerationalLocation {
generation: NonZeroU64::MIN,
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
created_at: caller,
};
GenerationalPointer { storage, location }
}
}
}
}
static SYNC_RUNTIME: OnceLock<Arc<Mutex<Vec<&'static SyncStorage>>>> = OnceLock::new();
fn sync_runtime() -> &'static Arc<Mutex<Vec<&'static SyncStorage>>> {
SYNC_RUNTIME.get_or_init(|| Arc::new(Mutex::new(Vec::new())))
}
impl AnyStorage for SyncStorage {
type Ref<'a, R: ?Sized + 'a> = GenerationalRef<MappedRwLockReadGuard<'a, R>>;
type Mut<'a, W: ?Sized + 'a> = GenerationalRefMut<MappedRwLockWriteGuard<'a, W>>;
fn downcast_lifetime_ref<'a: 'b, 'b, T: ?Sized + 'b>(
ref_: Self::Ref<'a, T>,
) -> Self::Ref<'b, T> {
ref_
}
fn downcast_lifetime_mut<'a: 'b, 'b, T: ?Sized + 'a>(
mut_: Self::Mut<'a, T>,
) -> Self::Mut<'b, T> {
mut_
}
fn map<T: ?Sized, U: ?Sized>(
ref_: Self::Ref<'_, T>,
f: impl FnOnce(&T) -> &U,
) -> Self::Ref<'_, U> {
ref_.map(|inner| MappedRwLockReadGuard::map(inner, f))
}
fn map_mut<T: ?Sized, U: ?Sized>(
mut_ref: Self::Mut<'_, T>,
f: impl FnOnce(&mut T) -> &mut U,
) -> Self::Mut<'_, U> {
mut_ref.map(|inner| MappedRwLockWriteGuard::map(inner, f))
}
fn try_map<I: ?Sized, U: ?Sized>(
ref_: Self::Ref<'_, I>,
f: impl FnOnce(&I) -> Option<&U>,
) -> Option<Self::Ref<'_, U>> {
ref_.try_map(|inner| MappedRwLockReadGuard::try_map(inner, f).ok())
}
fn try_map_mut<I: ?Sized, U: ?Sized>(
mut_ref: Self::Mut<'_, I>,
f: impl FnOnce(&mut I) -> Option<&mut U>,
) -> Option<Self::Mut<'_, U>> {
mut_ref.try_map(|inner| MappedRwLockWriteGuard::try_map(inner, f).ok())
}
fn data_ptr(&self) -> *const () {
self.data.data_ptr() as *const ()
}
fn recycle(pointer: GenerationalPointer<Self>) {
let mut borrow_mut = pointer.storage.data.write();
// First check if the generation is still valid
if !borrow_mut.valid(&pointer.location) {
return;
}
borrow_mut.increment_generation();
// Then decrement the reference count or drop the value if it's the last reference
match &mut borrow_mut.data {
// If this is the original reference, drop the value
RwLockStorageEntryData::Data(_) => borrow_mut.data = RwLockStorageEntryData::Empty,
// If this is a rc, just ignore the drop
RwLockStorageEntryData::Rc(_) => {}
// If this is a reference, decrement the reference count
RwLockStorageEntryData::Reference(reference) => {
drop_ref(*reference);
}
RwLockStorageEntryData::Empty => {}
}
sync_runtime().lock().push(pointer.storage);
}
}
fn drop_ref(pointer: GenerationalPointer<SyncStorage>) {
let mut borrow_mut = pointer.storage.data.write();
// First check if the generation is still valid
if !borrow_mut.valid(&pointer.location) {
return;
}
if let RwLockStorageEntryData::Rc(entry) = &mut borrow_mut.data {
// Decrement the reference count
if entry.drop_ref() {
// If the reference count is now zero, drop the value
borrow_mut.data = RwLockStorageEntryData::Empty;
sync_runtime().lock().push(pointer.storage);
}
} else {
unreachable!("References should always point to a data entry directly");
}
}
impl<T: Sync + Send + 'static> Storage<T> for SyncStorage {
#[track_caller]
fn try_read(
pointer: GenerationalPointer<Self>,
) -> Result<Self::Ref<'static, T>, error::BorrowError> {
let (read, pointer) = Self::read(pointer)?;
let read = MappedRwLockReadGuard::try_map(read, |any| {
// Then try to downcast
any.downcast_ref()
});
match read {
Ok(guard) => Ok(GenerationalRef::new(
guard,
pointer.storage.borrow_info.borrow_guard(),
)),
Err(_) => Err(error::BorrowError::Dropped(
ValueDroppedError::new_for_location(pointer.location),
)),
}
}
#[track_caller]
fn try_write(
pointer: GenerationalPointer<Self>,
) -> Result<Self::Mut<'static, T>, error::BorrowMutError> {
let (write, pointer) = Self::write(pointer)?;
let write = MappedRwLockWriteGuard::try_map(write, |any| {
// Then try to downcast
any.downcast_mut()
});
match write {
Ok(guard) => Ok(GenerationalRefMut::new(
guard,
pointer.storage.borrow_info.borrow_mut_guard(),
)),
Err(_) => Err(error::BorrowMutError::Dropped(
ValueDroppedError::new_for_location(pointer.location),
)),
}
}
fn new(value: T, caller: &'static std::panic::Location<'static>) -> GenerationalPointer<Self> {
Self::create_new(RwLockStorageEntryData::new_full(Box::new(value)), caller)
}
fn new_rc(
value: T,
caller: &'static std::panic::Location<'static>,
) -> GenerationalPointer<Self> {
// Create the data that the rc points to
let data = Self::create_new(
RwLockStorageEntryData::Rc(RcStorageEntry::new(Box::new(value))),
caller,
);
Self::create_new(RwLockStorageEntryData::Reference(data), caller)
}
fn new_reference(
location: GenerationalPointer<Self>,
) -> BorrowResult<GenerationalPointer<Self>> {
// Chase the reference to get the final location
let (location, value) = Self::get_split_ref(location)?;
if let RwLockStorageEntryData::Rc(data) = &value.data {
data.add_ref();
} else {
unreachable!()
}
Ok(Self::create_new(
RwLockStorageEntryData::Reference(location),
location
.location
.created_at()
.unwrap_or(std::panic::Location::caller()),
))
}
fn change_reference(
location: GenerationalPointer<Self>,
other: GenerationalPointer<Self>,
) -> BorrowResult {
if location == other {
return Ok(());
}
let (other_final, other_write) = Self::get_split_ref(other)?;
let mut write = location.storage.data.write();
// First check if the generation is still valid
if !write.valid(&location.location) {
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
location.location,
)));
}
if let (RwLockStorageEntryData::Reference(reference), RwLockStorageEntryData::Rc(data)) =
(&mut write.data, &other_write.data)
{
if reference == &other_final {
return Ok(());
}
drop_ref(*reference);
*reference = other_final;
data.add_ref();
} else {
tracing::trace!(
"References should always point to a data entry directly found {:?} instead",
other_write.data
);
return Err(BorrowError::Dropped(ValueDroppedError::new_for_location(
other_final.location,
)));
}
Ok(())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/src/references.rs | packages/generational-box/src/references.rs | use std::{
fmt::{Debug, Display},
ops::{Deref, DerefMut},
};
/// A reference to a value in a generational box. This reference acts similarly to [`std::cell::Ref`], but has extra debug information
/// to track when all references to the value are created and dropped.
///
/// [`GenerationalRef`] implements [`Deref`] which means you can call methods on the inner value just like you would on a reference to the
/// inner value. If you need to get the inner reference directly, you can call [`GenerationalRef::deref`].
///
/// # Example
/// ```rust
/// # use generational_box::{Owner, UnsyncStorage, AnyStorage};
/// let owner = UnsyncStorage::owner();
/// let value = owner.insert(String::from("hello"));
/// let reference = value.read();
///
/// // You call methods like `as_str` on the reference just like you would with the inner String
/// assert_eq!(reference.as_str(), "hello");
/// ```
///
/// ## Matching on GenerationalRef
///
/// You need to get the inner reference with [`GenerationalRef::deref`] before you match the inner value. If you try to match without
/// calling [`GenerationalRef::deref`], you will get an error like this:
///
/// ```compile_fail
/// # use generational_box::{Owner, UnsyncStorage, AnyStorage};
/// enum Colors {
/// Red,
/// Green
/// }
/// let owner = UnsyncStorage::owner();
/// let value = owner.insert(Colors::Red);
/// let reference = value.read();
///
/// match reference {
/// // Since we are matching on the `GenerationalRef` type instead of &Colors, we can't match on the enum directly
/// Colors::Red => {}
/// Colors::Green => {}
/// }
/// ```
///
/// ```text
/// error[E0308]: mismatched types
/// --> packages/generational-box/tests/basic.rs:25:9
/// |
/// 2 | Red,
/// | --- unit variant defined here
/// ...
/// 3 | match reference {
/// | --------- this expression has type `GenerationalRef<Ref<'_, Colors>>`
/// 4 | // Since we are matching on the `GenerationalRef` type instead of &Colors, we can't match on the enum directly
/// 5 | Colors::Red => {}
/// | ^^^^^^^^^^^ expected `GenerationalRef<Ref<'_, Colors>>`, found `Colors`
/// |
/// = note: expected struct `GenerationalRef<Ref<'_, Colors>>`
/// found enum `Colors`
/// ```
///
/// Instead, you need to deref the reference to get the inner value **before** you match on it:
///
/// ```rust
/// use std::ops::Deref;
/// # use generational_box::{AnyStorage, Owner, UnsyncStorage};
/// enum Colors {
/// Red,
/// Green
/// }
/// let owner = UnsyncStorage::owner();
/// let value = owner.insert(Colors::Red);
/// let reference = value.read();
///
/// // Deref converts the `GenerationalRef` into a `&Colors`
/// match reference.deref() {
/// // Now we can match on the inner value
/// Colors::Red => {}
/// Colors::Green => {}
/// }
/// ```
pub struct GenerationalRef<R> {
pub(crate) inner: R,
guard: GenerationalRefBorrowGuard,
}
impl<T: ?Sized, R: Deref<Target = T>> GenerationalRef<R> {
pub(crate) fn new(inner: R, guard: GenerationalRefBorrowGuard) -> Self {
Self { inner, guard }
}
/// Map the inner value to a new type
pub fn map<R2, F: FnOnce(R) -> R2>(self, f: F) -> GenerationalRef<R2> {
GenerationalRef {
inner: f(self.inner),
guard: self.guard,
}
}
/// Try to map the inner value to a new type
pub fn try_map<R2, F: FnOnce(R) -> Option<R2>>(self, f: F) -> Option<GenerationalRef<R2>> {
f(self.inner).map(|inner| GenerationalRef {
inner,
guard: self.guard,
})
}
/// Clone the inner value. This requires that the inner value implements [`Clone`].
pub fn cloned(&self) -> T
where
T: Clone,
{
self.inner.deref().clone()
}
}
impl<T: ?Sized + Debug, R: Deref<Target = T>> Debug for GenerationalRef<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.deref().fmt(f)
}
}
impl<T: ?Sized + Display, R: Deref<Target = T>> Display for GenerationalRef<R> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.inner.deref().fmt(f)
}
}
impl<T: ?Sized, R: Deref<Target = T>> Deref for GenerationalRef<R> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner.deref()
}
}
pub(crate) struct GenerationalRefBorrowGuard {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
pub(crate) borrowed_at: &'static std::panic::Location<'static>,
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
pub(crate) borrowed_from: &'static crate::entry::MemoryLocationBorrowInfo,
}
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
impl Drop for GenerationalRefBorrowGuard {
fn drop(&mut self) {
self.borrowed_from.drop_borrow(self.borrowed_at);
}
}
/// A mutable reference to a value in a generational box. This reference acts similarly to [`std::cell::RefMut`], but has extra debug information
/// to track when all references to the value are created and dropped.
///
/// [`GenerationalRefMut`] implements [`DerefMut`] which means you can call methods on the inner value just like you would on a mutable reference
/// to the inner value. If you need to get the inner reference directly, you can call [`GenerationalRefMut::deref_mut`].
///
/// # Example
/// ```rust
/// # use generational_box::{Owner, UnsyncStorage, AnyStorage};
/// let owner = UnsyncStorage::owner();
/// let mut value = owner.insert(String::from("hello"));
/// let mut mutable_reference = value.write();
///
/// // You call methods like `push_str` on the reference just like you would with the inner String
/// mutable_reference.push_str("world");
/// ```
///
/// ## Matching on GenerationalMut
///
/// You need to get the inner mutable reference with [`GenerationalRefMut::deref_mut`] before you match the inner value. If you try to match
/// without calling [`GenerationalRefMut::deref_mut`], you will get an error like this:
///
/// ```compile_fail
/// # use generational_box::{Owner, UnsyncStorage, AnyStorage};
/// enum Colors {
/// Red(u32),
/// Green
/// }
/// let owner = UnsyncStorage::owner();
/// let mut value = owner.insert(Colors::Red(0));
/// let mut mutable_reference = value.write();
///
/// match mutable_reference {
/// // Since we are matching on the `GenerationalRefMut` type instead of &mut Colors, we can't match on the enum directly
/// Colors::Red(brightness) => *brightness += 1,
/// Colors::Green => {}
/// }
/// ```
///
/// ```text
/// error[E0308]: mismatched types
/// --> packages/generational-box/tests/basic.rs:25:9
/// |
/// 9 | match mutable_reference {
/// | ----------------- this expression has type `GenerationalRefMut<RefMut<'_, fn(u32) -> Colors {Colors::Red}>>`
/// 10 | // Since we are matching on the `GenerationalRefMut` type instead of &mut Colors, we can't match on the enum directly
/// 11 | Colors::Red(brightness) => *brightness += 1,
/// | ^^^^^^^^^^^^^^^^^^^^^^^ expected `GenerationalRefMut<RefMut<'_, ...>>`, found `Colors`
/// |
/// = note: expected struct `GenerationalRefMut<RefMut<'_, fn(u32) -> Colors {Colors::Red}>>`
/// found enum `Colors`
/// ```
///
/// Instead, you need to call deref mut on the reference to get the inner value **before** you match on it:
///
/// ```rust
/// use std::ops::DerefMut;
/// # use generational_box::{AnyStorage, Owner, UnsyncStorage};
/// enum Colors {
/// Red(u32),
/// Green
/// }
/// let owner = UnsyncStorage::owner();
/// let mut value = owner.insert(Colors::Red(0));
/// let mut mutable_reference = value.write();
///
/// // DerefMut converts the `GenerationalRefMut` into a `&mut Colors`
/// match mutable_reference.deref_mut() {
/// // Now we can match on the inner value
/// Colors::Red(brightness) => *brightness += 1,
/// Colors::Green => {}
/// }
/// ```
pub struct GenerationalRefMut<W> {
pub(crate) inner: W,
pub(crate) borrow: GenerationalRefBorrowMutGuard,
}
impl<T: ?Sized, R: DerefMut<Target = T>> GenerationalRefMut<R> {
pub(crate) fn new(inner: R, borrow: GenerationalRefBorrowMutGuard) -> Self {
Self { inner, borrow }
}
/// Map the inner value to a new type
pub fn map<R2, F: FnOnce(R) -> R2>(self, f: F) -> GenerationalRefMut<R2> {
GenerationalRefMut {
inner: f(self.inner),
borrow: self.borrow,
}
}
/// Try to map the inner value to a new type
pub fn try_map<R2, F: FnOnce(R) -> Option<R2>>(self, f: F) -> Option<GenerationalRefMut<R2>> {
f(self.inner).map(|inner| GenerationalRefMut {
inner,
borrow: self.borrow,
})
}
}
impl<T: ?Sized, W: DerefMut<Target = T>> Deref for GenerationalRefMut<W> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner.deref()
}
}
impl<T: ?Sized, W: DerefMut<Target = T>> DerefMut for GenerationalRefMut<W> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.inner.deref_mut()
}
}
pub(crate) struct GenerationalRefBorrowMutGuard {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
/// The location where the borrow occurred.
pub(crate) borrowed_from: &'static crate::entry::MemoryLocationBorrowInfo,
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
pub(crate) borrowed_mut_at: &'static std::panic::Location<'static>,
}
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
impl Drop for GenerationalRefBorrowMutGuard {
fn drop(&mut self) {
self.borrowed_from.drop_borrow_mut(self.borrowed_mut_at);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/src/error.rs | packages/generational-box/src/error.rs | //! Generational box errors
#![allow(clippy::uninlined_format_args, reason = "causes compile error")]
use std::error::Error;
use std::fmt::Debug;
use std::fmt::Display;
use crate::GenerationalLocation;
/// A result that can be returned from a borrow operation.
pub type BorrowResult<T = ()> = std::result::Result<T, BorrowError>;
/// A result that can be returned from a borrow mut operation.
pub type BorrowMutResult<T = ()> = std::result::Result<T, BorrowMutError>;
#[derive(Debug, Clone, PartialEq)]
/// An error that can occur when trying to borrow a value.
pub enum BorrowError {
/// The value was dropped.
Dropped(ValueDroppedError),
/// The value was already borrowed mutably.
AlreadyBorrowedMut(AlreadyBorrowedMutError),
}
impl Display for BorrowError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BorrowError::Dropped(error) => Display::fmt(error, f),
BorrowError::AlreadyBorrowedMut(error) => Display::fmt(error, f),
}
}
}
impl Error for BorrowError {}
#[derive(Debug, Clone, PartialEq)]
/// An error that can occur when trying to borrow a value mutably.
pub enum BorrowMutError {
/// The value was dropped.
Dropped(ValueDroppedError),
/// The value was already borrowed.
AlreadyBorrowed(AlreadyBorrowedError),
/// The value was already borrowed mutably.
AlreadyBorrowedMut(AlreadyBorrowedMutError),
}
impl Display for BorrowMutError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BorrowMutError::Dropped(error) => Display::fmt(error, f),
BorrowMutError::AlreadyBorrowedMut(error) => Display::fmt(error, f),
BorrowMutError::AlreadyBorrowed(error) => Display::fmt(error, f),
}
}
}
impl Error for BorrowMutError {}
impl From<BorrowError> for BorrowMutError {
fn from(error: BorrowError) -> Self {
match error {
BorrowError::Dropped(error) => BorrowMutError::Dropped(error),
BorrowError::AlreadyBorrowedMut(error) => BorrowMutError::AlreadyBorrowedMut(error),
}
}
}
/// An error that can occur when trying to use a value that has been dropped.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ValueDroppedError {
#[cfg(any(debug_assertions, feature = "debug_ownership"))]
pub(crate) created_at: &'static std::panic::Location<'static>,
}
impl ValueDroppedError {
/// Create a new `ValueDroppedError`.
#[allow(unused)]
pub fn new(created_at: &'static std::panic::Location<'static>) -> Self {
Self {
#[cfg(any(debug_assertions, feature = "debug_ownership"))]
created_at,
}
}
/// Create a new `ValueDroppedError` for a [`GenerationalLocation`].
#[allow(unused)]
pub(crate) fn new_for_location(location: GenerationalLocation) -> Self {
Self {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
created_at: location.created_at,
}
}
}
impl Display for ValueDroppedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Failed to borrow because the value was dropped.")?;
#[cfg(any(debug_assertions, feature = "debug_ownership"))]
f.write_fmt(format_args!("created_at: {}", self.created_at))?;
Ok(())
}
}
impl std::error::Error for ValueDroppedError {}
/// An error that can occur when trying to borrow a value that has already been borrowed mutably.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct AlreadyBorrowedMutError {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
pub(crate) borrowed_mut_at: &'static std::panic::Location<'static>,
}
impl AlreadyBorrowedMutError {
/// Create a new `AlreadyBorrowedMutError`.
#[allow(unused)]
pub fn new(borrowed_mut_at: &'static std::panic::Location<'static>) -> Self {
Self {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
borrowed_mut_at,
}
}
}
impl Display for AlreadyBorrowedMutError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Failed to borrow because the value was already borrowed mutably.")?;
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
f.write_fmt(format_args!("borrowed_mut_at: {}", self.borrowed_mut_at))?;
Ok(())
}
}
impl std::error::Error for AlreadyBorrowedMutError {}
/// An error that can occur when trying to borrow a value mutably that has already been borrowed immutably.
#[derive(Debug, Clone, PartialEq)]
pub struct AlreadyBorrowedError {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
pub(crate) borrowed_at: Vec<&'static std::panic::Location<'static>>,
}
impl AlreadyBorrowedError {
/// Create a new `AlreadyBorrowedError`.
#[allow(unused)]
pub fn new(borrowed_at: Vec<&'static std::panic::Location<'static>>) -> Self {
Self {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
borrowed_at,
}
}
}
impl Display for AlreadyBorrowedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Failed to borrow mutably because the value was already borrowed immutably.")?;
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
f.write_str("borrowed_at:")?;
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
for location in self.borrowed_at.iter() {
f.write_fmt(format_args!("\t{}", location))?;
}
Ok(())
}
}
impl std::error::Error for AlreadyBorrowedError {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/src/entry.rs | packages/generational-box/src/entry.rs | use crate::{
BorrowError, BorrowMutError, GenerationalLocation, GenerationalRefBorrowGuard,
GenerationalRefBorrowMutGuard,
};
use std::{
num::NonZeroU64,
sync::atomic::{AtomicU64, Ordering},
};
pub(crate) struct RcStorageEntry<T> {
ref_count: AtomicU64,
pub data: T,
}
impl<T> RcStorageEntry<T> {
pub const fn new(data: T) -> Self {
Self {
ref_count: AtomicU64::new(0),
data,
}
}
pub fn add_ref(&self) {
self.ref_count.fetch_add(1, Ordering::SeqCst);
}
pub fn drop_ref(&self) -> bool {
let new_ref_count = self.ref_count.fetch_sub(1, Ordering::SeqCst);
new_ref_count == 0
}
}
pub(crate) struct StorageEntry<T> {
generation: NonZeroU64,
pub(crate) data: T,
}
impl<T> StorageEntry<T> {
pub const fn new(data: T) -> Self {
Self {
generation: NonZeroU64::MIN,
data,
}
}
pub fn valid(&self, location: &GenerationalLocation) -> bool {
self.generation == location.generation
}
pub fn increment_generation(&mut self) {
self.generation = self.generation.checked_add(1).unwrap();
}
pub fn generation(&self) -> NonZeroU64 {
self.generation
}
}
impl<T: Default + 'static> Default for StorageEntry<T> {
fn default() -> Self {
Self::new(T::default())
}
}
#[derive(Default)]
pub(crate) struct MemoryLocationBorrowInfo(
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
parking_lot::RwLock<MemoryLocationBorrowInfoInner>,
);
impl MemoryLocationBorrowInfo {
pub(crate) fn borrow_mut_error(&self) -> BorrowMutError {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
{
let borrow = self.0.read();
if let Some(borrowed_mut_at) = borrow.borrowed_mut_at.as_ref() {
BorrowMutError::AlreadyBorrowedMut(crate::error::AlreadyBorrowedMutError {
borrowed_mut_at,
})
} else {
BorrowMutError::AlreadyBorrowed(crate::error::AlreadyBorrowedError {
borrowed_at: borrow.borrowed_at.clone(),
})
}
}
#[cfg(not(any(debug_assertions, feature = "debug_borrows")))]
{
BorrowMutError::AlreadyBorrowed(crate::error::AlreadyBorrowedError {})
}
}
pub(crate) fn borrow_error(&self) -> BorrowError {
BorrowError::AlreadyBorrowedMut(crate::error::AlreadyBorrowedMutError {
#[cfg(any(debug_assertions, feature = "debug_ownership"))]
borrowed_mut_at: self.0.read().borrowed_mut_at.unwrap(),
})
}
/// Start a new borrow
#[track_caller]
pub(crate) fn borrow_guard(&'static self) -> GenerationalRefBorrowGuard {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
let borrowed_at = std::panic::Location::caller();
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
{
let mut borrow = self.0.write();
borrow.borrowed_at.push(borrowed_at);
}
GenerationalRefBorrowGuard {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
borrowed_at,
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
borrowed_from: self,
}
}
/// Start a new mutable borrow
#[track_caller]
pub(crate) fn borrow_mut_guard(&'static self) -> GenerationalRefBorrowMutGuard {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
let borrowed_mut_at = std::panic::Location::caller();
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
{
let mut borrow = self.0.write();
borrow.borrowed_mut_at = Some(borrowed_mut_at);
}
GenerationalRefBorrowMutGuard {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
borrowed_mut_at,
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
borrowed_from: self,
}
}
#[allow(unused)]
pub(crate) fn drop_borrow(&self, borrowed_at: &'static std::panic::Location<'static>) {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
{
let mut borrow = self.0.write();
borrow
.borrowed_at
.retain(|location| *location != borrowed_at);
}
}
#[allow(unused)]
pub(crate) fn drop_borrow_mut(&self, borrowed_mut_at: &'static std::panic::Location<'static>) {
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
{
let mut borrow = self.0.write();
if borrow.borrowed_mut_at == Some(borrowed_mut_at) {
borrow.borrowed_mut_at = None;
}
}
}
}
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
#[derive(Default)]
struct MemoryLocationBorrowInfoInner {
borrowed_at: Vec<&'static std::panic::Location<'static>>,
borrowed_mut_at: Option<&'static std::panic::Location<'static>>,
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/tests/errors.rs | packages/generational-box/tests/errors.rs | use generational_box::{
AlreadyBorrowedError, AlreadyBorrowedMutError, BorrowError, BorrowMutError, GenerationalBox,
Owner, Storage, SyncStorage, UnsyncStorage, ValueDroppedError,
};
#[track_caller]
fn read_at_location<S: Storage<i32>>(
value: GenerationalBox<i32, S>,
) -> (S::Ref<'static, i32>, &'static std::panic::Location<'static>) {
let location = std::panic::Location::caller();
let read = value.read();
(read, location)
}
#[track_caller]
fn write_at_location<S: Storage<i32>>(
value: GenerationalBox<i32, S>,
) -> (S::Mut<'static, i32>, &'static std::panic::Location<'static>) {
let location = std::panic::Location::caller();
let write = value.write();
(write, location)
}
#[track_caller]
fn create_at_location<S: Storage<i32>>(
owner: &Owner<S>,
) -> (
GenerationalBox<i32, S>,
&'static std::panic::Location<'static>,
) {
let location = std::panic::Location::caller();
let value = owner.insert(1);
(value, location)
}
#[track_caller]
fn create_at_location_rc<S: Storage<i32>>(
owner: &Owner<S>,
) -> (
GenerationalBox<i32, S>,
&'static std::panic::Location<'static>,
) {
let location = std::panic::Location::caller();
let value = owner.insert_rc(1);
(value, location)
}
#[test]
fn read_while_writing_error() {
fn read_while_writing_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let value = owner.insert(1);
let (write, location) = write_at_location(value);
assert_eq!(
value.try_read().err(),
Some(BorrowError::AlreadyBorrowedMut(
AlreadyBorrowedMutError::new(location)
))
);
drop(write);
}
// For sync storage this will deadlock
read_while_writing_error_test::<UnsyncStorage>();
}
#[test]
fn read_while_writing_error_rc() {
fn read_while_writing_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let value = owner.insert_rc(1);
let (write, location) = write_at_location(value);
assert_eq!(
value.try_read().err(),
Some(BorrowError::AlreadyBorrowedMut(
AlreadyBorrowedMutError::new(location)
))
);
drop(write);
}
// For sync storage this will deadlock
read_while_writing_error_test::<UnsyncStorage>();
}
#[test]
fn read_after_dropped_error() {
fn read_after_dropped_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let (value, location) = create_at_location(&owner);
drop(owner);
assert_eq!(
value.try_read().err(),
Some(BorrowError::Dropped(ValueDroppedError::new(location)))
);
}
read_after_dropped_error_test::<UnsyncStorage>();
read_after_dropped_error_test::<SyncStorage>();
}
#[test]
fn read_after_dropped_error_rc() {
fn read_after_dropped_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let (value, location) = create_at_location_rc(&owner);
drop(owner);
assert_eq!(
value.try_read().err(),
Some(BorrowError::Dropped(ValueDroppedError::new(location)))
);
}
read_after_dropped_error_test::<UnsyncStorage>();
read_after_dropped_error_test::<SyncStorage>();
}
#[test]
fn write_while_writing_error() {
fn write_while_writing_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let value = owner.insert(1);
#[allow(unused)]
let (write, location) = write_at_location(value);
let write_result = value.try_write();
assert!(write_result.is_err());
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
assert_eq!(
write_result.err(),
Some(BorrowMutError::AlreadyBorrowedMut(
AlreadyBorrowedMutError::new(location)
))
);
drop(write);
}
// For sync storage this will deadlock
write_while_writing_error_test::<UnsyncStorage>();
}
#[test]
fn write_while_writing_error_rc() {
fn write_while_writing_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let value = owner.insert_rc(1);
#[allow(unused)]
let (write, location) = write_at_location(value);
let write_result = value.try_write();
assert!(write_result.is_err());
#[cfg(any(debug_assertions, feature = "debug_borrows"))]
assert_eq!(
write_result.err(),
Some(BorrowMutError::AlreadyBorrowedMut(
AlreadyBorrowedMutError::new(location)
))
);
drop(write);
}
// For sync storage this will deadlock
write_while_writing_error_test::<UnsyncStorage>();
}
#[test]
fn write_while_reading_error() {
fn write_while_reading_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let value = owner.insert(1);
let (read, location) = read_at_location(value);
assert_eq!(
value.try_write().err(),
Some(BorrowMutError::AlreadyBorrowed(AlreadyBorrowedError::new(
vec![location]
)))
);
drop(read);
}
// For sync storage this will deadlock
write_while_reading_error_test::<UnsyncStorage>();
}
#[test]
fn write_while_reading_error_rc() {
fn write_while_reading_error_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let value = owner.insert_rc(1);
let (read, location) = read_at_location(value);
assert_eq!(
value.try_write().err(),
Some(BorrowMutError::AlreadyBorrowed(AlreadyBorrowedError::new(
vec![location]
)))
);
drop(read);
}
// For sync storage this will deadlock
write_while_reading_error_test::<UnsyncStorage>();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/tests/sync.rs | packages/generational-box/tests/sync.rs | // Regression test for https://github.com/DioxusLabs/dioxus/issues/2636
use std::time::Duration;
use generational_box::{AnyStorage, GenerationalBox, SyncStorage};
#[test]
fn race_condition_regression() {
for _ in 0..100 {
let handle = {
let owner = SyncStorage::owner();
let key = owner.insert(1u64);
let handle = std::thread::spawn(move || reader(key));
std::thread::sleep(Duration::from_millis(10));
handle
// owner is dropped now
};
// owner is *recycled*
let owner = SyncStorage::owner();
let _key = owner.insert(2u64);
let _ = handle.join();
}
}
fn reader(key: GenerationalBox<u64, SyncStorage>) {
for _ in 0..1000000 {
match key.try_read() {
Ok(value) => {
if *value == 2 {
panic!("Read a new value with the old generation");
} else {
// fine
}
}
Err(err) => {
eprintln!("bailing out - {err:?}");
break;
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/tests/reused.rs | packages/generational-box/tests/reused.rs | //! This test needs to be in its own file such that it doesn't share
//! an address space with the other tests.
//!
//! That will cause random failures on CI.
use generational_box::{Storage, SyncStorage, UnsyncStorage};
#[test]
fn reused() {
fn reused_test<S: Storage<i32> + 'static>() {
let first_ptr;
{
let owner = S::owner();
first_ptr = owner.insert(1).raw_ptr();
drop(owner);
}
{
let owner = S::owner();
let second_ptr = owner.insert(1234).raw_ptr();
assert_eq!(first_ptr, second_ptr);
drop(owner);
}
}
reused_test::<UnsyncStorage>();
reused_test::<SyncStorage>();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/tests/reference_counting.rs | packages/generational-box/tests/reference_counting.rs | use generational_box::{Storage, SyncStorage, UnsyncStorage};
#[test]
fn reference_counting() {
fn reference_counting<S: Storage<String> + 'static>() {
let data = String::from("hello world");
let reference;
{
let outer_owner = S::owner();
{
// create an owner
let owner = S::owner();
// insert data into the store
let original = owner.insert_rc(data);
reference = outer_owner.insert_reference(original).unwrap();
// The reference should point to the value immediately
assert_eq!(&*reference.read(), "hello world");
// Original is dropped
}
// The reference should still point to the value
assert_eq!(&*reference.read(), "hello world");
}
// Now that all references are dropped, the value should be dropped
assert!(reference.try_read().is_err());
}
reference_counting::<UnsyncStorage>();
reference_counting::<SyncStorage>();
}
#[test]
fn move_reference_in_place() {
fn move_reference_in_place<S: Storage<String> + 'static>() {
let data1 = String::from("hello world");
let data2 = String::from("hello world 2");
// create an owner
let original_owner = S::owner();
// insert data into the store
let original = original_owner.insert_rc(data1.clone());
let reference = original_owner.insert_reference(original).unwrap();
// The reference should point to the original value
assert_eq!(&*reference.read(), &data1);
let new_owner = S::owner();
// Move the reference in place
let new = new_owner.insert_rc(data2.clone());
reference.point_to(new).unwrap();
// The reference should point to the new value
assert_eq!(&*reference.read(), &data2);
// make sure both got dropped
drop(original_owner);
drop(new_owner);
assert!(original.try_read().is_err());
assert!(new.try_read().is_err());
}
move_reference_in_place::<UnsyncStorage>();
move_reference_in_place::<SyncStorage>();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/tests/basic.rs | packages/generational-box/tests/basic.rs | use generational_box::{GenerationalBox, Storage, SyncStorage, UnsyncStorage};
/// # Example
///
/// ```compile_fail
/// let data = String::from("hello world");
/// let owner = UnsyncStorage::owner();
/// let key = owner.insert(&data);
/// drop(data);
/// assert_eq!(*key.read(), "hello world");
/// ```
#[allow(unused)]
fn compile_fail() {}
#[test]
fn leaking_is_ok() {
fn leaking_is_ok_test<S: Storage<String> + 'static>() {
let data = String::from("hello world");
let key;
{
// create an owner
let owner = S::owner();
// insert data into the store
key = owner.insert(data);
// don't drop the owner
std::mem::forget(owner);
}
assert_eq!(
key.try_read().as_deref().unwrap(),
&"hello world".to_string()
);
}
leaking_is_ok_test::<UnsyncStorage>();
leaking_is_ok_test::<SyncStorage>();
}
#[test]
fn drops() {
fn drops_test<S: Storage<String> + 'static>() {
let data = String::from("hello world");
let key;
{
// create an owner
let owner = S::owner();
// insert data into the store
key = owner.insert(data);
// drop the owner
}
assert!(key.try_read().is_err());
}
drops_test::<UnsyncStorage>();
drops_test::<SyncStorage>();
}
#[test]
fn works() {
fn works_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let key = owner.insert(1);
assert_eq!(*key.read(), 1);
}
works_test::<UnsyncStorage>();
works_test::<SyncStorage>();
}
#[test]
fn insert_while_reading() {
fn insert_while_reading_test<S: Storage<String> + Storage<&'static i32> + 'static>() {
let owner = S::owner();
let key;
{
let data: String = "hello world".to_string();
key = owner.insert(data);
}
let value = key.read();
owner.insert(&1);
assert_eq!(*value, "hello world");
}
insert_while_reading_test::<UnsyncStorage>();
insert_while_reading_test::<SyncStorage>();
}
#[test]
#[should_panic]
fn panics() {
fn panics_test<S: Storage<i32> + 'static>() {
let owner = S::owner();
let key = owner.insert(1);
drop(owner);
assert_eq!(*key.read(), 1);
}
panics_test::<UnsyncStorage>();
panics_test::<SyncStorage>();
}
#[test]
fn fuzz() {
fn maybe_owner_scope<S: Storage<String> + 'static>(
valid_keys: &mut Vec<GenerationalBox<String, S>>,
invalid_keys: &mut Vec<GenerationalBox<String, S>>,
path: &mut Vec<u8>,
) {
let branch_cutoff = 5;
let children = if path.len() < branch_cutoff {
rand::random::<u8>() % 4
} else {
rand::random::<u8>() % 2
};
for i in 0..children {
let owner = S::owner();
let value = format!("hello world {path:?}");
let key = owner.insert(value.clone());
println!("created new box {key:?}");
valid_keys.push(key);
path.push(i);
// read all keys
println!("{:?}", path);
for key in valid_keys.iter() {
println!("reading {key:?}");
let value = key.read();
println!("{:?}", &*value);
assert!(value.starts_with("hello world"));
}
for key in invalid_keys.iter() {
println!("reading invalid {key:?}");
assert!(key.try_read().is_err());
}
maybe_owner_scope(valid_keys, invalid_keys, path);
// After all the children run, we should still have our data
let key_value = &*key.read();
println!("{:?}", key_value);
assert_eq!(key_value, &value);
let invalid = valid_keys.pop().unwrap();
println!("popping {invalid:?}");
invalid_keys.push(invalid);
path.pop();
}
}
for _ in 0..10 {
maybe_owner_scope::<UnsyncStorage>(&mut Vec::new(), &mut Vec::new(), &mut Vec::new());
}
for _ in 0..10 {
maybe_owner_scope::<SyncStorage>(&mut Vec::new(), &mut Vec::new(), &mut Vec::new());
}
}
#[test]
fn fuzz_rc() {
fn maybe_owner_scope<S: Storage<String>>(
valid_keys: &mut Vec<Vec<GenerationalBox<String, S>>>,
invalid_keys: &mut Vec<GenerationalBox<String, S>>,
path: &mut Vec<u8>,
) {
let branch_cutoff = 5;
let children = if path.len() < branch_cutoff {
rand::random::<u8>() % 4
} else {
rand::random::<u8>() % 2
};
for i in 0..children {
let owner = S::owner();
let value = format!("hello world {path:?}");
let key = owner.insert_rc(value.clone());
println!("created new box {key:?}");
let mut keys = vec![key];
for _ in 0..rand::random::<u8>() % 10 {
if rand::random::<u8>() % 2 == 0 {
let owner = S::owner();
let key = owner.insert_reference(key).unwrap();
println!("created new reference {key:?}");
invalid_keys.push(key);
}
let key = owner.insert_reference(key).unwrap();
println!("created new reference {key:?}");
keys.push(key);
}
valid_keys.push(keys.clone());
path.push(i);
// read all keys
println!("{:?}", path);
for keys in valid_keys.iter() {
for key in keys {
println!("reading {key:?}");
let value = key.read();
println!("{:?}", &*value);
assert!(value.starts_with("hello world"));
}
}
for key in invalid_keys.iter() {
println!("reading invalid {key:?}");
assert!(key.try_read().is_err());
}
maybe_owner_scope(valid_keys, invalid_keys, path);
// After all the children run, we should still have our data
for key in keys {
let key_value = &*key.read();
println!("{:?}", key_value);
assert_eq!(key_value, &value);
}
let invalid = valid_keys.pop().unwrap();
println!("popping {invalid:?}");
invalid_keys.extend(invalid);
path.pop();
}
}
for _ in 0..10 {
maybe_owner_scope::<UnsyncStorage>(&mut Vec::new(), &mut Vec::new(), &mut Vec::new());
}
for _ in 0..10 {
maybe_owner_scope::<SyncStorage>(&mut Vec::new(), &mut Vec::new(), &mut Vec::new());
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/generational-box/benches/lock.rs | packages/generational-box/benches/lock.rs | #![allow(unused)]
use generational_box::*;
use criterion::{criterion_group, criterion_main, Criterion};
use std::hint::black_box;
fn create<S: Storage<u32>>(owner: &Owner<S>) -> GenerationalBox<u32, S> {
owner.insert(0)
}
fn set_read<S: Storage<u32>>(signal: GenerationalBox<u32, S>) -> u32 {
signal.set(1);
*signal.read()
}
fn bench_fib(c: &mut Criterion) {
{
let owner = UnsyncStorage::owner();
c.bench_function("create_unsync", |b| b.iter(|| create(black_box(&owner))));
let signal = create(&owner);
c.bench_function("set_read_unsync", |b| {
b.iter(|| set_read(black_box(signal)))
});
}
{
let owner = SyncStorage::owner();
c.bench_function("create_sync", |b| b.iter(|| create(black_box(&owner))));
let signal = create(&owner);
c.bench_function("set_read_sync", |b| b.iter(|| set_read(black_box(signal))));
}
}
criterion_group!(benches, bench_fib);
criterion_main!(benches);
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/subsecond/subsecond-tests/cross-tls-crate/src/lib.rs | packages/subsecond/subsecond-tests/cross-tls-crate/src/lib.rs | pub use std::cell::Cell;
use std::{cell::RefCell, thread::LocalKey};
#[derive(Debug)]
pub struct StoredItem {
pub name: String,
pub value: f32,
pub items: Vec<String>,
}
thread_local! {
pub static BAR: RefCell<Option<StoredItem>> = const { RefCell::new(None) };
}
pub fn get_bar() -> &'static LocalKey<RefCell<Option<StoredItem>>> {
if BAR.with(|f| f.borrow().is_none()) {
BAR.set(Some(StoredItem {
name: "BAR".to_string(),
value: 0.0,
items: vec!["item1".to_string(), "item2".to_string()],
}));
}
&BAR
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/subsecond/subsecond-tests/cross-tls-crate-dylib/src/lib.rs | packages/subsecond/subsecond-tests/cross-tls-crate-dylib/src/lib.rs | pub use std::cell::Cell;
use std::{cell::RefCell, thread::LocalKey};
#[derive(Debug)]
pub struct StoredItem {
pub name: String,
pub value: f32,
pub items: Vec<String>,
}
thread_local! {
pub static BAZ: RefCell<Option<StoredItem>> = const { RefCell::new(None) };
}
pub fn get_baz() -> &'static LocalKey<RefCell<Option<StoredItem>>> {
if BAZ.with(|f| f.borrow().is_none()) {
BAZ.set(Some(StoredItem {
name: "BAR".to_string(),
value: 0.0,
items: vec!["item1".to_string(), "item2".to_string()],
}));
}
&BAZ
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/subsecond/subsecond-tests/cross-tls-test/src/main.rs | packages/subsecond/subsecond-tests/cross-tls-test/src/main.rs | use std::{cell::Cell, thread, time::Duration};
use cross_tls_crate::get_bar;
use cross_tls_crate_dylib::get_baz;
fn main() {
dioxus_devtools::connect_subsecond();
loop {
dioxus_devtools::subsecond::call(|| {
use cross_tls_crate::BAR;
use cross_tls_crate_dylib::BAZ;
thread_local! {
pub static FOO: Cell<f32> = const { Cell::new(2.0) };
}
println!("Hello 123s123123s: {}", FOO.get());
get_bar().with(|f| println!("Bar: {:?}", f.borrow()));
thread::sleep(Duration::from_secs(1));
FOO.set(2.0);
get_bar().with(|f| f.borrow_mut().as_mut().unwrap().value = 3.0);
get_baz().with(|f| f.borrow_mut().as_mut().unwrap().value = 4.0);
BAR.with_borrow(|f| {
println!("Bar: {:?}", f);
});
BAZ.with_borrow(|f| {
println!("Baz: {:?}", f);
});
});
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/subsecond/subsecond-types/src/lib.rs | packages/subsecond/subsecond-types/src/lib.rs | use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
hash::{BuildHasherDefault, Hasher},
path::PathBuf,
};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct JumpTable {
/// The dylib containing the patch. This should be a valid path so you can just pass it to LibLoading
///
/// On wasm you will need to fetch() this file and then pass it to the WebAssembly.instantiate() function
pub lib: PathBuf,
/// old -> new
/// does not take into account the base address of the patch when loaded into memory - need dlopen for that
///
/// These are intended to be `*const ()` pointers but need to be `u64` for the hashmap. On 32-bit platforms
/// you will need to cast to `usize` before using them.
pub map: AddressMap,
/// the address of the base address of the old original binary
///
/// machos: this is the address of the `_mh_execute_header` symbol usually at 0x100000000 and loaded near 0x100000000
/// linux: this is the address of the `__executable_start` symbol usually at 0x0 but loaded around 0x555555550000
/// windows: this is the address of the `ImageBase` field of the PE header
/// wasm: not useful since there's no ASLR
///
/// While we can generally guess that these values are, it's possible they are different and thus reading
/// them dynamically is worthwhile.
pub aslr_reference: u64,
/// the address of the base address of the new binary
///
/// machos: this is the address of the `_mh_execute_header` symbol usually at 0x100000000 and loaded near 0x100000000
/// linux: this is the address of the `__executable_start` symbol usually at 0x0 but loaded around 0x555555550000
/// windows: this is the address of the `ImageBase` field of the PE header
/// wasm: not useful since there's no ASLR
///
/// While we can generally guess that these values are, it's possible they are different and thus reading
/// them dynamically is worthwhile.
pub new_base_address: u64,
/// The amount of ifuncs this will register. This is used by WASM to know how much space to allocate
/// for the ifuncs in the ifunc table
pub ifunc_count: u64,
}
/// An address to address hashmap that does not hash addresses since addresses are by definition unique.
pub type AddressMap = HashMap<u64, u64, BuildAddressHasher>;
pub type BuildAddressHasher = BuildHasherDefault<AddressHasher>;
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct AddressHasher(u64);
impl Hasher for AddressHasher {
fn write(&mut self, _: &[u8]) {
panic!("Invalid use of NoHashHasher")
}
fn write_u8(&mut self, n: u8) {
self.0 = u64::from(n)
}
fn write_u16(&mut self, n: u16) {
self.0 = u64::from(n)
}
fn write_u32(&mut self, n: u32) {
self.0 = u64::from(n)
}
fn write_u64(&mut self, n: u64) {
self.0 = n
}
fn write_usize(&mut self, n: usize) {
self.0 = n as u64
}
fn write_i8(&mut self, n: i8) {
self.0 = n as u64
}
fn write_i16(&mut self, n: i16) {
self.0 = n as u64
}
fn write_i32(&mut self, n: i32) {
self.0 = n as u64
}
fn write_i64(&mut self, n: i64) {
self.0 = n as u64
}
fn write_isize(&mut self, n: isize) {
self.0 = n as u64
}
fn finish(&self) -> u64 {
self.0
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/subsecond/subsecond/src/lib.rs | packages/subsecond/subsecond/src/lib.rs | #![allow(clippy::needless_doctest_main)]
//! # Subsecond: Hot-patching for Rust
//!
//! Subsecond is a library that enables hot-patching for Rust applications. This allows you to change
//! the code of a running application without restarting it. This is useful for game engines, servers,
//! and other long-running applications where the typical edit-compile-run cycle is too slow.
//!
//! Subsecond also implements a technique we call "ThinLinking" which makes compiling Rust code
//! significantly faster in development mode, which can be used outside of hot-patching.
//!
//! # Usage
//!
//! Subsecond is designed to be as simple for both application developers and library authors.
//!
//! Simply call your existing functions with [`call`] and Subsecond will automatically detour
//! that call to the latest version of the function.
//!
//! ```rust
//! for x in 0..5 {
//! subsecond::call(|| {
//! println!("Hello, world! {}", x);
//! });
//! }
//! ```
//!
//! To actually load patches into your application, a third-party tool that implements the Subsecond
//! compiler and protocol is required. Subsecond is built and maintained by the Dioxus team, so we
//! suggest using the dioxus CLI tool to use subsecond.
//!
//! To install the Dioxus CLI, we recommend using [`cargo binstall`](https://crates.io/crates/cargo-binstall):
//!
//! ```sh
//! cargo binstall dioxus-cli
//! ```
//!
//! The Dioxus CLI provides several tools for development. To run your application with Subsecond enabled,
//! use `dx serve` - this takes the same arguments as `cargo run` but will automatically hot-reload your
//! application when changes are detected.
//!
//! As of Dioxus 0.7, "--hotpatch" is required to use hotpatching while Subsecond is still experimental.
//!
//! ```sh
//! dx serve --hotpatch
//! ```
//!
//! ## How it works
//!
//! Subsecond works by detouring function calls through a jump table. This jump table contains the latest
//! version of the program's function pointers, and when a function is called, Subsecond will look up
//! the function in the jump table and call that instead.
//!
//! Unlike libraries like [detour](https://crates.io/crates/detour), Subsecond *does not* modify your
//! process memory. Patching pointers is wildly unsafe and can lead to crashes and undefined behavior.
//!
//! Instead, an external tool compiles only the parts of your project that changed, links them together
//! using the addresses of the functions in your running program, and then sends the new jump table to
//! your application. Subsecond then applies the patch and continues running. Since Subsecond doesn't
//! modify memory, the program must have a runtime integration to handle the patching.
//!
//! If the framework you're using doesn't integrate with subsecond, you can rely on the fact that calls
//! to stale [`call`] instances will emit a safe panic that is automatically caught and retried
//! by the next [`call`] instance up the callstack.
//!
//! Subsecond is only enabled when debug_assertions are enabled so you can safely ship your application
//! with Subsecond enabled without worrying about the performance overhead.
//!
//! ## Workspace support
//!
//! Subsecond currently only patches the "tip" crate - ie the crate in which your `main.rs` is located.
//! Changes to crates outside this crate will be ignored, which can be confusing. We plan to add full
//! workspace support in the future, but for now be aware of this limitation. Crate setups that have
//! a `main.rs` importing a `lib.rs` won't patch sensibly since the crate becomes a library for itself.
//!
//! This is due to limitations in rustc itself where the build-graph is non-deterministic and changes
//! to functions that forward generics can cause a cascade of codegen changes.
//!
//! ## Globals, statics, and thread-locals
//!
//! Subsecond *does* support hot-reloading of globals, statics, and thread locals. However, there are several limitations:
//!
//! - You may add new globals at runtime, but their destructors will never be called.
//! - Globals are tracked across patches, but renames are considered to be *new* globals.
//! - Changes to static initializers will not be observed.
//!
//! Subsecond purposefully handles statics this way since many libraries like Dioxus and Tokio rely
//! on persistent global runtimes.
//!
//! HUGE WARNING: Currently, thread-locals in the "tip" crate (the one being patched) will seemingly
//! reset to their initial value on new patches. This is because we don't currently bind thread-locals
//! in the patches to their original addresses in the main program. If you rely on thread-locals heavily
//! in your tip crate, you should be aware of this. Sufficiently complex setups might crash or even
//! segfault. We plan to fix this in the future, but for now, you should be aware of this limitation.
//!
//! ## Struct layout and alignment
//!
//! Subsecond currently does not support hot-reloading of structs. This is because the generated code
//! assumes a particular layout and alignment of the struct. If layout or alignment change and new
//! functions are called referencing an old version of the struct, the program will crash.
//!
//! To mitigate this, framework authors can integrate with Subsecond to either dispose of the old struct
//! or to re-allocate the struct in a way that is compatible with the new layout. This is called "re-instancing."
//!
//! In practice, frameworks that implement subsecond patching properly will throw out the old state
//! and thus you should never witness a segfault due to misalignment or size changes. Frameworks are
//! encouraged to aggressively dispose of old state that might cause size and alignment changes.
//!
//! We'd like to lift this limitation in the future by providing utilities to re-instantiate structs,
//! but for now it's up to the framework authors to handle this. For example, Dioxus apps simply throw
//! out the old state and rebuild it from scratch.
//!
//! ## Pointer versioning
//!
//! Currently, Subsecond does not "version" function pointers. We have plans to provide this metadata
//! so framework authors can safely memoize changes without much runtime overhead. Frameworks like
//! Dioxus and Bevy circumvent this issue by using the TypeID of structs passed to hot functions as
//! well as the `ptr_address` method on [`HotFn`] to determine if the function pointer has changed.
//!
//! Currently, the `ptr_address` method will always return the most up-to-date version of the function
//! even if the function contents itself did not change. In essence, this is equivalent to a version
//! of the function where every function is considered "new." This means that framework authors who
//! integrate re-instancing in their apps might dispose of old state too aggressively. For now, this
//! is the safer and more practical approach.
//!
//! ## Nesting Calls
//!
//! Subsecond calls are designed to be nested. This provides clean integration points to know exactly
//! where a hooked function is called.
//!
//! The highest level call is `fn main()` though by default this is not hooked since initialization code
//! tends to be side-effectual and modify global state. Instead, we recommend wrapping the hot-patch
//! points manually with [`call`].
//!
//! ```rust
//! fn main() {
//! // Changes to the the `for` loop will cause an unwind to this call.
//! subsecond::call(|| {
//! for x in 0..5 {
//! // Changes to the `println!` will be isolated to this call.
//! subsecond::call(|| {
//! println!("Hello, world! {}", x);
//! });
//! }
//! });
//! }
//! ```
//!
//! The goal here is to provide granular control over where patches are applied to limit loss of state
//! when new code is loaded.
//!
//! ## Applying patches
//!
//! When running under the Dioxus CLI, the `dx serve` command will automatically apply patches when
//! changes are detected. Patches are delivered over the [Dioxus Devtools](https://crates.io/crates/dioxus-devtools)
//! websocket protocol and received by corresponding websocket.
//!
//! If you're using Subsecond in your own application that doesn't have a runtime integration, you can
//! build an integration using the [`apply_patch`] function. This function takes a `JumpTable` which
//! the dioxus-cli crate can generate.
//!
//! To add support for the Dioxus Devtools protocol to your app, you can use the [dioxus-devtools](https://crates.io/crates/dioxus-devtools)
//! crate which provides a `connect` method that will automatically apply patches to your application.
//!
//! Unfortunately, one design quirk of Subsecond is that running apps need to communicate the address
//! of `main` to the patcher. This is due to a security technique called [ASLR](https://en.wikipedia.org/wiki/Address_space_layout_randomization)
//! which randomizes the address of functions in memory. See the subsecond-harness and subsecond-cli
//! for more details on how to implement the protocol.
//!
//! ## ThinLink
//!
//! ThinLink is a program linker for Rust that is designed to be used with Subsecond. It implements
//! the powerful patching system that Subsecond uses to hot-reload Rust applications.
//!
//! ThinLink is simply a wrapper around your existing linker but with extra features:
//!
//! - Automatic dynamic linking to dependencies
//! - Generation of Subsecond jump tables
//! - Diffing of object files for function invalidation
//!
//! Because ThinLink performs very to little actual linking, it drastically speeds up traditional Rust
//! development. With a development-optimized profile, ThinLink can shrink an incremental build to less than 500ms.
//!
//! ThinLink is automatically integrated into the Dioxus CLI though it's currently not available as
//! a standalone tool.
//!
//! ## Limitations
//!
//! Subsecond is a powerful tool but it has several limitations. We talk about them above, but here's
//! a quick summary:
//!
//! - Struct hot reloading requires instancing or unwinding
//! - Statics are tracked but not destructed
//!
//! ## Platform support
//!
//! Subsecond works across all major platforms:
//!
//! - Android (arm64-v8a, armeabi-v7a)
//! - iOS (arm64)
//! - Linux (x86_64, aarch64)
//! - macOS (x86_64, aarch64)
//! - Windows (x86_64, arm64)
//! - WebAssembly (wasm32)
//!
//! If you have a new platform you'd like to see supported, please open an issue on the Subsecond repository.
//! We are keen to add support for new platforms like wasm64, riscv64, and more.
//!
//! Note that iOS device is currently not supported due to code-signing requirements. We hope to fix
//! this in the future, but for now you can use the simulator to test your app.
//!
//! ## Adding the Subsecond badge to your project
//!
//! If you're a framework author and want your users to know that your library supports Subsecond, you
//! can add the Subsecond badge to your README! Users will know that your library is hot-reloadable and
//! can be used with Subsecond.
//!
//! [](https://crates.io/crates/subsecond)
//!
//! ```markdown
//! [](https://crates.io/crates/subsecond)
//! ```
//!
//! ## License
//!
//! Subsecond and ThinLink are licensed under the MIT license. See the LICENSE file for more information.
//!
//! ## Supporting this work
//!
//! Subsecond is a project by the Dioxus team. If you'd like to support our work, please consider
//! [sponsoring us on GitHub](https://github.com/sponsors/DioxusLabs) or eventually deploying your
//! apps with Dioxus Deploy (currently under construction).
pub use subsecond_types::JumpTable;
use std::{
backtrace,
mem::transmute,
panic::AssertUnwindSafe,
sync::{atomic::AtomicPtr, Arc, Mutex},
};
/// Call a given function with hot-reloading enabled. If the function's code changes, `call` will use
/// the new version of the function. If code *above* the function changes, this will emit a panic
/// that forces an unwind to the next [`call`] instance.
///
/// WASM/rust does not support unwinding, so [`call`] will not track dependency graph changes.
/// If you are building a framework for use on WASM, you will need to use `Subsecond::HotFn` directly.
///
/// However, if you wrap your calling code in a future, you *can* simply drop the future which will
/// cause `drop` to execute and get something similar to unwinding. Not great if refcells are open.
pub fn call<O>(mut f: impl FnMut() -> O) -> O {
// Only run in debug mode - the rest of this function will dissolve away
if !cfg!(debug_assertions) {
return f();
}
let mut hotfn = HotFn::current(f);
loop {
let res = std::panic::catch_unwind(AssertUnwindSafe(|| hotfn.call(())));
// If the call succeeds just return the result, otherwise we try to handle the panic if its our own.
let err = match res {
Ok(res) => return res,
Err(err) => err,
};
// If this is our panic then let's handle it, otherwise we just resume unwinding
let Some(_hot_payload) = err.downcast_ref::<HotFnPanic>() else {
std::panic::resume_unwind(err);
};
}
}
// We use an AtomicPtr with a leaked JumpTable and Relaxed ordering to give us a global jump table
// with very very little overhead. Reading this amounts of a Relaxed atomic load which basically
// is no overhead. We might want to look into using a thread_local with a stop-the-world approach
// just in case multiple threads try to call the jump table before synchronization with the runtime.
// For Dioxus purposes, this is not a big deal, but for libraries like bevy which heavily rely on
// multithreading, it might become an issue.
static APP_JUMP_TABLE: AtomicPtr<JumpTable> = AtomicPtr::new(std::ptr::null_mut());
static HOTRELOAD_HANDLERS: Mutex<Vec<Arc<dyn Fn() + Send + Sync>>> = Mutex::new(Vec::new());
/// Register a function that will be called whenever a patch is applied.
///
/// This handler will be run immediately after the patch library is loaded into the process and the
/// JumpTable has been set.
pub fn register_handler(handler: Arc<dyn Fn() + Send + Sync + 'static>) {
HOTRELOAD_HANDLERS.lock().unwrap().push(handler);
}
/// Get the current jump table, if it exists.
///
/// This will return `None` if no jump table has been set yet.
///
/// # Safety
///
/// The `JumpTable` returned here is a pointer into a leaked box. While technically this reference is
/// valid, we might change the implementation to invalidate the pointer between hotpatches.
///
/// You should only use this lifetime in temporary contexts - not *across* hotpatches!
pub unsafe fn get_jump_table() -> Option<&'static JumpTable> {
let ptr = APP_JUMP_TABLE.load(std::sync::atomic::Ordering::Relaxed);
if ptr.is_null() {
return None;
}
Some(unsafe { &*ptr })
}
unsafe fn commit_patch(table: JumpTable) {
APP_JUMP_TABLE.store(
Box::into_raw(Box::new(table)),
std::sync::atomic::Ordering::Relaxed,
);
HOTRELOAD_HANDLERS
.lock()
.unwrap()
.clone()
.iter()
.for_each(|handler| {
handler();
});
}
/// A panic issued by the [`call`] function if the caller would be stale if called. This causes
/// an unwind to the next [`call`] instance that can properly handle the panic and retry the call.
///
/// This technique allows Subsecond to provide hot-reloading of codebases that don't have a runtime integration.
#[derive(Debug)]
pub struct HotFnPanic {
_backtrace: backtrace::Backtrace,
}
/// A pointer to a hot patched function
#[non_exhaustive]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub struct HotFnPtr(pub u64);
impl HotFnPtr {
/// Create a new [`HotFnPtr`].
///
/// The safe way to get one is through [`HotFn::ptr_address`].
///
/// # Safety
///
/// The underlying `u64` must point to a valid function.
pub unsafe fn new(index: u64) -> Self {
Self(index)
}
}
/// A hot-reloadable function.
///
/// To call this function, use the [`HotFn::call`] method. This will automatically use the latest
/// version of the function from the JumpTable.
pub struct HotFn<A, M, F>
where
F: HotFunction<A, M>,
{
inner: F,
_marker: std::marker::PhantomData<(A, M)>,
}
impl<A, M, F: HotFunction<A, M>> HotFn<A, M, F> {
/// Create a new [`HotFn`] instance with the current function.
///
/// Whenever you call [`HotFn::call`], it will use the current function from the [`JumpTable`].
pub const fn current(f: F) -> HotFn<A, M, F> {
HotFn {
inner: f,
_marker: std::marker::PhantomData,
}
}
/// Call the function with the given arguments.
///
/// This will unwrap the [`HotFnPanic`] panic, propagating up to the next [`HotFn::call`].
///
/// If you want to handle the panic yourself, use [`HotFn::try_call`].
pub fn call(&mut self, args: A) -> F::Return {
self.try_call(args).unwrap()
}
/// Get the address of the function in memory which might be different than the original.
///
/// This is useful for implementing a memoization strategy to safely preserve state across
/// hot-patches. If the ptr_address of a function did not change between patches, then the
/// state that exists "above" the function is still valid.
///
/// Note that Subsecond does not track this state over time, so it's up to the runtime integration
/// to track this state and diff it.
pub fn ptr_address(&self) -> HotFnPtr {
if size_of::<F>() == size_of::<fn() -> ()>() {
let ptr: usize = unsafe { std::mem::transmute_copy(&self.inner) };
return HotFnPtr(ptr as u64);
}
let known_fn_ptr = <F as HotFunction<A, M>>::call_it as *const () as usize;
if let Some(jump_table) = unsafe { get_jump_table() } {
if let Some(ptr) = jump_table.map.get(&(known_fn_ptr as u64)).cloned() {
return HotFnPtr(ptr);
}
}
HotFnPtr(known_fn_ptr as u64)
}
/// Attempt to call the function with the given arguments.
///
/// If this function is stale and can't be updated in place (ie, changes occurred above this call),
/// then this function will emit an [`HotFnPanic`] which can be unwrapped and handled by next [`call`]
/// instance.
pub fn try_call(&mut self, args: A) -> Result<F::Return, HotFnPanic> {
if !cfg!(debug_assertions) {
return Ok(self.inner.call_it(args));
}
unsafe {
// Try to handle known function pointers. This is *really really* unsafe, but due to how
// rust trait objects work, it's impossible to make an arbitrary usize-sized type implement Fn()
// since that would require a vtable pointer, pushing out the bounds of the pointer size.
if size_of::<F>() == size_of::<fn() -> ()>() {
return Ok(self.inner.call_as_ptr(args));
}
// Handle trait objects. This will occur for sizes other than usize. Normal rust functions
// become ZST's and thus their <T as SomeFn>::call becomes a function pointer to the function.
//
// For non-zst (trait object) types, then there might be an issue. The real call function
// will likely end up in the vtable and will never be hot-reloaded since signature takes self.
if let Some(jump_table) = get_jump_table() {
let known_fn_ptr = <F as HotFunction<A, M>>::call_it as *const () as u64;
if let Some(ptr) = jump_table.map.get(&known_fn_ptr).cloned() {
// The type sig of the cast should match the call_it function
// Technically function pointers need to be aligned, but that alignment is 1 so we're good
let call_it = transmute::<*const (), fn(&F, A) -> F::Return>(ptr as _);
return Ok(call_it(&self.inner, args));
}
}
Ok(self.inner.call_it(args))
}
}
/// Attempt to call the function with the given arguments, using the given [`HotFnPtr`].
///
/// You can get a [`HotFnPtr`] from [`Self::ptr_address`].
///
/// If this function is stale and can't be updated in place (ie, changes occurred above this call),
/// then this function will emit an [`HotFnPanic`] which can be unwrapped and handled by next [`call`]
/// instance.
///
/// # Safety
///
/// The [`HotFnPtr`] must be to a function whose arguments layouts haven't changed.
pub unsafe fn try_call_with_ptr(
&mut self,
ptr: HotFnPtr,
args: A,
) -> Result<F::Return, HotFnPanic> {
if !cfg!(debug_assertions) {
return Ok(self.inner.call_it(args));
}
unsafe {
// Try to handle known function pointers. This is *really really* unsafe, but due to how
// rust trait objects work, it's impossible to make an arbitrary usize-sized type implement Fn()
// since that would require a vtable pointer, pushing out the bounds of the pointer size.
if size_of::<F>() == size_of::<fn() -> ()>() {
return Ok(self.inner.call_as_ptr(args));
}
// Handle trait objects. This will occur for sizes other than usize. Normal rust functions
// become ZST's and thus their <T as SomeFn>::call becomes a function pointer to the function.
//
// For non-zst (trait object) types, then there might be an issue. The real call function
// will likely end up in the vtable and will never be hot-reloaded since signature takes self.
// The type sig of the cast should match the call_it function
// Technically function pointers need to be aligned, but that alignment is 1 so we're good
let call_it = transmute::<*const (), fn(&F, A) -> F::Return>(ptr.0 as _);
Ok(call_it(&self.inner, args))
}
}
}
/// Apply the patch using a given jump table.
///
/// # Safety
///
/// This function is unsafe because it detours existing functions in memory. This is *wildly* unsafe,
/// especially if the JumpTable is malformed. Only run this if you know what you're doing.
///
/// If the pointers are incorrect, function type signatures will be incorrect and the program will crash,
/// sometimes in a way that requires a restart of your entire computer. Be careful.
///
/// # Warning
///
/// This function will load the library and thus allocates. In cannot be used when the program is
/// stopped (ie in a signal handler).
pub unsafe fn apply_patch(mut table: JumpTable) -> Result<(), PatchError> {
// On non-wasm platforms we can just use libloading and the known aslr offsets to load the library
#[cfg(any(unix, windows))]
{
// on android we try to circumvent permissions issues by copying the library to a memmap and then libloading that
#[cfg(target_os = "android")]
let lib = Box::leak(Box::new(android_memmap_dlopen(&table.lib)?));
#[cfg(not(target_os = "android"))]
let lib = Box::leak(Box::new({
match libloading::Library::new(&table.lib) {
Ok(lib) => lib,
Err(err) => return Err(PatchError::Dlopen(err.to_string())),
}
}));
// Use the `main` symbol as a sentinel for the current executable. This is basically a
// cross-platform version of `__mh_execute_header` on macOS that we can use to base the executable.
let old_offset = aslr_reference() - table.aslr_reference as usize;
// Use the `main` symbol as a sentinel for the loaded library. Might want to move away
// from this at some point, or make it configurable
let new_offset = unsafe {
// Leak the library. dlopen is basically a no-op on many platforms and if we even try to drop it,
// some code might be called (ie drop) that results in really bad crashes (restart your computer...)
//
// This code currently assumes "main" always makes it to the export list (which it should)
// and requires coordination from the CLI to export it.
lib.get::<*const ()>(b"main")
.ok()
.unwrap()
.try_as_raw_ptr()
.unwrap()
.wrapping_byte_sub(table.new_base_address as usize) as usize
};
// Modify the jump table to be relative to the base address of the loaded library
table.map = table
.map
.iter()
.map(|(k, v)| {
(
(*k as usize + old_offset) as u64,
(*v as usize + new_offset) as u64,
)
})
.collect();
commit_patch(table);
};
// On wasm, we need to download the module, compile it, and then run it.
#[cfg(target_arch = "wasm32")]
wasm_bindgen_futures::spawn_local(async move {
use js_sys::{
ArrayBuffer, Object, Reflect,
WebAssembly::{self, Memory, Table},
};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsValue;
use wasm_bindgen::UnwrapThrowExt;
use wasm_bindgen_futures::JsFuture;
let funcs: Table = wasm_bindgen::function_table().unchecked_into();
let memory: Memory = wasm_bindgen::memory().unchecked_into();
let exports: Object = wasm_bindgen::exports().unchecked_into();
let buffer: ArrayBuffer = memory.buffer().unchecked_into();
let path = table.lib.to_str().unwrap();
if !path.ends_with(".wasm") {
return;
}
// Start the fetch of the module
let response = web_sys::window().unwrap_throw().fetch_with_str(&path);
// Wait for the fetch to complete - we need the wasm module size in bytes to reserve in the memory
let response: web_sys::Response = JsFuture::from(response).await.unwrap().unchecked_into();
// If the status is not success, we bail
if !response.ok() {
panic!(
"Failed to patch wasm module at {} - response failed with: {}",
path,
response.status_text()
);
}
let dl_bytes: ArrayBuffer = JsFuture::from(response.array_buffer().unwrap())
.await
.unwrap()
.unchecked_into();
// Expand the memory and table size to accommodate the new data and functions
//
// Normally we wouldn't be able to trust that we are allocating *enough* memory
// for BSS segments, but ld emits them in the binary when using import-memory.
//
// Make sure we align the memory base to the page size
const PAGE_SIZE: u32 = 64 * 1024;
let page_count = (buffer.byte_length() as f64 / PAGE_SIZE as f64).ceil() as u32;
let memory_base = (page_count + 1) * PAGE_SIZE;
// We need to grow the memory to accommodate the new module
memory.grow((dl_bytes.byte_length() as f64 / PAGE_SIZE as f64).ceil() as u32 + 1);
// We grow the ifunc table to accommodate the new functions
// In theory we could just put all the ifuncs in the jump map and use that for our count,
// but there's no guarantee from the jump table that it references "itself"
// We might need a sentinel value for each ifunc in the jump map to indicate that it is
let table_base = funcs.grow(table.ifunc_count as u32).unwrap();
// Adjust the jump table to be relative to the new base address
for v in table.map.values_mut() {
*v += table_base as u64;
}
// Build up the import object. We copy everything over from the current exports, but then
// need to add in the memory and table base offsets for the relocations to work.
//
// let imports = {
// env: {
// memory: base.memory,
// __tls_base: base.__tls_base,
// __stack_pointer: base.__stack_pointer,
// __indirect_function_table: base.__indirect_function_table,
// __memory_base: memory_base,
// __table_base: table_base,
// ..base_exports
// },
// };
let env = Object::new();
// Move memory, __tls_base, __stack_pointer, __indirect_function_table, and all exports over
for key in Object::keys(&exports) {
Reflect::set(&env, &key, &Reflect::get(&exports, &key).unwrap()).unwrap();
}
// Set the memory and table in the imports
// Following this pattern: Global.new({ value: "i32", mutable: false }, value)
for (name, value) in [("__table_base", table_base), ("__memory_base", memory_base)] {
let descriptor = Object::new();
Reflect::set(&descriptor, &"value".into(), &"i32".into()).unwrap();
Reflect::set(&descriptor, &"mutable".into(), &false.into()).unwrap();
let value = WebAssembly::Global::new(&descriptor, &value.into()).unwrap();
Reflect::set(&env, &name.into(), &value.into()).unwrap();
}
// Set the memory and table in the imports
let imports = Object::new();
Reflect::set(&imports, &"env".into(), &env).unwrap();
// Download the module, returning { module, instance }
// we unwrap here instead of using `?` since this whole thing is async
let result_object = JsFuture::from(WebAssembly::instantiate_module(
dl_bytes.unchecked_ref(),
&imports,
))
.await
.unwrap();
// We need to run the data relocations and then fire off the constructors
let res: Object = result_object.unchecked_into();
let instance: Object = Reflect::get(&res, &"instance".into())
.unwrap()
.unchecked_into();
let exports: Object = Reflect::get(&instance, &"exports".into())
.unwrap()
.unchecked_into();
_ = Reflect::get(&exports, &"__wasm_apply_data_relocs".into())
.unwrap()
.unchecked_into::<js_sys::Function>()
.call0(&JsValue::undefined());
_ = Reflect::get(&exports, &"__wasm_apply_global_relocs".into())
.unwrap()
.unchecked_into::<js_sys::Function>()
.call0(&JsValue::undefined());
_ = Reflect::get(&exports, &"__wasm_call_ctors".into())
.unwrap()
.unchecked_into::<js_sys::Function>()
.call0(&JsValue::undefined());
unsafe { commit_patch(table) };
});
Ok(())
}
#[derive(Debug, PartialEq, thiserror::Error)]
pub enum PatchError {
/// The patch failed to apply.
///
/// This returns a string instead of the Dlopen error type so we don't need to bring the libloading
/// dependency into the public API.
#[error("Failed to load library: {0}")]
Dlopen(String),
/// The patch failed to apply on Android, most likely due to a permissions issue.
#[error("Failed to load library on Android: {0}")]
AndroidMemfd(String),
}
/// This function returns the address of the main function in the current executable. This is used as
/// an anchor to reference the current executable's base address.
///
/// The point here being that we have a stable address both at runtime and compile time, making it
/// possible to calculate the ASLR offset from within the process to correct the jump table.
///
/// It should only be called from the main executable *first* and not from a shared library since it
/// self-initializes.
#[doc(hidden)]
pub fn aslr_reference() -> usize {
#[cfg(target_family = "wasm")]
return 0;
#[cfg(not(target_family = "wasm"))]
unsafe {
use std::ffi::c_void;
// The first call to this function should occur in the
static mut MAIN_PTR: *mut c_void = std::ptr::null_mut();
if MAIN_PTR.is_null() {
#[cfg(unix)]
{
MAIN_PTR = libc::dlsym(libc::RTLD_DEFAULT, c"main".as_ptr() as _);
}
#[cfg(windows)]
{
extern "system" {
fn GetModuleHandleA(lpModuleName: *const i8) -> *mut std::ffi::c_void;
fn GetProcAddress(
hModule: *mut std::ffi::c_void,
lpProcName: *const i8,
) -> *mut std::ffi::c_void;
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/fullstack-hydration-order/src/main.rs | packages/playwright-tests/fullstack-hydration-order/src/main.rs | // Adjacent server components that both use server functions shouldn't cause
// hydration issues
// https://github.com/DioxusLabs/dioxus/issues/4595
use dioxus::prelude::*;
fn main() {
dioxus::launch(|| rsx! { Home {} });
}
#[component]
pub fn Home() -> Element {
let mut count = use_signal(|| 0);
rsx! {
div {
MyStrings {}
MyFloats {}
}
button {
id: "counter",
onclick: move |_| count += 1,
"Count {count}"
}
}
}
#[component]
fn MyStrings() -> Element {
let strings = use_server_future(get_strings)?;
let data = match &*strings.read() {
Some(Ok(data)) => data.clone(),
_ => vec![],
};
rsx! {
div {
for string in data.iter() {
p { "{string}" }
}
}
}
}
#[get("/api/get_strings")]
pub async fn get_strings() -> Result<Vec<String>, ServerFnError> {
let data: Vec<String> = vec!["Hello".to_string(), "World".to_string()];
Ok(data)
}
#[component]
fn MyFloats() -> Element {
let floats = use_server_future(get_floats)?;
let data = match &*floats.read() {
Some(Ok(data)) => data.clone(),
_ => vec![],
};
rsx! {
div {
for float in data.iter() {
p { "{float}" }
}
}
}
}
#[get("/api/get_floats")]
pub async fn get_floats() -> Result<Vec<f32>, ServerFnError> {
let data: Vec<f32> = vec![1.0, 2.0, 3.0];
Ok(data)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/windows-headless/src/main.rs | packages/playwright-tests/windows-headless/src/main.rs | use dioxus::LaunchBuilder;
use dioxus::prelude::*;
fn main() {
LaunchBuilder::new()
.with_cfg(
dioxus::desktop::Config::new()
.with_windows_browser_args("--remote-debugging-port=8787"),
)
.launch(app);
}
fn app() -> Element {
let mut count = use_signal(|| 0);
rsx! {
h1 { "High-five counter: {count}" }
button {
id: "increment-button",
onclick: move |_| count += 1, "Up high!"
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/default-features-disabled/src/main.rs | packages/playwright-tests/default-features-disabled/src/main.rs | // This test asserts that the client feature is disable on the server build by the cli
// even if it is set as a default feature
#![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
launch(app);
}
fn app() -> Element {
let server_features = use_server_future(get_server_features)?.unwrap().unwrap();
let mut client_features = use_signal(Vec::new);
use_effect(move || {
client_features.set(current_platform_features());
});
let mut count = use_signal(|| 0);
rsx! {
div {
"server features: {server_features:?}"
}
div {
"client features: {client_features:?}"
}
button {
onclick: move |_| count += 1,
"{count}"
}
}
}
fn current_platform_features() -> Vec<String> {
let mut features = Vec::new();
if cfg!(feature = "web") {
features.push("web".to_string());
}
if cfg!(feature = "server") {
features.push("server".to_string());
}
features
}
#[server]
async fn get_server_features() -> ServerFnResult<Vec<String>> {
Ok(current_platform_features())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/wasm-split-harness/src/main.rs | packages/playwright-tests/wasm-split-harness/src/main.rs | //! This file is a fuzz-test for the wasm-split engine to ensure that it works as expected.
//! The docsite is a better target for this, but we try to boil down the complexity into this small
//! test file.
#![allow(non_snake_case)]
use dioxus::prelude::*;
use futures::AsyncReadExt;
use js_sys::Date;
use std::pin::Pin;
use wasm_bindgen::prelude::*;
use wasm_split::lazy_loader;
fn main() {
dioxus::launch(|| {
rsx! {
Router::<Route> {}
}
});
}
#[derive(Routable, PartialEq, Eq, Debug, Clone)]
enum Route {
#[layout(Nav)]
#[route("/")]
Home,
#[route("/child")]
ChildSplit,
}
fn Nav() -> Element {
rsx! {
div {
Link { id: "link-home", to: Route::Home, "Home" }
Link { id: "link-child", to: Route::ChildSplit, "Child" }
Outlet::<Route> {}
}
}
}
pub(crate) static GLOBAL_COUNTER: GlobalSignal<usize> = Signal::global(|| 0);
fn Home() -> Element {
let mut count = use_signal(|| 1);
let mut res = use_signal(|| "hello".to_string());
rsx! {
h1 { "Hello bundle split 456" }
h3 { id: "counter-display", "Count: {count}" }
h3 { id: "global-counter", "Global Counter: {GLOBAL_COUNTER}" }
button {
id: "increment-counter",
onclick: move |_| count += 1,
"Click me"
}
button {
id: "increment-counter-global",
onclick: move |_| *GLOBAL_COUNTER.write() += 1,
"Click me"
}
button {
id: "add-body-text",
onclick: move |_| add_body_text(),
"Add body text"
}
button {
id: "add-body-element",
onclick: move |_| async move {
add_body_element().await;
count += 1;
},
"Add body element"
}
button {
id: "gzip-it",
onclick: move |_| async move {
gzip_it().await;
},
"GZIP it"
}
button {
id: "brotli-it",
onclick: move |_| async move {
brotli_it(&[0u8; 10]).await;
},
"Brotli It"
}
button {
id: "make-request",
onclick: move |_| async move {
let res_ = make_request().await.unwrap();
res.set(res_);
},
"Make Request!"
}
button {
id: "make-local-request",
onclick: move |_| async move {
let client = reqwest::Client::new();
let response = client
.get("https://dog.ceo/api/breeds/image/random")
.send()
.await?;
let body = response.text().await?;
*res.write() = body;
Ok(())
},
"local request"
}
LazyComponent {
abc: 0
}
div { "Response: {res}" }
div { id: "output-box" }
}
}
#[wasm_split::wasm_split(one)]
async fn add_body_text() {
let window = web_sys::window().unwrap_throw();
let document = window.document().unwrap_throw();
let output = document.create_text_node("Rendered!");
let output_box = document.get_element_by_id("output-box").unwrap_throw();
output_box.append_child(&output).unwrap_throw();
*GLOBAL_COUNTER.write() += 1;
}
#[wasm_split::wasm_split(two)]
async fn add_body_element() {
let window = web_sys::window().unwrap_throw();
let document = window.document().unwrap_throw();
let output = document.create_element("div").unwrap_throw();
output.set_text_content(Some("Some inner div"));
let output_box = document.get_element_by_id("output-box").unwrap_throw();
output_box.append_child(&output).unwrap_throw();
dioxus::core::queue_effect(move || {
web_sys::console::log_1(&"add body async internal!".into());
*GLOBAL_COUNTER.write() += 2;
});
}
#[wasm_split::wasm_split(four)]
async fn gzip_it() {
static DATA: &[u8] = &[0u8; 10];
let reader = Box::pin(futures::io::BufReader::new(DATA));
let reader: Pin<Box<dyn futures::io::AsyncBufRead>> = reader;
dioxus::core::spawn(async move {
let mut fut = Box::pin(async_compression::futures::bufread::GzipDecoder::new(
reader,
));
if fut.read_to_end(&mut Vec::new()).await.is_err() {
web_sys::console::log_1(&"error reading gzip".into());
}
*GLOBAL_COUNTER.write() += 3;
let res: Result<String, anyhow::Error> = Box::pin(async move {
let client = reqwest::Client::new();
let response = client
.get("https://dog.ceo/api/breeds/image/random")
.send()
.await?;
let body = response.text().await?;
Ok(body)
})
.await;
if res.is_err() {
web_sys::console::log_1(&"error making request".into());
}
});
}
#[wasm_split::wasm_split(three)]
async fn brotli_it(data: &'static [u8]) {
let reader = Box::pin(futures::io::BufReader::new(data));
let reader: Pin<Box<dyn futures::io::AsyncBufRead>> = reader;
dioxus::core::spawn(async move {
let mut fut = Box::pin(async_compression::futures::bufread::BrotliDecoder::new(
reader,
));
if fut.read_to_end(&mut Vec::new()).await.is_err() {
web_sys::console::log_1(&"error reading brotli".into());
}
*GLOBAL_COUNTER.write() += 4;
});
}
#[wasm_split::wasm_split(eleven)]
async fn make_request() -> Result<String, anyhow::Error> {
let client = reqwest::Client::new();
let response = client
.get("https://dog.ceo/api/breeds/image/random")
.send()
.await?;
let body = response.text().await?;
Ok(body)
}
#[component(lazy)]
fn LazyComponent(abc: i32) -> Element {
rsx! {
div {
"This is a lazy component! {abc}"
}
}
}
fn ChildSplit() -> Element {
pub(crate) static DATE: GlobalSignal<Date> = Signal::global(Date::new_0);
static LOADER: wasm_split::LazyLoader<(), Element> =
lazy_loader!(extern "five" fn InnerChild(props: ()) -> Element);
fn InnerChild(_props: ()) -> Element {
static LOADER2: wasm_split::LazyLoader<Signal<String>, Element> =
lazy_loader!(extern "fortytwo" fn InnerChild3(props: Signal<String>) -> Element);
fn InnerChild3(count: Signal<String>) -> Element {
pub(crate) static ICONCHECK: Component<()> = |_| {
rsx! {
svg {
class: "octicon octicon-check js-clipboard-check-icon d-inline-block d-none",
fill: "rgb(26, 127, 55)",
height: "24",
version: "1.1",
"aria_hidden": "true",
width: "24",
view_box: "0 0 16 16",
"data_view_component": "true",
path {
d: "M13.78 4.22a.75.75 0 010 1.06l-7.25 7.25a.75.75 0 01-1.06 0L2.22 9.28a.75.75 0 011.06-1.06L6 10.94l6.72-6.72a.75.75 0 011.06 0z",
fill_rule: "evenodd",
}
}
button {
onclick: move |_| {
*DATE.write() = Date::new_0();
},
"Update Date"
}
}
};
let now = DATE.read().clone();
rsx! {
h1 { "Some other child" }
h3 { "Global Counter: {GLOBAL_COUNTER}" }
h3 { "Date: {now.to_date_string()}" }
h3 { "count: {count}" }
ICONCHECK {}
}
}
#[wasm_bindgen(module = "/src/stars.js")]
extern "C" {
pub(crate) fn get_stars(name: String) -> Option<usize>;
pub(crate) fn set_stars(name: String, stars: usize);
}
let num = get_stars("stars".to_string()).unwrap_or(0);
use_resource(|| async move { LOADER2.load().await }).suspend()?;
let mut count = use_signal(|| "hello".to_string());
let fp = LOADER2.call(count).unwrap();
rsx! {
h1 { "Some huge child?" }
p { "Stars: {num}" }
button {
onclick: move |_| {
set_stars("stars".to_string(), num + 1);
dioxus::core::needs_update();
},
"Add Star"
}
{fp}
h3 { id: "nested-child-count", "Count: {count}" }
button {
id: "nested-child-add-world",
onclick: move |_| {
*count.write() += " world";
},
"Add World"
}
}
}
use_resource(|| async move { LOADER.load().await }).suspend()?;
LOADER.call(()).unwrap()
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/fullstack-mounted/src/main.rs | packages/playwright-tests/fullstack-mounted/src/main.rs | // Regression test for https://github.com/DioxusLabs/dioxus/pull/3480
use dioxus::prelude::*;
fn main() {
dioxus::launch(App);
}
#[component]
fn App() -> Element {
let mut mounted = use_signal(|| false);
rsx! {
div {
onmounted: move |_| {
mounted.set(true);
},
if mounted() {
"The mounted event was triggered."
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/fullstack/src/main.rs | packages/playwright-tests/fullstack/src/main.rs | // This test is used by playwright configured in the root of the repo
// Tests:
// - Server functions
// - SSR
// - Hydration
#![allow(non_snake_case)]
use dioxus::fullstack::{commit_initial_chunk, Websocket};
use dioxus::{fullstack::WebSocketOptions, prelude::*};
fn main() {
#[cfg(feature = "server")]
dioxus::serve(|| async move {
use dioxus::server::axum::{self, Extension};
let cfg = dioxus::server::ServeConfig::builder().enable_out_of_order_streaming();
let router = axum::Router::new()
.serve_dioxus_application(cfg, app)
.layer(Extension(1234u32));
Ok(router)
});
#[cfg(not(feature = "server"))]
launch(app);
}
fn app() -> Element {
let mut count = use_signal(|| 12345);
let mut text = use_signal(|| "...".to_string());
rsx! {
Title { "hello axum! {count}" }
h1 { "hello axum! {count}" }
button { class: "increment-button", onclick: move |_| count += 1, "Increment" }
button {
class: "server-button",
onclick: move |_| async move {
if let Ok(data) = get_server_data().await {
println!("Client received: {}", data);
text.set(data.clone());
post_server_data(data).await.unwrap();
}
},
"Run a server function!"
}
"Server said: {text}"
div {
id: "errors",
Errors {}
}
OnMounted {}
DefaultServerFnCodec {}
DocumentElements {}
Assets {}
WebSockets {}
}
}
#[component]
fn OnMounted() -> Element {
let mut mounted_triggered_count = use_signal(|| 0);
rsx! {
div {
class: "onmounted-div",
onmounted: move |_| {
mounted_triggered_count += 1;
},
"onmounted was called {mounted_triggered_count} times"
}
}
}
#[component]
fn DefaultServerFnCodec() -> Element {
let resource = use_server_future(|| get_server_data_empty_vec(Vec::new()))?;
let empty_vec = resource.unwrap().unwrap();
assert!(empty_vec.is_empty());
rsx! {}
}
#[cfg(feature = "server")]
async fn assert_server_context_provided() {
use dioxus::{fullstack::FullstackContext, server::axum::Extension};
// Just make sure the server context is provided
let Extension(id): Extension<u32> = FullstackContext::extract().await.unwrap();
assert_eq!(id, 1234u32);
}
#[server]
async fn post_server_data(data: String) -> ServerFnResult {
assert_server_context_provided().await;
println!("Server received: {}", data);
Ok(())
}
#[server]
async fn get_server_data() -> ServerFnResult<String> {
assert_server_context_provided().await;
Ok("Hello from the server!".to_string())
}
// Make sure the default codec work with empty data structures
// Regression test for https://github.com/DioxusLabs/dioxus/issues/2628
#[server]
async fn get_server_data_empty_vec(empty_vec: Vec<String>) -> ServerFnResult<Vec<String>> {
assert_server_context_provided().await;
assert!(empty_vec.is_empty());
Ok(Vec::new())
}
#[server]
async fn server_error() -> ServerFnResult<String> {
use dioxus_core::AnyhowContext;
assert_server_context_provided().await;
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
Err(None.context("Server error occurred")?)
}
#[component]
fn Errors() -> Element {
// Make the suspense boundary below happen during streaming
use_hook(commit_initial_chunk);
rsx! {
// This is a tricky case for suspense https://github.com/DioxusLabs/dioxus/issues/2570
// Root suspense boundary is already resolved when the inner suspense boundary throws an error.
// We need to throw the error from the inner suspense boundary on the server to the hydrated
// suspense boundary on the client
ErrorBoundary {
handle_error: |_| rsx! {
"Hmm, something went wrong."
},
SuspenseBoundary {
fallback: |_: SuspenseContext| rsx! {
div {
"Loading..."
}
},
ThrowsError {}
}
}
}
}
#[component]
pub fn ThrowsError() -> Element {
use_server_future(server_error)?.unwrap()?;
rsx! {
"success"
}
}
/// This component tests the document::* elements pre-rendered on the server
#[component]
fn DocumentElements() -> Element {
rsx! {
document::Meta { id: "meta-head", name: "testing", data: "dioxus-meta-element" }
document::Link {
id: "link-head",
rel: "stylesheet",
href: "https://fonts.googleapis.com/css?family=Roboto+Mono"
}
document::Stylesheet { id: "stylesheet-head", href: "https://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic" }
document::Script { id: "script-head", async: true, "console.log('hello world');" }
document::Style { id: "style-head", "body {{ font-family: 'Roboto'; }}" }
}
}
/// Make sure assets in the assets folder are served correctly and hashed assets are cached forever
#[component]
fn Assets() -> Element {
#[used]
static _ASSET: Asset = asset!("/assets/image.png");
#[used]
static _STATIC_NO_HASH: Asset = asset!(
"/assets/image.png",
AssetOptions::image().with_hash_suffix(false)
);
#[used]
static _UNHASHED_FOLDER: Asset = asset!(
"/assets/nested/",
AssetOptions::folder().with_hash_suffix(false)
);
#[used]
static _EMBEDDED_FOLDER: Asset = asset!("/assets/nested");
rsx! {
img {
src: asset!("/assets/image.png"),
}
img {
src: "{_EMBEDDED_FOLDER}/image.png",
}
img {
src: "{_UNHASHED_FOLDER}/image.png",
}
img {
src: "/assets/image.png",
}
}
}
/// This component tests websocket server functions
#[component]
fn WebSockets() -> Element {
let mut received = use_signal(String::new);
use_future(move || async move {
let socket = echo_ws(WebSocketOptions::default()).await.unwrap();
socket.send("hello world".to_string()).await.unwrap();
while let Ok(msg) = socket.recv().await {
received.write().push_str(&msg);
}
});
rsx! {
div {
id: "websocket-div",
"Received: {received}"
}
}
}
#[get("/api/echo_ws")]
async fn echo_ws(options: WebSocketOptions) -> Result<Websocket> {
info!("Upgrading to websocket");
Ok(options.on_upgrade(
|mut tx: dioxus::fullstack::TypedWebsocket<String, String>| async move {
while let Ok(msg) = tx.recv().await {
let _ = tx.send(msg.to_ascii_uppercase()).await;
}
},
))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/liveview/src/main.rs | packages/playwright-tests/liveview/src/main.rs | // This test is used by playwright configured in the root of the repo
use axum::{extract::ws::WebSocketUpgrade, response::Html, routing::get, Router};
use dioxus::{logger::tracing::Level, prelude::*};
fn app() -> Element {
let mut num = use_signal(|| 0);
rsx! {
div {
"hello axum! {num}"
button { onclick: move |_| num += 1, "Increment" }
}
svg { circle { cx: 50, cy: 50, r: 40, stroke: "green", fill: "yellow" } }
div { class: "raw-attribute-div", "raw-attribute": "raw-attribute-value" }
div { class: "hidden-attribute-div", hidden: true }
div {
class: "dangerous-inner-html-div",
dangerous_inner_html: "<p>hello dangerous inner html</p>"
}
input { value: "hello input" }
div { class: "style-div", color: "red", "colored text" }
OnMounted {}
}
}
#[component]
fn OnMounted() -> Element {
let mut mounted_triggered_count = use_signal(|| 0);
rsx! {
div {
class: "onmounted-div",
onmounted: move |_| {
mounted_triggered_count += 1;
},
"onmounted was called {mounted_triggered_count} times"
}
}
}
#[tokio::main]
async fn main() {
_ = dioxus::logger::init(Level::DEBUG);
let addr: std::net::SocketAddr = ([127, 0, 0, 1], 3030).into();
let view = dioxus_liveview::LiveViewPool::new();
let app = Router::new()
.route(
"/",
get(move || async move {
Html(format!(
r#"
<!DOCTYPE html>
<html>
<head> <title>Dioxus LiveView with axum</title> </head>
<body> <div id="main"></div> </body>
{glue}
</html>
"#,
glue = dioxus_liveview::interpreter_glue(&format!("ws://{addr}/ws"))
))
}),
)
.route(
"/ws",
get(move |ws: WebSocketUpgrade| async move {
ws.on_upgrade(move |socket| async move {
_ = view.launch(dioxus_liveview::axum_socket(socket), app).await;
})
}),
);
println!("Listening on http://{addr}");
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/web-routing/src/main.rs | packages/playwright-tests/web-routing/src/main.rs | use dioxus::prelude::*;
fn main() {
launch(|| {
rsx! {
Router::<Route> {}
}
})
}
#[derive(Routable, Clone, PartialEq)]
#[rustfmt::skip]
enum Route {
#[redirect("/",|| Route::Other)]
#[route("/other")]
Other,
#[route("/other/:id")]
OtherId { id: String },
#[route("/:..segments")]
NotFound { segments: Vec<String> },
}
#[component]
fn Other() -> Element {
rsx! {
div {
id: "other",
"Other"
}
Link {
id: "other-id-link",
to: Route::OtherId { id: "123".to_string() },
"go to OtherId"
}
}
}
#[component]
fn OtherId(id: String) -> Element {
rsx! {
div {
id: "other-id",
"OtherId {id}"
}
}
}
#[component]
fn NotFound(segments: Vec<String>) -> Element {
rsx! {
div {
id: "not-found",
"NotFound {segments:?}"
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/barebones-template/src/main.rs | packages/playwright-tests/barebones-template/src/main.rs | use dioxus::prelude::*;
const FAVICON: Asset = asset!("/assets/favicon.ico");
const MAIN_CSS: Asset = asset!("/assets/main.css");
const HEADER_SVG: Asset = asset!("/assets/header.svg");
fn main() {
dioxus::launch(App);
}
#[component]
fn App() -> Element {
rsx! {
document::Link { rel: "icon", href: FAVICON }
document::Link { rel: "stylesheet", href: MAIN_CSS }
Hero {}
}
}
#[component]
pub fn Hero() -> Element {
rsx! {
div {
id: "hero",
img { src: HEADER_SVG, id: "header" }
div { id: "links",
a { href: "https://dioxuslabs.com/learn/0.7/", "📚 Learn Dioxus" }
a { href: "https://dioxuslabs.com/awesome", "🚀 Awesome Dioxus" }
a { href: "https://github.com/dioxus-community/", "📡 Community Libraries" }
a { href: "https://github.com/DioxusLabs/sdk", "⚙️ Dioxus Development Kit" }
a { href: "https://marketplace.visualstudio.com/items?itemName=DioxusLabs.dioxus", "💫 VSCode Extension" }
a { href: "https://discord.gg/XgGxMSkvUM", "👋 Community Discord" }
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/web-hot-patch/src/main.rs | packages/playwright-tests/web-hot-patch/src/main.rs | use dioxus::prelude::*;
const CSS: Asset = asset!("/assets/style.css");
const IMAGE: Asset = asset!("/assets/toasts.png");
fn app() -> Element {
let mut num = use_signal(|| 0);
// make sure to emit funky closure code in this module to test wasm-bindgen handling
let _closures = wasm_bindgen::closure::Closure::<dyn FnMut(web_sys::MouseEvent)>::new(
move |event: web_sys::MouseEvent| {},
);
rsx! {
document::Link {
href: CSS,
rel: "stylesheet",
}
img {
id: "toasts",
src: IMAGE,
}
button {
id: "increment-button",
onclick: move |_| {
num += 1;
},
"Click me! Count: {num}"
}
}
}
fn main() {
dioxus::launch(app);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/fullstack-spread/src/main.rs | packages/playwright-tests/fullstack-spread/src/main.rs | //! Regression test for <https://github.com/DioxusLabs/dioxus/issues/4646>
use dioxus::prelude::*;
fn main() {
// we split these two to ensure `dioxus::serve` works properly.
#[cfg(feature = "server")]
dioxus::serve(|| async move { Ok(dioxus::server::router(app)) });
#[cfg(not(feature = "server"))]
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
Comp {}
Comp {}
Button {}
}
}
#[component]
fn Button() -> Element {
let mut count = use_signal(|| 0);
rsx! {
button {
id: "counter",
onclick: move |_| {
count += 1;
},
"Count: {count}"
}
}
}
#[component]
fn Comp(#[props(extends = GlobalAttributes)] attributes: Vec<Attribute>) -> Element {
rsx! {
div {
width: 100,
div {
..attributes,
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/fullstack-error-codes/src/main.rs | packages/playwright-tests/fullstack-error-codes/src/main.rs | //! To render custom error pages, you can create a layout component that captures errors from routes
//! with an `ErrorBoundary` and display different content based on the error type.
//!
//! While capturing the error, we set the appropriate HTTP status code using `FullstackContext::commit_error_status`.
//! The router will then use this status code when doing server-side rendering (SSR).
//!
//! Any errors not captured by an error boundary will be handled by dioxus-ssr itself, which will render
//! a generic error page instead.
use dioxus::prelude::*;
use dioxus_fullstack::{FullstackContext, StatusCode};
fn main() {
dioxus::launch(|| {
rsx! {
Router::<Route> {}
}
});
}
#[derive(Routable, PartialEq, Clone, Debug)]
enum Route {
#[layout(ErrorLayout)]
#[route("/")]
Home,
#[route("/blog/:id")]
Blog { id: u32 },
}
#[component]
fn Home() -> Element {
rsx! {
div { "Welcome to the home page!" }
div { display: "flex", flex_direction: "column",
Link { to: Route::Blog { id: 1 }, "Go to blog post 1" }
Link { to: Route::Blog { id: 2 }, "Go to blog post 2 (201)" }
Link { to: Route::Blog { id: 3 }, "Go to blog post 3 (error)" }
Link { to: Route::Blog { id: 4 }, "Go to blog post 4 (not found)" }
}
}
}
#[component]
fn Blog(id: u32) -> Element {
match id {
1 => rsx! { div { "Blog post 1" } },
2 => {
FullstackContext::commit_http_status(StatusCode::CREATED, None);
rsx! { div { "Blog post 2" } }
}
3 => dioxus_core::bail!("An error occurred while loading the blog post!"),
_ => HttpError::not_found("Blog post not found")?,
}
}
/// In our `ErrorLayout` component, we wrap the `Outlet` in an `ErrorBoundary`. This lets us attempt
/// to downcast the error to an `HttpError` and set the appropriate status code.
///
/// The `commit_error_status` function will attempt to downcast the error to an `HttpError` and
/// set the status code accordingly. Note that you can commit any status code you want with `commit_http_status`.
///
/// The router will automatically set the HTTP status code when doing SSR.
#[component]
fn ErrorLayout() -> Element {
rsx! {
ErrorBoundary {
handle_error: move |err: ErrorContext| {
let http_error = FullstackContext::commit_error_status(err.error().unwrap());
match http_error.status {
StatusCode::NOT_FOUND => rsx! { div { "404 - Page not found" } },
StatusCode::UNAUTHORIZED => rsx! { div { "401 - Unauthorized" } },
StatusCode::INTERNAL_SERVER_ERROR => rsx! { div { "500 - Internal Server Error" } },
_ => rsx! { div { "An unknown error occurred" } },
}
},
Outlet::<Route> {}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/fullstack-errors/src/main.rs | packages/playwright-tests/fullstack-errors/src/main.rs | // This test is used by playwright configured in the root of the repo
// Tests:
// - Errors that originate in the initial render
#![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
dioxus::launch(app);
}
fn app() -> Element {
rsx! {
Errors {}
}
}
#[server]
async fn server_error() -> ServerFnResult<String> {
tokio::time::sleep(tokio::time::Duration::from_millis(1000)).await;
Err(ServerFnError::new("the server threw an error!"))
}
#[component]
fn Errors() -> Element {
rsx! {
// This is a tricky case for suspense https://github.com/DioxusLabs/dioxus/issues/2570
// Root suspense boundary is already resolved when the inner suspense boundary throws an error.
// We need to throw the error from the inner suspense boundary on the server to the hydrated
// suspense boundary on the client
ErrorBoundary {
handle_error: |_| rsx! {
ErrorFallbackButton {}
},
SuspenseBoundary {
fallback: |_: SuspenseContext| rsx! {
div {
"Loading..."
}
},
ThrowsError {}
}
}
}
}
#[component]
pub fn ErrorFallbackButton() -> Element {
let mut count = use_signal(|| 0);
rsx! {
// Make sure the error fallback is interactive after hydration
button {
id: "error-fallback-button",
onclick: move |_| count += 1,
"Error fallback button clicked {count} times"
}
}
}
#[component]
pub fn ThrowsError() -> Element {
use_server_future(server_error)?.unwrap()?;
rsx! {
"success"
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/cli-optimization/build.rs | packages/playwright-tests/cli-optimization/build.rs | fn main() {
// use std::path::PathBuf;
// // If the monaco editor folder doesn't exist, download it
// let monaco_path = PathBuf::from("monaco-editor");
// if monaco_path.exists() {
// return;
// }
// let url = "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.52.2.tgz";
// let bytes = reqwest::blocking::get(url).unwrap().bytes().unwrap();
// let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(bytes.as_ref()));
// let monaco_path_partial = PathBuf::from("partial-monaco-editor");
// archive.unpack(&monaco_path_partial).unwrap();
// std::fs::rename(monaco_path_partial, monaco_path).unwrap();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/cli-optimization/src/lib.rs | packages/playwright-tests/cli-optimization/src/lib.rs | // This test checks the CLI optimizes assets correctly without breaking them
use dioxus::prelude::*;
const SOME_IMAGE: Asset = asset!("/images/toasts.png", AssetOptions::image().with_avif());
const SOME_IMAGE_WITH_THE_SAME_URL: Asset =
asset!("/images/toasts.png", AssetOptions::image().with_jpg());
#[used]
static SOME_IMAGE_WITHOUT_HASH: Asset = asset!(
"/images/toasts.png",
AssetOptions::image().with_avif().with_hash_suffix(false)
);
// This asset is unused, but it should still be bundled because it is an external asset
#[used]
static _ASSET: Asset = asset!(
"/images/toasts.png",
AssetOptions::builder().with_hash_suffix(false)
);
pub fn main() {
dioxus::launch(App);
}
#[component]
fn App() -> Element {
// todo: test monaco more....
// const MONACO_FOLDER: Asset = asset!("/monaco-editor/package/min/vs");
// let script = format!("(() => {{
// require.config({{ paths: {{ vs: '{MONACO_FOLDER}' }} }});
// require(['vs/editor/editor.main'], () => {{
// var model = monaco.editor.createModel('fn main() {{\\n\\tprintln!(\\\"hi\\\")\\n}}', 'rust');
// var editor = monaco.editor.create(document.getElementById('editor'));
// editor.setModel(model);
// }})
// }})()");
rsx! {
div {
id: "editor",
width: "100vw",
height: "100vw",
}
// // Monaco script
// script {
// src: "{MONACO_FOLDER}/loader.js",
// "onload": script
// }
img {
id: "some_image",
src: "{SOME_IMAGE}"
}
img {
id: "some_image_with_the_same_url",
src: "{SOME_IMAGE_WITH_THE_SAME_URL}"
}
img {
id: "some_image_without_hash",
src: "{SOME_IMAGE_WITHOUT_HASH}"
}
LoadsAsset {}
}
}
const JSON: Asset = asset!("/assets/data.json");
#[derive(Debug, Clone, serde::Deserialize)]
struct Data {
list: Vec<i32>,
}
#[component]
fn LoadsAsset() -> Element {
let data = use_resource(|| async {
let bytes = dioxus::asset_resolver::read_asset_bytes(&JSON)
.await
.unwrap();
serde_json::from_slice::<Data>(&bytes).unwrap()
});
match data() {
Some(data) => rsx! {
div {
id: "resolved-data",
"List: {data.list:?}"
}
},
None => rsx! {
div {
"Loading..."
}
},
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/cli-optimization/src/old_cli.rs | packages/playwright-tests/cli-optimization/src/old_cli.rs | fn main() {
dioxus_cli_optimization_test::main()
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/cli-optimization/src/main.rs | packages/playwright-tests/cli-optimization/src/main.rs | fn main() {
dioxus_cli_optimization_test::main()
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/web-hash-routing/src/main.rs | packages/playwright-tests/web-hash-routing/src/main.rs | use std::rc::Rc;
use dioxus::{prelude::*, web::HashHistory};
fn main() {
dioxus::LaunchBuilder::new()
.with_cfg(dioxus::web::Config::new().history(Rc::new(HashHistory::new(false))))
.launch(|| {
rsx! {
Router::<Route> {}
}
})
}
#[derive(Routable, Clone, PartialEq)]
#[rustfmt::skip]
enum Route {
#[redirect("/",|| Route::Other)]
#[route("/other")]
Other,
#[route("/other/:id")]
OtherId { id: String },
#[route("/:..segments")]
NotFound { segments: Vec<String> },
}
#[component]
fn Other() -> Element {
rsx! {
div {
id: "other",
"Other"
}
Link {
id: "other-id-link",
to: Route::OtherId { id: "123".to_string() },
"go to OtherId"
}
}
}
#[component]
fn OtherId(id: String) -> Element {
rsx! {
div {
id: "other-id",
"OtherId {id}"
}
}
}
#[component]
fn NotFound(segments: Vec<String>) -> Element {
rsx! {
div {
id: "not-found",
"NotFound {segments:?}"
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/fullstack-routing/src/main.rs | packages/playwright-tests/fullstack-routing/src/main.rs | // This test is used by playwright configured in the root of the repo
// Tests:
// - 200 Routes
// - 404 Routes
// - 500 Routes
#![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
dioxus::LaunchBuilder::new()
.with_cfg(server_only! {
dioxus::server::ServeConfig::builder().enable_out_of_order_streaming()
})
.launch(app);
}
fn app() -> Element {
rsx! { Router::<Route> {} }
}
#[derive(Clone, Routable, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
enum Route {
#[route("/")]
Home,
#[route("/blog/:id/")]
Blog { id: i32 },
#[route("/error")]
ThrowsError,
#[route("/async-error")]
ThrowsAsyncError,
#[route("/can-go-back")]
HydrateCanGoBack,
}
#[component]
fn Blog(id: i32) -> Element {
let route: Route = use_route();
assert_eq!(route, Route::Blog { id });
rsx! {
Link { to: Route::Home {}, "Go home" }
"id: {id}"
}
}
#[component]
fn ThrowsError() -> Element {
dioxus::core::bail!("This route tests uncaught errors in the server",)
}
#[component]
fn ThrowsAsyncError() -> Element {
#[server]
async fn error_after_delay() -> ServerFnResult<()> {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
Err(ServerFnError::new("Async error from a server function"))
}
use_server_future(error_after_delay)?().unwrap()?;
rsx! {
"Hello, world!"
}
}
#[component]
fn Home() -> Element {
let route: Route = use_route();
assert_eq!(route, Route::Home);
rsx! {
"Home"
Link { to: Route::Blog { id: 1 }, "Go to blog 1" }
}
}
#[component]
pub fn HydrateCanGoBack() -> Element {
let navigator = use_navigator();
let mut count = use_signal(|| 0);
rsx! {
header {
class:"flex justify-start items-center app-bg-color-primary px-5 py-2 space-x-4",
if navigator.can_go_back() {
button {
class: "app-button-circle item-navbar",
onclick: move |_| {
count += 1;
},
"{count}"
},
}
else {
div {
Link {
class: "app-button-circle item-navbar",
to: Route::Home,
"Go to home"
},
button {
class: "app-button-circle item-navbar",
onclick: move |_| {
count += 1;
},
"{count}"
},
}
}
},
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/nested-suspense/src/lib.rs | packages/playwright-tests/nested-suspense/src/lib.rs | // This test is used by playwright configured in the root of the repo
// Tests:
// - SEO without JS
// - Streaming hydration
// - Suspense
// - Server functions
//
// Without Javascript, content may not load into the right location, but it should still be somewhere in the html even if it is invisible
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
pub fn app() -> Element {
// Start streaming immediately
use_hook(dioxus::fullstack::commit_initial_chunk);
rsx! {
SuspenseBoundary {
fallback: move |_| rsx! {},
document::Style {
href: asset!("/assets/style.css")
}
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_server_future(move || server_content(0))?()
.unwrap()
.unwrap();
rsx! {
"title loaded"
document::Title { "{title.title}" }
}
}
#[component]
fn Message(id: usize) -> Element {
let message = use_server_future(move || server_content(id))?()
.unwrap()
.unwrap();
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, Serialize, Deserialize)]
pub struct Content {
title: String,
body: String,
children: Vec<usize>,
}
#[server]
async fn server_content(id: usize) -> ServerFnResult<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, 3],
},
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![4],
},
Content {
title: "Goodbye Robot".to_string(),
body: "The robot says goodbye".to_string(),
children: vec![],
},
Content {
title: "Goodbye World".to_string(),
body: "The world says goodbye".to_string(),
children: vec![],
},
Content {
title: "Hello World".to_string(),
body: "The world says hello again".to_string(),
children: vec![],
},
];
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
Ok(content_tree[id].clone())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/nested-suspense/src/main.rs | packages/playwright-tests/nested-suspense/src/main.rs | #![allow(non_snake_case)]
use dioxus::prelude::*;
use nested_suspense::app;
fn main() {
LaunchBuilder::new()
.with_cfg(server_only! {
ServeConfig::builder()
.enable_out_of_order_streaming()
})
.launch(app);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/nested-suspense/src/ssg.rs | packages/playwright-tests/nested-suspense/src/ssg.rs | #![allow(non_snake_case)]
use dioxus::prelude::*;
use nested_suspense::app;
fn main() {
dioxus::logger::init(dioxus::logger::tracing::Level::TRACE).expect("logger failed to init");
dioxus::LaunchBuilder::new()
.with_cfg(server_only! {
ServeConfig::builder()
.incremental(
dioxus::server::IncrementalRendererConfig::new()
.static_dir(
std::env::current_exe()
.unwrap()
.parent()
.unwrap()
.join("public")
)
.clear_cache(false)
)
.enable_out_of_order_streaming()
})
.launch(app);
}
#[server(endpoint = "static_routes")]
async fn static_routes() -> ServerFnResult<Vec<String>> {
Ok(vec!["/".to_string()])
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/web-hot-patch-fullstack/src/main.rs | packages/playwright-tests/web-hot-patch-fullstack/src/main.rs | use dioxus::prelude::*;
const CSS: Asset = asset!("/assets/style.css");
const IMAGE: Asset = asset!("/assets/toasts.png");
fn app() -> Element {
let mut num = use_signal(|| 0);
rsx! {
document::Link {
href: CSS,
rel: "stylesheet",
}
img {
id: "toasts",
src: IMAGE,
}
button {
id: "increment-button",
onclick: move |_| async move {
let increment_amount = get_count().await.unwrap();
*num.write() += increment_amount;
},
"Click me! Count: {num}"
}
}
}
#[post("/api/get_count")]
async fn get_count() -> Result<i32> {
Ok(1)
}
fn main() {
dioxus::launch(app);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/web/src/main.rs | packages/playwright-tests/web/src/main.rs | // This test is used by playwright configured in the root of the repo
use dioxus::prelude::*;
use wasm_bindgen::prelude::*;
fn app() -> Element {
let mut num = use_signal(|| 0);
let mut eval_result = use_signal(String::new);
rsx! {
div {
"hello axum! {num}"
document::Title { "hello axum! {num}" }
button { class: "increment-button", onclick: move |_| num += 1, "Increment" }
}
svg { circle { cx: 50, cy: 50, r: 40, stroke: "green", fill: "yellow" } }
div { class: "raw-attribute-div", "raw-attribute": "raw-attribute-value" }
div { class: "hidden-attribute-div", hidden: true }
div {
class: "dangerous-inner-html-div",
dangerous_inner_html: "<p>hello dangerous inner html</p>"
}
input { value: "hello input" }
div { class: "style-div", color: "red", "colored text" }
button {
class: "eval-button",
onclick: move |_| async move {
// Make sure normal return values work. Regression test for https://github.com/DioxusLabs/dioxus/issues/3655
let eval = document::eval(r#"return "hello world";"#);
let result = eval.await.unwrap();
assert_eq!(result, "hello world");
// Make sure dioxus.send/dioxus.recv works
let mut eval = document::eval(
r#"
window.document.title = 'Hello from Dioxus Eval!';
// Receive and multiply 10 numbers
for (let i = 0; i < 10; i++) {
let value = await dioxus.recv();
dioxus.send(value*2);
}
dioxus.send("returned eval value");
"#,
);
// Send 10 numbers
for i in 0..10 {
eval.send(i).unwrap();
let value: i32 = eval.recv().await.unwrap();
assert_eq!(value, i * 2);
}
let result = eval.recv().await;
if let Ok(serde_json::Value::String(string)) = result {
eval_result.set(string);
}
},
"Eval"
}
div { class: "eval-result", "{eval_result}" }
PreventDefault {}
OnMounted {}
WebSysClosure {}
DocumentElements {}
MergeStyles {}
SelectMultiple {}
}
}
#[component]
fn PreventDefault() -> Element {
let mut text = use_signal(|| "View source".to_string());
rsx! {
a {
class: "prevent-default",
href: "https://github.com/DioxusLabs/dioxus/tree/main/packages/playwright-tests/web",
onclick: move |evt| {
evt.prevent_default();
text.set("Psych!".to_string());
},
"{text}"
}
}
}
#[component]
fn OnMounted() -> Element {
let mut mounted_triggered_count = use_signal(|| 0);
rsx! {
div {
class: "onmounted-div",
onmounted: move |_| {
mounted_triggered_count += 1;
},
"onmounted was called {mounted_triggered_count} times"
}
}
}
// This component tests attaching an event listener to the document with a web-sys closure
// and effect
#[component]
fn WebSysClosure() -> Element {
static TRIGGERED: GlobalSignal<bool> = GlobalSignal::new(|| false);
use_effect(|| {
let window = web_sys::window().expect("window not available");
// Assert the component contents have been mounted
window
.document()
.unwrap()
.get_element_by_id("web-sys-closure-div")
.expect("Effects should only be run after all contents have bene mounted to the dom");
// Make sure passing the runtime into the closure works
let callback = Callback::new(|_| {
assert!(!dioxus::dioxus_core::Runtime::current().vdom_is_rendering());
*TRIGGERED.write() = true;
});
let closure: Closure<dyn Fn()> = Closure::new({
move || {
callback(());
}
});
window
.add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref())
.expect("Failed to add keydown event listener");
closure.forget();
});
rsx! {
div {
id: "web-sys-closure-div",
if TRIGGERED() {
"the keydown event was triggered"
}
}
}
}
/// This component tests the document::* elements
#[component]
fn DocumentElements() -> Element {
rsx! {
document::Meta { id: "meta-head", name: "testing", data: "dioxus-meta-element" }
document::Link {
id: "link-head",
rel: "stylesheet",
href: "https://fonts.googleapis.com/css?family=Roboto+Mono"
}
document::Stylesheet { id: "stylesheet-head", href: "https://fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic" }
document::Script { id: "script-head", async: true, "console.log('hello world');" }
document::Style { id: "style-head", "body {{ font-family: 'Roboto'; }}" }
// Test that links with same href but different rel are NOT deduplicated
// See https://github.com/DioxusLabs/dioxus/issues/5070
document::Link {
id: "dedup-preload",
rel: "preload",
href: "dedup-test.css",
r#as: "style",
}
document::Link {
id: "dedup-stylesheet",
rel: "stylesheet",
href: "dedup-test.css",
}
// Test that links with same href AND same rel ARE deduplicated
document::Link {
id: "dedup-first",
rel: "stylesheet",
href: "dedup-same.css",
}
document::Link {
id: "dedup-second",
rel: "stylesheet",
href: "dedup-same.css",
}
}
}
// Regression test for https://github.com/DioxusLabs/dioxus/issues/3887
#[component]
fn MergeStyles() -> Element {
let px = 100;
rsx! {
div {
id: "merge-styles-div",
style: "width: {px}px; height: {px}px",
background_color: "red",
}
}
}
// Select elements have odd default behavior when you set the multiple attribute after mounting the element
// Regression test for https://github.com/DioxusLabs/dioxus/issues/3185
#[component]
fn SelectMultiple() -> Element {
rsx! {
select {
id: "static-multiple-select",
// This is static and will be set in the template
multiple: "true",
option { label: "Value1", value: "1" }
option { label: "Value2", value: "2" }
}
select {
id: "dynamic-multiple-select",
// This is dynamic and will be set after it is mounted
multiple: true,
option { label: "Value1", value: "1" }
option { label: "Value2", value: "2" }
}
}
}
fn main() {
tracing_wasm::set_as_global_default_with_config(
tracing_wasm::WASMLayerConfigBuilder::default()
.set_max_level(tracing::Level::TRACE)
.build(),
);
dioxus::launch(app);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/playwright-tests/suspense-carousel/src/main.rs | packages/playwright-tests/suspense-carousel/src/main.rs | // This test is used by playwright configured in the root of the repo
// Tests:
// - Streaming hydration
// - Suspense
// - Server futures
#![allow(non_snake_case, unused)]
use dioxus::{fullstack::commit_initial_chunk, prelude::*};
use serde::{Deserialize, Serialize};
fn app() -> Element {
// Start streaming immediately
use_hook(commit_initial_chunk);
let mut count = use_signal(|| 0);
rsx! {
button {
id: "increment-carousel-button",
onclick: move |_| count += 1,
"Increment"
}
button {
id: "decrement-carousel-button",
onclick: move |_| count -= 1,
"Decrement"
}
div {
"Hello world"
}
div {
for i in count()..count() + 3 {
SuspenseBoundary {
key: "{i}",
fallback: |_| rsx! {
"Loading..."
},
SuspendedComponent {
id: i
}
}
}
}
div { "footer 123" }
}
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
enum ResolvedOn {
Server,
Client,
}
impl ResolvedOn {
#[cfg(feature = "web")]
const CURRENT: Self = Self::Client;
#[cfg(not(feature = "web"))]
const CURRENT: Self = Self::Server;
}
#[component]
fn SuspendedComponent(id: i32) -> Element {
let resolved_on = use_server_future(move || async move {
async_std::task::sleep(std::time::Duration::from_secs(1)).await;
ResolvedOn::CURRENT
})?()
.unwrap();
let mut count = use_signal(|| 0);
rsx! {
div {
id: "outer-{id}",
"outer suspense result: {resolved_on:?}"
button {
id: "outer-button-{id}",
onclick: move |_| count += 1,
"{count}"
}
SuspenseBoundary {
fallback: |_| rsx! {
"Loading... more"
},
NestedSuspendedComponent {
id
}
}
}
}
}
#[component]
fn NestedSuspendedComponent(id: i32) -> Element {
let resolved_on = use_server_future(move || async move {
async_std::task::sleep(std::time::Duration::from_secs(1)).await;
ResolvedOn::CURRENT
})?()
.unwrap();
let mut count = use_signal(|| 0);
rsx! {
div {
"nested suspense result: {resolved_on:?}"
button {
id: "nested-button-{id}",
onclick: move |_| count += 1,
"{count}"
}
}
}
}
fn main() {
LaunchBuilder::new()
.with_cfg(server_only! {
dioxus::server::ServeConfig::builder().enable_out_of_order_streaming()
})
.launch(app);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/build.rs | packages/web/build.rs | fn main() {
// If any TS files change, re-run the build script
lazy_js_bundle::LazyTypeScriptBindings::new()
.with_watching("./src/ts")
.with_binding("./src/ts/eval.ts", "./src/js/eval.js")
.run();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/launch.rs | packages/web/src/launch.rs | //! This module contains the `launch` function, which is the main entry point for dioxus web
pub use crate::Config;
use dioxus_core::{Element, VirtualDom};
use std::any::Any;
/// Launch the web application with the given root component, context and config
///
/// For a builder API, see `LaunchBuilder` defined in the `dioxus` crate.
pub fn launch(
root: fn() -> Element,
contexts: Vec<Box<dyn Fn() -> Box<dyn Any> + Send + Sync>>,
platform_config: Vec<Box<dyn Any>>,
) {
let mut vdom = VirtualDom::new(root);
for context in contexts {
vdom.insert_any_root_context(context());
}
let platform_config = *platform_config
.into_iter()
.find_map(|cfg| cfg.downcast::<Config>().ok())
.unwrap_or_default();
launch_virtual_dom(vdom, platform_config)
}
/// Launch the web application with a prebuild virtual dom
///
/// For a builder API, see `LaunchBuilder` defined in the `dioxus` crate.
pub fn launch_virtual_dom(vdom: VirtualDom, platform_config: Config) {
wasm_bindgen_futures::spawn_local(async move {
crate::run(vdom, platform_config).await;
});
}
/// Launch the web application with the given root component and config
pub fn launch_cfg(root: fn() -> Element, platform_config: Config) {
launch(root, Vec::new(), vec![Box::new(platform_config)])
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/lib.rs | packages/web/src/lib.rs | #![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
#![deny(missing_docs)]
//! # Dioxus Web
pub use crate::cfg::Config;
use crate::hydration::SuspenseMessage;
use dioxus_core::{ScopeId, VirtualDom};
use dom::WebsysDom;
use futures_util::{pin_mut, select, FutureExt, StreamExt};
mod cfg;
mod dom;
mod events;
pub mod launch;
mod mutations;
pub use events::*;
#[cfg(feature = "document")]
mod document;
#[cfg(feature = "document")]
mod history;
#[cfg(feature = "document")]
pub use document::WebDocument;
#[cfg(feature = "document")]
pub use history::{HashHistory, WebHistory};
mod files;
pub use files::*;
mod data_transfer;
pub use data_transfer::*;
#[cfg(all(feature = "devtools", debug_assertions))]
mod devtools;
mod hydration;
#[allow(unused)]
pub use hydration::*;
/// Runs the app as a future that can be scheduled around the main thread.
///
/// Polls futures internal to the VirtualDOM, hence the async nature of this function.
///
/// # Example
///
/// ```ignore, rust
/// let app_fut = dioxus_web::run_with_props(App, RootProps { name: String::from("foo") });
/// wasm_bindgen_futures::spawn_local(app_fut);
/// ```
pub async fn run(mut virtual_dom: VirtualDom, web_config: Config) -> ! {
#[cfg(all(feature = "devtools", debug_assertions))]
let mut hotreload_rx = devtools::init(&web_config);
#[cfg(feature = "document")]
if let Some(history) = web_config.history.clone() {
virtual_dom.in_scope(ScopeId::ROOT, || dioxus_core::provide_context(history));
}
#[cfg(feature = "document")]
virtual_dom.in_runtime(document::init_document);
let runtime = virtual_dom.runtime();
// If the hydrate feature is enabled, launch the client with hydration enabled
let should_hydrate = web_config.hydrate || cfg!(feature = "hydrate");
let mut websys_dom = WebsysDom::new(web_config, runtime);
let mut hydration_receiver: Option<futures_channel::mpsc::UnboundedReceiver<SuspenseMessage>> =
None;
if should_hydrate {
// If we are hydrating, then the hotreload message might actually have a patch for us to apply.
// Let's wait for a moment to see if we get a hotreload message before we start hydrating.
// That way, the hydration will use the same functions that the server used to serialize the data.
#[cfg(all(feature = "devtools", debug_assertions))]
loop {
let mut timeout = gloo_timers::future::TimeoutFuture::new(100).fuse();
futures_util::select! {
msg = hotreload_rx.next() => {
if let Some(msg) = msg {
if msg.for_build_id == Some(dioxus_cli_config::build_id()) {
dioxus_devtools::apply_changes(&virtual_dom, &msg);
}
}
}
_ = &mut timeout => {
break;
}
}
}
#[cfg(feature = "hydrate")]
{
use dioxus_fullstack_core::HydrationContext;
websys_dom.skip_mutations = true;
// Get the initial hydration data from the client
#[wasm_bindgen::prelude::wasm_bindgen(inline_js = r#"
export function get_initial_hydration_data() {
const decoded = atob(window.initial_dioxus_hydration_data);
return Uint8Array.from(decoded, (c) => c.charCodeAt(0))
}
export function get_initial_hydration_debug_types() {
return window.initial_dioxus_hydration_debug_types;
}
export function get_initial_hydration_debug_locations() {
return window.initial_dioxus_hydration_debug_locations;
}
"#)]
extern "C" {
fn get_initial_hydration_data() -> js_sys::Uint8Array;
fn get_initial_hydration_debug_types() -> Option<Vec<String>>;
fn get_initial_hydration_debug_locations() -> Option<Vec<String>>;
}
let hydration_data = get_initial_hydration_data().to_vec();
// If we are running in debug mode, also get the debug types and locations
#[cfg(debug_assertions)]
let debug_types = get_initial_hydration_debug_types();
#[cfg(not(debug_assertions))]
let debug_types = None;
#[cfg(debug_assertions)]
let debug_locations = get_initial_hydration_debug_locations();
#[cfg(not(debug_assertions))]
let debug_locations = None;
let server_data =
HydrationContext::from_serialized(&hydration_data, debug_types, debug_locations);
// If the server serialized an error into the root suspense boundary, throw it into the root scope
if let Some(error) = server_data.error_entry().get().ok().flatten() {
virtual_dom.in_runtime(|| virtual_dom.runtime().throw_error(ScopeId::APP, error));
}
server_data.in_context(|| {
virtual_dom.in_scope(ScopeId::ROOT, || {
// Provide a hydration compatible create error boundary method
dioxus_core::provide_create_error_boundary(
dioxus_fullstack_core::init_error_boundary,
);
#[cfg(feature = "document")]
document::init_fullstack_document();
});
virtual_dom.rebuild(&mut websys_dom);
});
websys_dom.skip_mutations = false;
let rx = websys_dom.rehydrate(&virtual_dom).unwrap();
hydration_receiver = Some(rx);
#[cfg(feature = "mounted")]
{
// Flush any mounted events that were queued up while hydrating
websys_dom.flush_queued_mounted_events();
}
}
#[cfg(not(feature = "hydrate"))]
{
panic!("Hydration is not enabled. Please enable the `hydrate` feature.");
}
} else {
virtual_dom.rebuild(&mut websys_dom);
websys_dom.flush_edits();
}
loop {
// if virtual dom has nothing, wait for it to have something before requesting idle time
// if there is work then this future resolves immediately.
#[cfg(all(feature = "devtools", debug_assertions))]
let template;
#[allow(unused)]
let mut hydration_work: Option<SuspenseMessage> = None;
{
let work = virtual_dom.wait_for_work().fuse();
pin_mut!(work);
let mut hydration_receiver_iter = futures_util::stream::iter(&mut hydration_receiver)
.fuse()
.flatten();
let mut rx_hydration = hydration_receiver_iter.select_next_some();
#[cfg(all(feature = "devtools", debug_assertions))]
#[allow(unused)]
{
let mut devtools_next = hotreload_rx.select_next_some();
select! {
_ = work => {
template = None;
},
new_template = devtools_next => {
template = Some(new_template);
},
hydration_data = rx_hydration => {
template = None;
#[cfg(feature = "hydrate")]
{
hydration_work = Some(hydration_data);
}
},
}
}
#[cfg(not(all(feature = "devtools", debug_assertions)))]
#[allow(unused)]
{
select! {
_ = work => {},
hyd = rx_hydration => {
#[cfg(feature = "hydrate")]
{
hydration_work = Some(hyd);
}
}
}
}
}
#[cfg(all(feature = "devtools", debug_assertions))]
if let Some(hr_msg) = template {
// Replace all templates
dioxus_devtools::apply_changes(&virtual_dom, &hr_msg);
if !hr_msg.assets.is_empty() {
crate::devtools::invalidate_browser_asset_cache();
}
if hr_msg.for_build_id == Some(dioxus_cli_config::build_id()) {
devtools::show_toast(
"Hot-patch success!",
&format!("App successfully patched in {} ms", hr_msg.ms_elapsed),
devtools::ToastLevel::Success,
std::time::Duration::from_millis(2000),
false,
);
}
}
#[cfg(feature = "hydrate")]
if let Some(hydration_data) = hydration_work {
websys_dom.rehydrate_streaming(hydration_data, &mut virtual_dom);
}
// Todo: This is currently disabled because it has a negative impact on response times for events but it could be re-enabled for tasks
// Jank free rendering
//
// 1. wait for the browser to give us "idle" time
// 2. During idle time, diff the dom
// 3. Stop diffing if the deadline is exceeded
// 4. Wait for the animation frame to patch the dom
// wait for the mainthread to schedule us in
// let deadline = work_loop.wait_for_idle_time().await;
// run the virtualdom work phase until the frame deadline is reached
virtual_dom.render_immediate(&mut websys_dom);
// wait for the animation frame to fire so we can apply our changes
// work_loop.wait_for_raf().await;
websys_dom.flush_edits();
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/document.rs | packages/web/src/document.rs | use dioxus_core::queue_effect;
use dioxus_core::ScopeId;
use dioxus_core::{provide_context, Runtime};
use dioxus_document::{
Document, Eval, EvalError, Evaluator, LinkProps, MetaProps, ScriptProps, StyleProps,
};
use dioxus_history::History;
use futures_util::FutureExt;
use generational_box::{AnyStorage, GenerationalBox, UnsyncStorage};
use js_sys::Function;
use serde::Serialize;
use serde_json::Value;
use std::future::Future;
use std::pin::Pin;
use std::result;
use std::{rc::Rc, str::FromStr};
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use crate::history::WebHistory;
#[wasm_bindgen::prelude::wasm_bindgen]
pub struct JSOwner {
_owner: Box<dyn std::any::Any>,
}
impl JSOwner {
pub fn new(owner: impl std::any::Any) -> Self {
Self {
_owner: Box::new(owner),
}
}
}
#[wasm_bindgen::prelude::wasm_bindgen(module = "/src/js/eval.js")]
extern "C" {
pub type WeakDioxusChannel;
#[wasm_bindgen(method, js_name = "rustSend")]
pub fn rust_send(this: &WeakDioxusChannel, value: wasm_bindgen::JsValue);
#[wasm_bindgen(method, js_name = "rustRecv")]
pub async fn rust_recv(this: &WeakDioxusChannel) -> wasm_bindgen::JsValue;
}
#[wasm_bindgen::prelude::wasm_bindgen(module = "/src/js/eval.js")]
extern "C" {
pub type WebDioxusChannel;
#[wasm_bindgen(constructor)]
pub fn new(owner: JSOwner) -> WebDioxusChannel;
#[wasm_bindgen(method, js_name = "rustSend")]
pub fn rust_send(this: &WebDioxusChannel, value: wasm_bindgen::JsValue);
#[wasm_bindgen(method, js_name = "rustRecv")]
pub async fn rust_recv(this: &WebDioxusChannel) -> wasm_bindgen::JsValue;
#[wasm_bindgen(method)]
pub fn send(this: &WebDioxusChannel, value: wasm_bindgen::JsValue);
#[wasm_bindgen(method)]
pub async fn recv(this: &WebDioxusChannel) -> wasm_bindgen::JsValue;
#[wasm_bindgen(method)]
pub fn weak(this: &WebDioxusChannel) -> WeakDioxusChannel;
}
fn init_document_with(document: impl FnOnce(), history: impl FnOnce()) {
use dioxus_core::has_context;
Runtime::current().in_scope(ScopeId::ROOT, || {
if has_context::<Rc<dyn Document>>().is_none() {
document();
}
if has_context::<Rc<dyn History>>().is_none() {
history();
}
})
}
/// Provides the Document through [`dioxus_core::provide_context`].
pub fn init_document() {
// If hydrate is enabled, we add the FullstackWebDocument with the initial hydration data
#[cfg(not(feature = "hydrate"))]
{
use dioxus_history::provide_history_context;
init_document_with(
|| {
provide_context(Rc::new(WebDocument) as Rc<dyn Document>);
},
|| {
provide_history_context(Rc::new(WebHistory::default()));
},
);
}
}
#[cfg(feature = "hydrate")]
pub fn init_fullstack_document() {
use dioxus_fullstack_core::{
document::FullstackWebDocument, history::provide_fullstack_history_context,
};
init_document_with(
|| {
provide_context(Rc::new(FullstackWebDocument::from(WebDocument)) as Rc<dyn Document>);
},
|| provide_fullstack_history_context(WebHistory::default()),
);
}
/// The web-target's document provider.
#[derive(Clone)]
pub struct WebDocument;
impl Document for WebDocument {
fn eval(&self, js: String) -> Eval {
Eval::new(WebEvaluator::create(js))
}
/// Set the title of the document
fn set_title(&self, title: String) {
let myself = self.clone();
queue_effect(move || {
myself.eval(format!("document.title = {title:?};"));
});
}
/// Create a new meta tag in the head
fn create_meta(&self, props: MetaProps) {
queue_effect(move || {
_ = append_element_to_head("meta", &props.attributes(), None);
});
}
/// Create a new script tag in the head
fn create_script(&self, props: ScriptProps) {
queue_effect(move || {
_ = append_element_to_head(
"script",
&props.attributes(),
props.script_contents().ok().as_deref(),
);
});
}
/// Create a new style tag in the head
fn create_style(&self, props: StyleProps) {
queue_effect(move || {
_ = append_element_to_head(
"style",
&props.attributes(),
props.style_contents().ok().as_deref(),
);
});
}
/// Create a new link tag in the head
fn create_link(&self, props: LinkProps) {
queue_effect(move || {
_ = append_element_to_head("link", &props.attributes(), None);
});
}
}
fn append_element_to_head(
local_name: &str,
attributes: &Vec<(&'static str, String)>,
text_content: Option<&str>,
) -> Result<(), JsValue> {
let window = web_sys::window().expect("no global `window` exists");
let document = window.document().expect("should have a document on window");
let head = document.head().expect("document should have a head");
let element = document.create_element(local_name)?;
for (name, value) in attributes {
element.set_attribute(name, value)?;
}
if text_content.is_some() {
element.set_text_content(text_content);
}
head.append_child(&element)?;
Ok(())
}
/// Required to avoid blocking the Rust WASM thread.
const PROMISE_WRAPPER: &str = r#"
return (async function(){
{JS_CODE}
dioxus.close();
})();
"#;
type NextPoll = Pin<Box<dyn Future<Output = Result<serde_json::Value, EvalError>>>>;
/// Represents a web-target's JavaScript evaluator.
struct WebEvaluator {
channels: WeakDioxusChannel,
next_future: Option<NextPoll>,
result: Pin<Box<dyn Future<Output = result::Result<Value, EvalError>>>>,
}
impl WebEvaluator {
/// Creates a new evaluator for web-based targets.
fn create(js: String) -> GenerationalBox<Box<dyn Evaluator>> {
let owner = UnsyncStorage::owner();
// add the drop handler to DioxusChannel so that it gets dropped when the channel is dropped in js
let channels = WebDioxusChannel::new(JSOwner::new(owner.clone()));
// The Rust side of the channel is a weak reference to the DioxusChannel
let weak_channels = channels.weak();
// Wrap the evaluated JS in a promise so that wasm can continue running (send/receive data from js)
let code = PROMISE_WRAPPER.replace("{JS_CODE}", &js);
let result = match Function::new_with_args("dioxus", &code).call1(&JsValue::NULL, &channels)
{
Ok(result) => {
let future = js_sys::Promise::resolve(&result);
let js_future = JsFuture::from(future);
Box::pin(async move {
let result = js_future.await.map_err(|e| {
EvalError::Communication(format!("Failed to await result - {:?}", e))
})?;
let stringified = js_sys::JSON::stringify(&result).map_err(|e| {
EvalError::Communication(format!("Failed to stringify result - {:?}", e))
})?;
if !stringified.is_undefined() && stringified.is_valid_utf16() {
let string: String = stringified.into();
Value::from_str(&string).map_err(|e| {
EvalError::Communication(format!("Failed to parse result - {}", e))
})
} else {
Err(EvalError::Communication(
"Failed to stringify result - undefined or not valid utf16".to_string(),
))
}
})
as Pin<Box<dyn Future<Output = result::Result<Value, EvalError>>>>
}
Err(err) => Box::pin(futures_util::future::ready(Err(EvalError::InvalidJs(
err.as_string().unwrap_or("unknown".to_string()),
)))),
};
owner.insert(Box::new(Self {
channels: weak_channels,
result,
next_future: None,
}) as Box<dyn Evaluator>)
}
}
impl Evaluator for WebEvaluator {
/// Runs the evaluated JavaScript.
fn poll_join(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
self.result.poll_unpin(cx)
}
/// Sends a message to the evaluated JavaScript.
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
let serializer = serde_wasm_bindgen::Serializer::json_compatible();
let data = match data.serialize(&serializer) {
Ok(d) => d,
Err(e) => return Err(EvalError::Communication(e.to_string())),
};
self.channels.rust_send(data);
Ok(())
}
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
fn poll_recv(
&mut self,
context: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
if self.next_future.is_none() {
let channels: WebDioxusChannel = self.channels.clone().into();
let pinned = Box::pin(async move {
let fut = channels.rust_recv();
let data = fut.await;
serde_wasm_bindgen::from_value::<serde_json::Value>(data)
.map_err(|err| EvalError::Communication(err.to_string()))
});
self.next_future = Some(pinned);
}
let fut = self.next_future.as_mut().unwrap();
let mut pinned = std::pin::pin!(fut);
let result = pinned.as_mut().poll(context);
if result.is_ready() {
self.next_future = None;
}
result
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/devtools.rs | packages/web/src/devtools.rs | //! Handler code for hotreloading.
//!
//! This sets up a websocket connection to the devserver and handles messages from it.
//! We also set up a little recursive timer that will attempt to reconnect if the connection is lost.
use dioxus_devtools::{DevserverMsg, HotReloadMsg};
use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use js_sys::JsString;
use std::fmt::Display;
use std::time::Duration;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen::{closure::Closure, JsValue};
use web_sys::{window, CloseEvent, MessageEvent, WebSocket};
const POLL_INTERVAL_MIN: i32 = 250;
const POLL_INTERVAL_MAX: i32 = 4000;
const POLL_INTERVAL_SCALE_FACTOR: i32 = 2;
/// Amount of time that toats should be displayed.
const TOAST_TIMEOUT: Duration = Duration::from_secs(5);
const TOAST_TIMEOUT_LONG: Duration = Duration::from_secs(3600); // Duration::MAX is too long for JS.
pub(crate) fn init(config: &crate::Config) -> UnboundedReceiver<HotReloadMsg> {
// Create the tx/rx pair that we'll use for the top-level future in the dioxus loop
let (tx, rx) = unbounded();
// Wire up the websocket to the devserver
make_ws(tx.clone(), POLL_INTERVAL_MIN, false);
// Set up the playground
playground(tx);
// Set up the panic hook
if config.panic_hook {
std::panic::set_hook(Box::new(|info| {
hook_impl(info);
}));
}
rx
}
fn make_ws(tx: UnboundedSender<HotReloadMsg>, poll_interval: i32, reload: bool) {
// Get the location of the devserver, using the current location plus the /_dioxus path
// The idea here being that the devserver is always located on the /_dioxus behind a proxy
let location = web_sys::window().unwrap().location();
let url = format!(
"{protocol}//{host}/_dioxus?build_id={build_id}",
protocol = match location.protocol().unwrap() {
prot if prot == "https:" => "wss:",
_ => "ws:",
},
host = location.host().unwrap(),
build_id = dioxus_cli_config::build_id(),
);
let ws = WebSocket::new(&url).unwrap();
// Set the onmessage handler to bounce messages off to the main dioxus loop
let tx_ = tx.clone();
ws.set_onmessage(Some(
Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
let Ok(text) = e.data().dyn_into::<JsString>() else {
return;
};
// The devserver messages have some &'static strs in them, so we need to leak the source string
let string: String = text.into();
let string = Box::leak(string.into_boxed_str());
match serde_json::from_str::<DevserverMsg>(string) {
Ok(DevserverMsg::HotReload(hr)) => _ = tx_.unbounded_send(hr),
// todo: we want to throw a screen here that shows the user that the devserver has disconnected
// Would be nice to do that with dioxus itself or some html/css
// But if the dev server shutsdown we don't want to be super aggressive about it... let's
// play with other devservers to see how they handle this
Ok(DevserverMsg::Shutdown) => {
web_sys::console::error_1(&"Connection to the devserver was closed".into())
}
// The devserver is telling us that it started a full rebuild. This does not mean that it is ready.
Ok(DevserverMsg::FullReloadStart) => show_toast(
"Your app is being rebuilt.",
"A non-hot-reloadable change occurred and we must rebuild.",
ToastLevel::Info,
TOAST_TIMEOUT_LONG,
false,
),
// The devserver is telling us that it started a full rebuild. This does not mean that it is ready.
Ok(DevserverMsg::HotPatchStart) => show_toast(
"Hot-patching app...",
"Hot-patching modified Rust code.",
ToastLevel::Info,
TOAST_TIMEOUT_LONG,
false,
),
// The devserver is telling us that the full rebuild failed.
Ok(DevserverMsg::FullReloadFailed) => show_toast(
"Oops! The build failed.",
"We tried to rebuild your app, but something went wrong.",
ToastLevel::Error,
TOAST_TIMEOUT_LONG,
false,
),
// The devserver is telling us to reload the whole page
Ok(DevserverMsg::FullReloadCommand) => {
show_toast(
"Successfully rebuilt.",
"Your app was rebuilt successfully and without error.",
ToastLevel::Success,
TOAST_TIMEOUT,
true,
);
window().unwrap().location().reload().unwrap()
}
Err(e) => web_sys::console::error_1(
&format!("Error parsing devserver message: {}", e).into(),
),
e => {
web_sys::console::error_1(
&format!("Error parsing devserver message: {:?}", e).into(),
);
}
}
})
.into_js_value()
.as_ref()
.unchecked_ref(),
));
// Set the onclose handler to reload the page if the connection is closed
ws.set_onclose(Some(
Closure::<dyn FnMut(CloseEvent)>::new(move |e: CloseEvent| {
// Firefox will send a 1001 code when the connection is closed because the page is reloaded
// Only firefox will trigger the onclose event when the page is reloaded manually: https://stackoverflow.com/questions/10965720/should-websocket-onclose-be-triggered-by-user-navigation-or-refresh
// We should not reload the page in this case
if e.code() == 1001 {
return;
}
// set timeout to reload the page in timeout_ms
let tx = tx.clone();
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(
Closure::<dyn FnMut()>::new(move || {
make_ws(
tx.clone(),
POLL_INTERVAL_MAX.min(poll_interval * POLL_INTERVAL_SCALE_FACTOR),
true,
);
})
.into_js_value()
.as_ref()
.unchecked_ref(),
poll_interval,
)
.unwrap();
})
.into_js_value()
.as_ref()
.unchecked_ref(),
));
// Set the onopen handler to reload the page if the connection is closed
ws.set_onopen(Some(
Closure::<dyn FnMut(MessageEvent)>::new(move |_evt| {
if reload {
window().unwrap().location().reload().unwrap();
}
})
.into_js_value()
.as_ref()
.unchecked_ref(),
));
// monkey patch our console.log / console.error to send the logs to the websocket
// this will let us see the logs in the devserver!
// We only do this if we're not reloading the page, since that will cause duplicate monkey patches
if !reload {
// the method we need to patch:
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
// log, info, warn, error, debug
let ws: &JsValue = ws.as_ref();
dioxus_interpreter_js::minimal_bindings::monkeyPatchConsole(ws.clone());
}
}
/// Represents what color the toast should have.
pub(crate) enum ToastLevel {
/// Green
Success,
/// Blue
Info,
/// Red
Error,
}
impl Display for ToastLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ToastLevel::Success => write!(f, "success"),
ToastLevel::Info => write!(f, "info"),
ToastLevel::Error => write!(f, "error"),
}
}
}
/// Displays a toast to the developer.
pub(crate) fn show_toast(
header_text: &str,
message: &str,
level: ToastLevel,
duration: Duration,
after_reload: bool,
) {
let as_ms = duration.as_millis();
let js_fn_name = match after_reload {
true => "scheduleDXToast",
false => "showDXToast",
};
_ = js_sys::eval(&format!(
r#"
if (typeof {js_fn_name} !== "undefined") {{
window.{js_fn_name}(`{header_text}`, `{message}`, `{level}`, {as_ms});
}}
"#,
));
}
/// Force a hotreload of the assets on this page by walking them and changing their URLs to include
/// some extra entropy.
///
/// This should... mostly work.
pub(crate) fn invalidate_browser_asset_cache() {
// it might be triggering a reload of assets
// invalidate all the stylesheets on the page
let links = web_sys::window()
.unwrap()
.document()
.unwrap()
.query_selector_all("link[rel=stylesheet]")
.unwrap();
let noise = js_sys::Math::random();
for x in 0..links.length() {
use wasm_bindgen::JsCast;
let link: web_sys::Element = links.get(x).unwrap().unchecked_into();
if let Some(href) = link.get_attribute("href") {
let (url, query) = href.split_once('?').unwrap_or((&href, ""));
let mut query_params: Vec<&str> = query.split('&').collect();
// Remove the old force reload param
query_params.retain(|param| !param.starts_with("dx_force_reload="));
// Add the new force reload param
let force_reload = format!("dx_force_reload={noise}");
query_params.push(&force_reload);
// Rejoin the query
let query = query_params.join("&");
_ = link.set_attribute("href", &format!("{url}?{query}"));
}
}
}
/// Initialize required devtools for dioxus-playground.
///
/// This listens for window message events from other Windows (such as window.top when this is running in an iframe).
fn playground(tx: UnboundedSender<HotReloadMsg>) {
let window = web_sys::window().expect("this code should be running in a web context");
let binding = Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
let Ok(text) = e.data().dyn_into::<JsString>() else {
return;
};
let string: String = text.into();
let Ok(hr_msg) = serde_json::from_str::<HotReloadMsg>(&string) else {
return;
};
_ = tx.unbounded_send(hr_msg);
});
let callback = binding.as_ref().unchecked_ref();
window
.add_event_listener_with_callback("message", callback)
.expect("event listener should be added successfully");
binding.forget();
}
fn hook_impl(info: &std::panic::PanicHookInfo) {
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn error(msg: String);
type Error;
#[wasm_bindgen(constructor)]
fn new() -> Error;
#[wasm_bindgen(structural, method, getter)]
fn stack(error: &Error) -> String;
}
let mut msg = info.to_string();
// Add the error stack to our message.
//
// This ensures that even if the `console` implementation doesn't
// include stacks for `console.error`, the stack is still available
// for the user. Additionally, Firefox's console tries to clean up
// stack traces, and ruins Rust symbols in the process
// (https://bugzilla.mozilla.org/show_bug.cgi?id=1519569) but since
// it only touches the logged message's associated stack, and not
// the message's contents, by including the stack in the message
// contents we make sure it is available to the user.
msg.push_str("\n\nStack:\n\n");
let e = Error::new();
let stack = e.stack();
msg.push_str(&stack);
// Safari's devtools, on the other hand, _do_ mess with logged
// messages' contents, so we attempt to break their heuristics for
// doing that by appending some whitespace.
// https://github.com/rustwasm/console_error_panic_hook/issues/7
msg.push_str("\n\n");
// Log the panic with `console.error`!
error(msg.clone());
show_toast(
"App panicked! See console for details.",
&msg,
ToastLevel::Error,
TOAST_TIMEOUT_LONG,
false,
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/mutations.rs | packages/web/src/mutations.rs | use crate::dom::WebsysDom;
use dioxus_core::{
AttributeValue, ElementId, Template, TemplateAttribute, TemplateNode, WriteMutations,
};
use dioxus_core_types::event_bubbles;
use dioxus_interpreter_js::minimal_bindings;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
impl WebsysDom {
pub(crate) fn create_template_node(&self, v: &TemplateNode) -> web_sys::Node {
use TemplateNode::*;
match v {
Element {
tag,
namespace,
attrs,
children,
..
} => {
let el = match namespace {
Some(ns) => self.document.create_element_ns(Some(ns), tag).unwrap(),
None => self.document.create_element(tag).unwrap(),
};
for attr in *attrs {
if let TemplateAttribute::Static {
name,
value,
namespace,
} = attr
{
minimal_bindings::setAttributeInner(
el.clone().into(),
name,
JsValue::from_str(value),
*namespace,
);
}
}
for child in *children {
let _ = el.append_child(&self.create_template_node(child));
}
el.dyn_into().unwrap()
}
Text { text } => self.document.create_text_node(text).dyn_into().unwrap(),
Dynamic { .. } => {
let placeholder = self.document.create_comment("placeholder");
placeholder.dyn_into().unwrap()
}
}
}
pub fn flush_edits(&mut self) {
self.interpreter.flush();
// Now that we've flushed the edits and the dom nodes exist, we can send the mounted events.
#[cfg(feature = "mounted")]
self.flush_queued_mounted_events();
}
#[cfg(feature = "mounted")]
pub(crate) fn flush_queued_mounted_events(&mut self) {
for id in self.queued_mounted_events.drain(..) {
let node = self.interpreter.base().get_node(id.0 as u32);
if let Some(element) = node.dyn_ref::<web_sys::Element>() {
let event = dioxus_core::Event::new(
std::rc::Rc::new(dioxus_html::PlatformEventData::new(Box::new(
element.clone(),
))) as std::rc::Rc<dyn std::any::Any>,
false,
);
let name = "mounted";
self.runtime.handle_event(name, event, id)
}
}
}
#[cfg(feature = "mounted")]
pub(crate) fn send_mount_event(&mut self, id: ElementId) {
self.queued_mounted_events.push(id);
}
#[inline]
fn skip_mutations(&self) -> bool {
#[cfg(feature = "hydrate")]
{
self.skip_mutations
}
#[cfg(not(feature = "hydrate"))]
{
false
}
}
}
impl WriteMutations for WebsysDom {
fn append_children(&mut self, id: ElementId, m: usize) {
if self.skip_mutations() {
return;
}
self.interpreter.append_children(id.0 as u32, m as u16)
}
fn assign_node_id(&mut self, path: &'static [u8], id: ElementId) {
if self.skip_mutations() {
return;
}
self.interpreter
.assign_id(path.as_ptr() as u32, path.len() as u8, id.0 as u32)
}
fn create_placeholder(&mut self, id: ElementId) {
if self.skip_mutations() {
return;
}
self.interpreter.create_placeholder(id.0 as u32)
}
fn create_text_node(&mut self, value: &str, id: ElementId) {
if self.skip_mutations() {
return;
}
self.interpreter.create_text_node(value, id.0 as u32)
}
fn load_template(&mut self, template: Template, index: usize, id: ElementId) {
if self.skip_mutations() {
return;
}
let tmpl_id = self.templates.get(&template).cloned().unwrap_or_else(|| {
let mut roots = vec![];
for root in template.roots {
roots.push(self.create_template_node(root))
}
let id = self.templates.len() as u16;
self.templates.insert(template, id);
self.interpreter.base().save_template(roots, id);
id
});
self.interpreter
.load_template(tmpl_id, index as u16, id.0 as u32)
}
fn replace_node_with(&mut self, id: ElementId, m: usize) {
if self.skip_mutations() {
return;
}
self.interpreter.replace_with(id.0 as u32, m as u16)
}
fn replace_placeholder_with_nodes(&mut self, path: &'static [u8], m: usize) {
if self.skip_mutations() {
return;
}
self.interpreter
.replace_placeholder(path.as_ptr() as u32, path.len() as u8, m as u16)
}
fn insert_nodes_after(&mut self, id: ElementId, m: usize) {
if self.skip_mutations() {
return;
}
self.interpreter.insert_after(id.0 as u32, m as u16)
}
fn insert_nodes_before(&mut self, id: ElementId, m: usize) {
if self.skip_mutations() {
return;
}
self.interpreter.insert_before(id.0 as u32, m as u16)
}
fn set_attribute(
&mut self,
name: &'static str,
ns: Option<&'static str>,
value: &AttributeValue,
id: ElementId,
) {
if self.skip_mutations() {
return;
}
match value {
AttributeValue::Text(txt) => {
self.interpreter
.set_attribute(id.0 as u32, name, txt, ns.unwrap_or_default())
}
AttributeValue::Float(f) => self.interpreter.set_attribute(
id.0 as u32,
name,
&f.to_string(),
ns.unwrap_or_default(),
),
AttributeValue::Int(n) => self.interpreter.set_attribute(
id.0 as u32,
name,
&n.to_string(),
ns.unwrap_or_default(),
),
AttributeValue::Bool(b) => self.interpreter.set_attribute(
id.0 as u32,
name,
if *b { "true" } else { "false" },
ns.unwrap_or_default(),
),
AttributeValue::None => {
self.interpreter
.remove_attribute(id.0 as u32, name, ns.unwrap_or_default())
}
_ => unreachable!(),
}
}
fn set_node_text(&mut self, value: &str, id: ElementId) {
if self.skip_mutations() {
return;
}
self.interpreter.set_text(id.0 as u32, value)
}
fn create_event_listener(&mut self, name: &'static str, id: ElementId) {
if self.skip_mutations() {
return;
}
// mounted events are fired immediately after the element is mounted.
if name == "mounted" {
#[cfg(feature = "mounted")]
self.send_mount_event(id);
return;
}
self.interpreter
.new_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
}
fn remove_event_listener(&mut self, name: &'static str, id: ElementId) {
if self.skip_mutations() {
return;
}
if name == "mounted" {
return;
}
self.interpreter
.remove_event_listener(name, id.0 as u32, event_bubbles(name) as u8);
}
fn remove_node(&mut self, id: ElementId) {
if self.skip_mutations() {
return;
}
self.interpreter.remove(id.0 as u32)
}
fn push_root(&mut self, id: ElementId) {
if self.skip_mutations() {
return;
}
self.interpreter.push_root(id.0 as u32)
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/history.rs | packages/web/src/history.rs | use wasm_bindgen::{prelude::Closure, JsCast, JsValue};
use web_sys::{window, Event, History, ScrollRestoration, Window};
/// A [`dioxus_history::History`] provider that integrates with a browser via the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API).
///
/// # Prefix
/// This [`dioxus_history::History`] supports a prefix, which can be used for web apps that aren't located
/// at the root of their domain.
///
/// Application developers are responsible for ensuring that right after the prefix comes a `/`. If
/// that is not the case, this [`dioxus_history::History`] will replace the first character after the prefix
/// with one.
///
/// Application developers are responsible for not rendering the router if the prefix is not present
/// in the URL. Otherwise, if a router navigation is triggered, the prefix will be added.
pub struct WebHistory {
do_scroll_restoration: bool,
history: History,
prefix: Option<String>,
window: Window,
}
impl Default for WebHistory {
fn default() -> Self {
Self::new(None, true)
}
}
impl WebHistory {
/// Create a new [`WebHistory`].
///
/// If `do_scroll_restoration` is [`true`], [`WebHistory`] will take control of the history
/// state. It'll also set the browsers scroll restoration to `manual`.
pub fn new(prefix: Option<String>, do_scroll_restoration: bool) -> Self {
let myself = Self::new_inner(prefix, do_scroll_restoration);
let current_route = dioxus_history::History::current_route(&myself);
let current_route_str = current_route.to_string();
let prefix_str = myself.prefix.as_deref().unwrap_or("");
let current_url = format!("{prefix_str}{current_route_str}");
let state = myself.create_state();
let _ = replace_state_with_url(&myself.history, &state, Some(¤t_url));
myself
}
fn new_inner(prefix: Option<String>, do_scroll_restoration: bool) -> Self {
let window = window().expect("access to `window`");
let history = window.history().expect("`window` has access to `history`");
if do_scroll_restoration {
history
.set_scroll_restoration(ScrollRestoration::Manual)
.expect("`history` can set scroll restoration");
}
let prefix = prefix
// If there isn't a base path, try to grab one from the CLI
.or_else(dioxus_cli_config::web_base_path)
// Normalize the prefix to start and end with no slashes
.as_ref()
.map(|prefix| prefix.trim_matches('/'))
// If the prefix is empty, don't add it
.filter(|prefix| !prefix.is_empty())
// Otherwise, start with a slash
.map(|prefix| format!("/{prefix}"));
Self {
do_scroll_restoration,
history,
prefix,
window,
}
}
fn scroll_pos(&self) -> ScrollPosition {
if self.do_scroll_restoration {
ScrollPosition::of_window(&self.window)
} else {
Default::default()
}
}
fn create_state(&self) -> [f64; 2] {
let scroll = self.scroll_pos();
[scroll.x, scroll.y]
}
fn handle_nav(&self) {
if self.do_scroll_restoration {
self.window.scroll_to_with_x_and_y(0.0, 0.0)
}
}
fn route_from_location(&self) -> String {
let location = self.window.location();
let path = location.pathname().unwrap_or_else(|_| "/".into())
+ &location.search().unwrap_or("".into())
+ &location.hash().unwrap_or("".into());
let mut path = match self.prefix {
None => &path,
Some(ref prefix) => path.strip_prefix(prefix).unwrap_or(prefix),
};
// If the path is empty, parse the root route instead
if path.is_empty() {
path = "/"
}
path.to_string()
}
fn full_path(&self, state: &String) -> String {
match &self.prefix {
None => state.to_string(),
Some(prefix) => format!("{prefix}{state}"),
}
}
}
impl dioxus_history::History for WebHistory {
fn current_route(&self) -> String {
self.route_from_location()
}
fn current_prefix(&self) -> Option<String> {
self.prefix.clone()
}
fn go_back(&self) {
let _ = self.history.back();
}
fn go_forward(&self) {
let _ = self.history.forward();
}
fn push(&self, state: String) {
if state == self.current_route() {
// don't push the same state twice
return;
}
let w = window().expect("access to `window`");
let h = w.history().expect("`window` has access to `history`");
// update the scroll position before pushing the new state
update_scroll(&w, &h);
if push_state_and_url(&self.history, &self.create_state(), self.full_path(&state)).is_ok() {
self.handle_nav();
}
}
fn replace(&self, state: String) {
if replace_state_with_url(
&self.history,
&self.create_state(),
Some(&self.full_path(&state)),
)
.is_ok()
{
self.handle_nav();
}
}
fn external(&self, url: String) -> bool {
self.window.location().set_href(&url).is_ok()
}
fn updater(&self, callback: std::sync::Arc<dyn Fn() + Send + Sync>) {
let w = self.window.clone();
let h = self.history.clone();
let d = self.do_scroll_restoration;
let function = Closure::wrap(Box::new(move |_| {
(*callback)();
if d {
if let Some([x, y]) = get_current(&h) {
ScrollPosition { x, y }.scroll_to(w.clone())
}
}
}) as Box<dyn FnMut(Event)>);
self.window
.add_event_listener_with_callback(
"popstate",
&function.into_js_value().unchecked_into(),
)
.unwrap();
}
}
/// A [`dioxus_history::History`] provider that integrates with a browser via the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API)
/// but uses the url fragment for the route. This allows serving as a single html file or on a single url path.
pub struct HashHistory {
do_scroll_restoration: bool,
history: History,
pathname: String,
window: Window,
}
impl Default for HashHistory {
fn default() -> Self {
Self::new(true)
}
}
impl HashHistory {
/// Create a new [`HashHistory`].
///
/// If `do_scroll_restoration` is [`true`], [`HashHistory`] will take control of the history
/// state. It'll also set the browsers scroll restoration to `manual`.
pub fn new(do_scroll_restoration: bool) -> Self {
let myself = Self::new_inner(do_scroll_restoration);
let current_route = dioxus_history::History::current_route(&myself);
let current_route_str = current_route.to_string();
let pathname_str = &myself.pathname;
let current_url = format!("{pathname_str}#{current_route_str}");
let state = myself.create_state();
let _ = replace_state_with_url(&myself.history, &state, Some(¤t_url));
myself
}
fn new_inner(do_scroll_restoration: bool) -> Self {
let window = window().expect("access to `window`");
let history = window.history().expect("`window` has access to `history`");
let pathname = window.location().pathname().unwrap();
if do_scroll_restoration {
history
.set_scroll_restoration(ScrollRestoration::Manual)
.expect("`history` can set scroll restoration");
}
Self {
do_scroll_restoration,
history,
pathname,
window,
}
}
fn scroll_pos(&self) -> ScrollPosition {
if self.do_scroll_restoration {
ScrollPosition::of_window(&self.window)
} else {
Default::default()
}
}
fn create_state(&self) -> [f64; 2] {
let scroll = self.scroll_pos();
[scroll.x, scroll.y]
}
fn full_path(&self, state: &String) -> String {
format!("{}#{state}", self.pathname)
}
fn handle_nav(&self) {
if self.do_scroll_restoration {
self.window.scroll_to_with_x_and_y(0.0, 0.0)
}
}
}
impl dioxus_history::History for HashHistory {
fn current_route(&self) -> String {
let location = self.window.location();
let hash = location.hash().unwrap();
if hash.is_empty() {
// If the path is empty, parse the root route instead
"/".to_owned()
} else {
hash.trim_start_matches("#").to_owned()
}
}
fn current_prefix(&self) -> Option<String> {
Some(format!("{}#", self.pathname))
}
fn go_back(&self) {
let _ = self.history.back();
}
fn go_forward(&self) {
let _ = self.history.forward();
}
fn push(&self, state: String) {
if state == self.current_route() {
// don't push the same state twice
return;
}
let w = window().expect("access to `window`");
let h = w.history().expect("`window` has access to `history`");
// update the scroll position before pushing the new state
update_scroll(&w, &h);
if push_state_and_url(&self.history, &self.create_state(), self.full_path(&state)).is_ok() {
self.handle_nav();
}
}
fn replace(&self, state: String) {
if replace_state_with_url(
&self.history,
&self.create_state(),
Some(&self.full_path(&state)),
)
.is_ok()
{
self.handle_nav();
}
}
fn external(&self, url: String) -> bool {
self.window.location().set_href(&url).is_ok()
}
fn updater(&self, callback: std::sync::Arc<dyn Fn() + Send + Sync>) {
let w = self.window.clone();
let h = self.history.clone();
let d = self.do_scroll_restoration;
let function = Closure::wrap(Box::new(move |_| {
(*callback)();
if d {
if let Some([x, y]) = get_current(&h) {
ScrollPosition { x, y }.scroll_to(w.clone())
}
}
}) as Box<dyn FnMut(Event)>);
self.window
.add_event_listener_with_callback(
"popstate",
&function.into_js_value().unchecked_into(),
)
.unwrap();
}
}
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct ScrollPosition {
pub x: f64,
pub y: f64,
}
impl ScrollPosition {
pub(crate) fn of_window(window: &Window) -> Self {
Self {
x: window.scroll_x().unwrap_or_default(),
y: window.scroll_y().unwrap_or_default(),
}
}
pub(crate) fn scroll_to(&self, window: Window) {
let Self { x, y } = *self;
let f = Closure::wrap(
Box::new(move || window.scroll_to_with_x_and_y(x, y)) as Box<dyn FnMut()>
);
web_sys::window()
.expect("should be run in a context with a `Window` object (dioxus cannot be run from a web worker)")
.request_animation_frame(&f.into_js_value().unchecked_into())
.expect("should register `requestAnimationFrame` OK");
}
}
pub(crate) fn replace_state_with_url(
history: &History,
value: &[f64; 2],
url: Option<&str>,
) -> Result<(), JsValue> {
let position = js_sys::Array::new();
position.push(&JsValue::from(value[0]));
position.push(&JsValue::from(value[1]));
history.replace_state_with_url(&position, "", url)
}
pub(crate) fn push_state_and_url(
history: &History,
value: &[f64; 2],
url: String,
) -> Result<(), JsValue> {
let position = js_sys::Array::new();
position.push(&JsValue::from(value[0]));
position.push(&JsValue::from(value[1]));
history.push_state_with_url(&position, "", Some(&url))
}
pub(crate) fn get_current(history: &History) -> Option<[f64; 2]> {
use wasm_bindgen::JsCast;
history.state().ok().and_then(|state| {
let state = state.dyn_into::<js_sys::Array>().ok()?;
let x = state.get(0).as_f64()?;
let y = state.get(1).as_f64()?;
Some([x, y])
})
}
fn update_scroll(window: &Window, history: &History) {
let scroll = ScrollPosition::of_window(window);
let _ = replace_state_with_url(history, &[scroll.x, scroll.y], None);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/dom.rs | packages/web/src/dom.rs | //! Implementation of a renderer for Dioxus on the web.
//!
//! Outstanding todos:
//! - Passive event listeners
//! - no-op event listener patch for safari
//! - tests to ensure dyn_into works for various event types.
//! - Partial delegation?
use std::{any::Any, rc::Rc};
use dioxus_core::Runtime;
use dioxus_core::{ElementId, Template};
use dioxus_interpreter_js::unified_bindings::Interpreter;
use rustc_hash::FxHashMap;
use wasm_bindgen::{closure::Closure, JsCast};
use web_sys::{Document, Event, Node};
use crate::{load_document, virtual_event_from_websys_event, Config, WebEventConverter};
pub struct WebsysDom {
#[allow(dead_code)]
pub(crate) root: Node,
pub(crate) document: Document,
pub(crate) templates: FxHashMap<Template, u16>,
pub(crate) interpreter: Interpreter,
#[cfg(feature = "mounted")]
pub(crate) runtime: Rc<Runtime>,
#[cfg(feature = "mounted")]
pub(crate) queued_mounted_events: Vec<ElementId>,
// We originally started with a different `WriteMutations` for collecting templates during hydration.
// When profiling the binary size of web applications, this caused a large increase in binary size
// because diffing code in core is generic over the `WriteMutation` object.
//
// The fact that diffing is generic over WriteMutations instead of dynamic dispatch or a vec is nice
// because we can directly write mutations to sledgehammer and avoid the runtime and binary size overhead
// of dynamic dispatch
//
// Instead we now store a flag to see if we should be writing templates at all if hydration is enabled.
// This has a small overhead, but it avoids dynamic dispatch and reduces the binary size
//
// NOTE: running the virtual dom with the `write_mutations` flag set to true is different from running
// it with no mutation writer because it still assigns ids to nodes, but it doesn't write them to the dom
#[cfg(feature = "hydrate")]
pub(crate) skip_mutations: bool,
#[cfg(feature = "hydrate")]
pub(crate) suspense_hydration_ids: crate::hydration::SuspenseHydrationIds,
}
impl WebsysDom {
pub fn new(cfg: Config, runtime: Rc<Runtime>) -> Self {
let (document, root) = match cfg.root {
crate::cfg::ConfigRoot::RootName(rootname) => {
// eventually, we just want to let the interpreter do all the work of decoding events into our event type
// a match here in order to avoid some error during runtime browser test
let document = load_document();
let root = match document.get_element_by_id(&rootname) {
Some(root) => root,
None => {
web_sys::console::error_1(
&format!("element '#{}' not found. mounting to the body.", rootname)
.into(),
);
document.create_element("body").ok().unwrap()
}
};
(document, root.unchecked_into())
}
crate::cfg::ConfigRoot::RootNode(root) => {
let document = match root.owner_document() {
Some(document) => document,
None => load_document(),
};
(document, root)
}
};
let interpreter = Interpreter::default();
// The closure type we pass to the dom may be invoked recursively if one event triggers another. For example,
// one event could focus another element which triggers the focus event of the new element like inhttps://github.com/DioxusLabs/dioxus/issues/2882.
// The Closure<dyn Fn(_)> type can invoked recursively, but Closure<dyn FnMut()> cannot
let handler: Closure<dyn Fn(&Event)> = Closure::wrap(Box::new({
let runtime = runtime.clone();
move |web_sys_event: &web_sys::Event| {
let name = web_sys_event.type_();
let element = walk_event_for_id(web_sys_event);
let bubbles = web_sys_event.bubbles();
let Some((element, target)) = element else {
return;
};
let data = virtual_event_from_websys_event(web_sys_event.clone(), target);
let event = dioxus_core::Event::new(Rc::new(data) as Rc<dyn Any>, bubbles);
runtime.handle_event(name.as_str(), event.clone(), element);
// Prevent the default action if the user set prevent default on the event
let prevent_default = !event.default_action_enabled();
if prevent_default {
web_sys_event.prevent_default();
}
}
}));
let _interpreter = interpreter.base();
_interpreter.initialize(
root.clone().unchecked_into(),
handler.as_ref().unchecked_ref(),
);
dioxus_html::set_event_converter(Box::new(WebEventConverter));
handler.forget();
Self {
document,
root,
interpreter,
templates: FxHashMap::default(),
#[cfg(feature = "mounted")]
runtime,
#[cfg(feature = "mounted")]
queued_mounted_events: Default::default(),
#[cfg(feature = "hydrate")]
skip_mutations: false,
#[cfg(feature = "hydrate")]
suspense_hydration_ids: Default::default(),
}
}
}
fn walk_event_for_id(event: &web_sys::Event) -> Option<(ElementId, web_sys::Element)> {
let target = event
.target()
.expect("missing target")
.dyn_into::<web_sys::Node>()
.expect("not a valid node");
walk_element_for_id(&target)
}
fn walk_element_for_id(target: &Node) -> Option<(ElementId, web_sys::Element)> {
let mut current_target_element = target.dyn_ref::<web_sys::Element>().cloned();
loop {
match (
current_target_element
.as_ref()
.and_then(|el| el.get_attribute("data-dioxus-id").map(|f| f.parse())),
current_target_element,
) {
// This node is an element, and has a dioxus id, so we can stop walking
(Some(Ok(id)), Some(target)) => return Some((ElementId(id), target)),
// Walk the tree upwards until we actually find an event target
(None, target_element) => {
let parent = match target_element.as_ref() {
Some(el) => el.parent_element(),
// if this is the first node and not an element, we need to get the parent from the target node
None => target.parent_element(),
};
match parent {
Some(parent) => current_target_element = Some(parent),
_ => return None,
}
}
// This node is an element with an invalid dioxus id, give up
_ => return None,
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/files.rs | packages/web/src/files.rs | use dioxus_core::AnyhowContext;
use dioxus_html::{bytes::Bytes, FileData, NativeFileData};
use futures_channel::oneshot;
use js_sys::Uint8Array;
use send_wrapper::SendWrapper;
use std::{pin::Pin, prelude::rust_2024::Future};
use wasm_bindgen::{prelude::Closure, JsCast};
use web_sys::{File, FileList, FileReader};
/// A file representation for the web platform
#[derive(Clone)]
pub struct WebFileData {
file: File,
reader: FileReader,
}
unsafe impl Send for WebFileData {}
unsafe impl Sync for WebFileData {}
impl WebFileData {
/// Create a new WebFileData from a web_sys::File
pub fn new(file: File, reader: FileReader) -> Self {
Self { file, reader }
}
}
impl NativeFileData for WebFileData {
fn name(&self) -> String {
self.file.name()
}
fn size(&self) -> u64 {
self.file.size() as u64
}
fn last_modified(&self) -> u64 {
self.file.last_modified() as u64
}
fn read_bytes(
&self,
) -> Pin<Box<dyn Future<Output = Result<Bytes, dioxus_core::CapturedError>> + 'static>> {
let file_reader = self.reader.clone();
let file_reader_ = self.reader.clone();
let file = self.file.clone();
Box::pin(async move {
let (rx, tx) = oneshot::channel();
let on_load: Closure<dyn FnMut()> = Closure::new({
let mut rx = Some(rx);
move || {
let result = file_reader.result();
let _ = rx
.take()
.expect("multiple files read without refreshing the channel")
.send(result);
}
});
file_reader_.set_onload(Some(on_load.as_ref().unchecked_ref()));
on_load.forget();
file_reader_
.read_as_array_buffer(&file)
.ok()
.context("Failed to read file")?;
let js_val = tx.await?.ok().context("Failed to read file")?;
let as_u8_arr = Uint8Array::new(&js_val);
let as_u8_vec = as_u8_arr.to_vec().into();
Ok(as_u8_vec)
})
}
fn read_string(
&self,
) -> Pin<Box<dyn Future<Output = Result<String, dioxus_core::CapturedError>> + 'static>> {
let file_reader = self.reader.clone();
let file_reader_ = self.reader.clone();
let file = self.file.clone();
Box::pin(async move {
let (rx, tx) = oneshot::channel();
let on_load: Closure<dyn FnMut()> = Closure::new({
let mut rx = Some(rx);
move || {
let result = file_reader.result();
let _ = rx
.take()
.expect("multiple files read without refreshing the channel")
.send(result);
}
});
file_reader_.set_onload(Some(on_load.as_ref().unchecked_ref()));
on_load.forget();
file_reader_
.read_as_text(&file)
.ok()
.context("Failed to read file")?;
let js_val = tx.await?.ok().context("Failed to read file")?;
let as_string = js_val.as_string().context("Failed to read file")?;
Ok(as_string)
})
}
/// we'd like to use `blob` to readable stream here, but we cannot.
///
/// We just read the entire file into memory and return it as a single chunk.
/// This is not super great, especially given the wasm <-> js boundary duplication cost.
///
/// For more efficient streaming of byte data, consider using the dedicated FileStream type which
/// goes directly from `File` to fetch request body without going through Rust.
///
/// We should maybe update these APIs to use our own custom `ByteBuffer` type to avoid going through `Vec<u8>`?
fn byte_stream(
&self,
) -> Pin<
Box<
dyn futures_util::Stream<Item = Result<Bytes, dioxus_core::CapturedError>>
+ 'static
+ Send,
>,
> {
let file = self.file.dyn_ref::<web_sys::Blob>().unwrap().clone();
Box::pin(SendWrapper::new(futures_util::stream::once(async move {
let array_buff = wasm_bindgen_futures::JsFuture::from(file.array_buffer())
.await
.unwrap();
let as_uint_array = array_buff.dyn_into::<Uint8Array>().unwrap();
Ok(as_uint_array.to_vec().into())
})))
}
fn inner(&self) -> &dyn std::any::Any {
&self.file
}
fn path(&self) -> std::path::PathBuf {
let key = wasm_bindgen::JsValue::from_str("webkitRelativePath");
if let Ok(value) = js_sys::Reflect::get(&self.file, &key) {
if let Some(path_str) = value.as_string() {
if !path_str.is_empty() {
return std::path::PathBuf::from(path_str);
}
}
}
std::path::PathBuf::from(self.file.name())
}
fn content_type(&self) -> Option<String> {
let type_ = self.file.type_();
if type_.is_empty() {
None
} else {
Some(type_)
}
}
}
/// A file engine for the web platform
#[derive(Clone)]
pub(crate) struct WebFileEngine {
file_list: FileList,
}
impl WebFileEngine {
/// Create a new file engine from a file list
pub fn new(file_list: FileList) -> Self {
Self { file_list }
}
fn len(&self) -> usize {
self.file_list.length() as usize
}
fn get(&self, index: usize) -> Option<File> {
self.file_list.item(index as u32)
}
pub fn to_files(&self) -> Vec<FileData> {
(0..self.len())
.filter_map(|i| self.get(i))
.map(|file| {
FileData::new(WebFileData {
file,
reader: FileReader::new().unwrap(),
})
})
.collect()
}
}
/// Helper trait for extracting the underlying `web_sys::File` from a `FileData`
pub trait WebFileExt {
/// returns web_sys::File
fn get_web_file(&self) -> Option<web_sys::File>;
}
impl WebFileExt for FileData {
fn get_web_file(&self) -> Option<web_sys::File> {
self.inner().downcast_ref::<web_sys::File>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/data_transfer.rs | packages/web/src/data_transfer.rs | use crate::WebFileData;
use dioxus_html::{FileData, NativeDataTransfer};
/// A wrapper around the web_sys::DataTransfer to implement NativeDataTransfer
#[derive(Clone)]
pub struct WebDataTransfer {
pub(crate) data: web_sys::DataTransfer,
}
impl WebDataTransfer {
/// Create a new WebDataTransfer from a web_sys::DataTransfer
pub fn new(data: web_sys::DataTransfer) -> Self {
Self { data }
}
}
unsafe impl Send for WebDataTransfer {}
unsafe impl Sync for WebDataTransfer {}
impl NativeDataTransfer for WebDataTransfer {
fn get_data(&self, format: &str) -> Option<String> {
self.data.get_data(format).ok()
}
fn set_data(&self, format: &str, data: &str) -> Result<(), String> {
self.data.set_data(format, data).map_err(|e| {
format!(
"Failed to set data for format {format}: {:?}",
e.as_string()
)
})
}
fn clear_data(&self, format: Option<&str>) -> Result<(), String> {
match format {
Some(f) => self.data.clear_data_with_format(f),
None => self.data.clear_data(),
}
.map_err(|e| format!("{:?}", e))
}
fn effect_allowed(&self) -> String {
self.data.effect_allowed()
}
fn set_effect_allowed(&self, effect: &str) {
self.data.set_effect_allowed(effect);
}
fn drop_effect(&self) -> String {
self.data.drop_effect()
}
fn set_drop_effect(&self, effect: &str) {
self.data.set_drop_effect(effect);
}
fn files(&self) -> Vec<FileData> {
let mut result = Vec::new();
if let Some(file_list) = self.data.files() {
for i in 0..file_list.length() {
if let Some(file) = file_list.item(i) {
result.push(FileData::new(WebFileData::new(
file,
web_sys::FileReader::new().unwrap(),
)));
}
}
}
result
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/cfg.rs | packages/web/src/cfg.rs | use std::rc::Rc;
use dioxus_core::LaunchConfig;
use wasm_bindgen::JsCast as _;
/// Configuration for the WebSys renderer for the Dioxus VirtualDOM.
///
/// This struct helps configure the specifics of hydration and render destination for WebSys.
///
/// # Example
///
/// ```rust, ignore
/// dioxus_web::launch(App, Config::new().hydrate(true).root_name("myroot"))
/// ```
pub struct Config {
pub(crate) hydrate: bool,
#[allow(dead_code)]
pub(crate) panic_hook: bool,
pub(crate) root: ConfigRoot,
#[cfg(feature = "document")]
pub(crate) history: Option<Rc<dyn dioxus_history::History>>,
}
impl LaunchConfig for Config {}
pub(crate) enum ConfigRoot {
RootName(String),
RootNode(web_sys::Node),
}
impl Config {
/// Create a new Default instance of the Config.
///
/// This is no different than calling `Config::default()`
pub fn new() -> Self {
Self::default()
}
#[cfg(feature = "hydrate")]
/// Enable SSR hydration
///
/// This enables Dioxus to pick up work from a pre-rendered HTML file. Hydration will completely skip over any async
/// work and suspended nodes.
///
/// Dioxus will load up all the elements with the `dio_el` data attribute into memory when the page is loaded.
pub fn hydrate(mut self, f: bool) -> Self {
self.hydrate = f;
self
}
/// Set the name of the element that Dioxus will use as the root.
///
/// This is akin to calling React.render() on the element with the specified name.
/// Note that this only works on the current document, i.e. `window.document`.
/// To use a different document (popup, iframe, ...) use [Self::rootelement] instead.
pub fn rootname(mut self, name: impl Into<String>) -> Self {
self.root = ConfigRoot::RootName(name.into());
self
}
/// Set the element that Dioxus will use as root.
///
/// This is akin to calling React.render() on the given element.
pub fn rootelement(mut self, elem: web_sys::Element) -> Self {
self.root = ConfigRoot::RootNode(elem.unchecked_into());
self
}
/// Set the node that Dioxus will use as root.
///
/// This is akin to calling React.render() on the given element.
pub fn rootnode(mut self, node: web_sys::Node) -> Self {
self.root = ConfigRoot::RootNode(node);
self
}
/// Set the history provider for the application.
///
/// `dioxus-web` provides two history providers:
/// - `dioxus_history::WebHistory`: A history provider that uses the browser history API.
/// - `dioxus_history::HashHistory`: A history provider that uses the `#` url fragment.
///
/// By default, `dioxus-web` uses the `WebHistory` provider, but this method can be used to configure
/// a different history provider.
pub fn history(mut self, history: Rc<dyn dioxus_history::History>) -> Self {
#[cfg(feature = "document")]
{
self.history = Some(history);
}
self
}
}
impl Default for Config {
fn default() -> Self {
Self {
hydrate: false,
root: ConfigRoot::RootName("main".to_string()),
#[cfg(feature = "document")]
history: None,
panic_hook: true,
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/focus.rs | packages/web/src/events/focus.rs | use dioxus_html::HasFocusData;
use super::{Synthetic, WebEventExt};
impl HasFocusData for Synthetic<web_sys::FocusEvent> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::FocusData {
type WebEvent = web_sys::FocusEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::FocusEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/scroll.rs | packages/web/src/events/scroll.rs | use dioxus_html::HasScrollData;
use wasm_bindgen::JsCast;
use web_sys::{Document, Element, Event};
use super::{Synthetic, WebEventExt};
impl HasScrollData for Synthetic<Event> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
fn scroll_top(&self) -> f64 {
if let Some(target) = self.event.target().as_ref() {
if let Some(element) = target.dyn_ref::<Element>() {
return element.scroll_top() as f64;
} else if let Some(element) = target
.dyn_ref::<Document>()
.and_then(|document| document.document_element())
{
return element.scroll_top() as f64;
}
}
0f64
}
fn scroll_left(&self) -> f64 {
if let Some(target) = self.event.target().as_ref() {
if let Some(element) = target.dyn_ref::<Element>() {
return element.scroll_left() as f64;
} else if let Some(element) = target
.dyn_ref::<Document>()
.and_then(|document| document.document_element())
{
return element.scroll_left() as f64;
}
}
0f64
}
fn scroll_width(&self) -> i32 {
if let Some(target) = self.event.target().as_ref() {
if let Some(element) = target.dyn_ref::<Element>() {
return element.scroll_width();
} else if let Some(element) = target
.dyn_ref::<Document>()
.and_then(|document| document.document_element())
{
return element.scroll_width();
}
}
0
}
fn scroll_height(&self) -> i32 {
if let Some(target) = self.event.target().as_ref() {
if let Some(element) = target.dyn_ref::<Element>() {
return element.scroll_height();
} else if let Some(element) = target
.dyn_ref::<Document>()
.and_then(|document| document.document_element())
{
return element.scroll_height();
}
}
0
}
fn client_width(&self) -> i32 {
if let Some(target) = self.event.target().as_ref() {
if let Some(element) = target.dyn_ref::<Element>() {
return element.client_width();
} else if let Some(element) = target
.dyn_ref::<Document>()
.and_then(|document| document.document_element())
{
return element.client_width();
}
}
0
}
fn client_height(&self) -> i32 {
if let Some(target) = self.event.target().as_ref() {
if let Some(element) = target.dyn_ref::<Element>() {
return element.client_height();
} else if let Some(element) = target
.dyn_ref::<Document>()
.and_then(|document| document.document_element())
{
return element.client_height();
}
}
0
}
}
impl WebEventExt for dioxus_html::ScrollData {
type WebEvent = web_sys::Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::Event>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/mouse.rs | packages/web/src/events/mouse.rs | use dioxus_html::{
geometry::{ClientPoint, ElementPoint, PagePoint, ScreenPoint},
input_data::{decode_mouse_button_set, MouseButton},
HasMouseData, InteractionElementOffset, InteractionLocation, Modifiers, ModifiersInteraction,
PointerInteraction,
};
use web_sys::MouseEvent;
use super::{Synthetic, WebEventExt};
impl InteractionLocation for Synthetic<MouseEvent> {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.event.client_x().into(), self.event.client_y().into())
}
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(self.event.page_x().into(), self.event.page_y().into())
}
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(self.event.screen_x().into(), self.event.screen_y().into())
}
}
impl InteractionElementOffset for Synthetic<MouseEvent> {
fn element_coordinates(&self) -> ElementPoint {
ElementPoint::new(self.event.offset_x().into(), self.event.offset_y().into())
}
}
impl ModifiersInteraction for Synthetic<MouseEvent> {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.event.alt_key() {
modifiers.insert(Modifiers::ALT);
}
if self.event.ctrl_key() {
modifiers.insert(Modifiers::CONTROL);
}
if self.event.meta_key() {
modifiers.insert(Modifiers::META);
}
if self.event.shift_key() {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
impl PointerInteraction for Synthetic<MouseEvent> {
fn held_buttons(&self) -> dioxus_html::input_data::MouseButtonSet {
decode_mouse_button_set(self.event.buttons())
}
fn trigger_button(&self) -> Option<MouseButton> {
Some(MouseButton::from_web_code(self.event.button()))
}
}
impl HasMouseData for Synthetic<MouseEvent> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::MouseData {
type WebEvent = web_sys::MouseEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::MouseEvent> {
self.downcast::<web_sys::MouseEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/clipboard.rs | packages/web/src/events/clipboard.rs | use dioxus_html::HasClipboardData;
use web_sys::Event;
use super::{Synthetic, WebEventExt};
impl From<&Event> for Synthetic<Event> {
fn from(e: &Event) -> Self {
Synthetic::new(e.clone())
}
}
impl HasClipboardData for Synthetic<Event> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::ClipboardData {
type WebEvent = web_sys::Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::Event>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/composition.rs | packages/web/src/events/composition.rs | use dioxus_html::HasCompositionData;
use web_sys::CompositionEvent;
use super::{Synthetic, WebEventExt};
impl HasCompositionData for Synthetic<CompositionEvent> {
fn data(&self) -> std::string::String {
self.event.data().unwrap_or_default()
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::CompositionData {
type WebEvent = web_sys::CompositionEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::CompositionEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/animation.rs | packages/web/src/events/animation.rs | use dioxus_html::HasAnimationData;
use web_sys::AnimationEvent;
use super::{Synthetic, WebEventExt};
impl HasAnimationData for Synthetic<AnimationEvent> {
fn animation_name(&self) -> String {
self.event.animation_name()
}
fn pseudo_element(&self) -> String {
self.event.pseudo_element()
}
fn elapsed_time(&self) -> f32 {
self.event.elapsed_time()
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::AnimationData {
type WebEvent = web_sys::AnimationEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::AnimationEvent> {
self.downcast::<web_sys::AnimationEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/form.rs | packages/web/src/events/form.rs | use super::WebEventExt;
use crate::WebFileData;
use dioxus_html::{FileData, FormValue, HasFileData, HasFormData};
use js_sys::Array;
use std::any::Any;
use wasm_bindgen::{prelude::wasm_bindgen, JsCast};
use web_sys::{Element, Event, FileReader};
pub(crate) struct WebFormData {
element: Element,
event: Event,
}
impl WebEventExt for dioxus_html::FormData {
type WebEvent = Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<Event>().cloned()
}
}
impl WebFormData {
pub fn new(element: Element, event: Event) -> Self {
Self { element, event }
}
}
impl HasFormData for WebFormData {
fn value(&self) -> String {
let target = &self.element;
target
.dyn_ref()
.map(|input: &web_sys::HtmlInputElement| {
// todo: special case more input types
match input.type_().as_str() {
"checkbox" => {
match input.checked() {
true => "true".to_string(),
false => "false".to_string(),
}
},
_ => {
input.value()
}
}
})
.or_else(|| {
target
.dyn_ref()
.map(|input: &web_sys::HtmlTextAreaElement| input.value())
})
// select elements are NOT input events - because - why woudn't they be??
.or_else(|| {
target
.dyn_ref()
.map(|input: &web_sys::HtmlSelectElement| input.value())
})
.or_else(|| {
target
.dyn_ref::<web_sys::HtmlElement>()
.unwrap()
.text_content()
})
.expect("only an InputElement or TextAreaElement or an element with contenteditable=true can have an oninput event listener")
}
fn values(&self) -> Vec<(String, FormValue)> {
let mut values = Vec::new();
// try to fill in form values
if let Some(form) = self.element.dyn_ref::<web_sys::HtmlFormElement>() {
let form_data = web_sys::FormData::new_with_form(form).unwrap();
for entry in form_data.entries().into_iter().flatten() {
if let Ok(array) = entry.dyn_into::<Array>() {
if let Some(name) = array.get(0).as_string() {
let value = array.get(1);
if let Some(file) = value.dyn_ref::<web_sys::File>() {
if file.name().is_empty() {
values.push((name, FormValue::File(None)));
} else {
let data =
WebFileData::new(file.clone(), FileReader::new().unwrap());
let as_file = FileData::new(data);
values.push((name, FormValue::File(Some(as_file))));
}
} else if let Some(s) = value.as_string() {
values.push((name, FormValue::Text(s)));
}
}
}
}
} else if let Some(select) = self.element.dyn_ref::<web_sys::HtmlSelectElement>() {
// try to fill in select element values
let options = get_select_data(select);
for option in &options {
values.push((select.name(), FormValue::Text(option.clone())));
}
}
values
}
fn as_any(&self) -> &dyn Any {
&self.event as &dyn Any
}
fn valid(&self) -> bool {
self.event
.target()
.and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
.map(|input| input.check_validity())
.unwrap_or(true)
}
}
impl HasFileData for WebFormData {
fn files(&self) -> Vec<FileData> {
use wasm_bindgen::JsCast;
self.event
.target()
.and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
.and_then(|input| input.files())
.map(crate::files::WebFileEngine::new)
.map(|engine| engine.to_files())
.unwrap_or_default()
}
}
// web-sys does not expose the keys api for select data, so we need to manually bind to it
#[wasm_bindgen(inline_js = r#"
export function get_select_data(select) {
let values = [];
for (let i = 0; i < select.options.length; i++) {
let option = select.options[i];
if (option.selected) {
values.push(option.value.toString());
}
}
return values;
}
"#)]
extern "C" {
fn get_select_data(select: &web_sys::HtmlSelectElement) -> Vec<String>;
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/drag.rs | packages/web/src/events/drag.rs | use crate::{WebDataTransfer, WebFileData, WebFileEngine};
use super::{Synthetic, WebEventExt};
use dioxus_html::{
geometry::{ClientPoint, ElementPoint, PagePoint, ScreenPoint},
input_data::{decode_mouse_button_set, MouseButton},
FileData, HasDataTransferData, HasDragData, HasFileData, HasMouseData,
InteractionElementOffset, InteractionLocation, Modifiers, ModifiersInteraction,
PointerInteraction,
};
use web_sys::{DragEvent, FileReader};
impl InteractionLocation for Synthetic<DragEvent> {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.event.client_x().into(), self.event.client_y().into())
}
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(self.event.page_x().into(), self.event.page_y().into())
}
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(self.event.screen_x().into(), self.event.screen_y().into())
}
}
impl InteractionElementOffset for Synthetic<DragEvent> {
fn element_coordinates(&self) -> ElementPoint {
ElementPoint::new(self.event.offset_x().into(), self.event.offset_y().into())
}
}
impl ModifiersInteraction for Synthetic<DragEvent> {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.event.alt_key() {
modifiers.insert(Modifiers::ALT);
}
if self.event.ctrl_key() {
modifiers.insert(Modifiers::CONTROL);
}
if self.event.meta_key() {
modifiers.insert(Modifiers::META);
}
if self.event.shift_key() {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
impl PointerInteraction for Synthetic<DragEvent> {
fn held_buttons(&self) -> dioxus_html::input_data::MouseButtonSet {
decode_mouse_button_set(self.event.buttons())
}
fn trigger_button(&self) -> Option<MouseButton> {
Some(MouseButton::from_web_code(self.event.button()))
}
}
impl HasMouseData for Synthetic<DragEvent> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl HasDragData for Synthetic<DragEvent> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl HasDataTransferData for Synthetic<DragEvent> {
fn data_transfer(&self) -> dioxus_html::DataTransfer {
use wasm_bindgen::JsCast;
if let Some(target) = self.event.dyn_ref::<web_sys::DragEvent>() {
if let Some(data) = target.data_transfer() {
let web_data_transfer = WebDataTransfer::new(data);
return dioxus_html::DataTransfer::new(web_data_transfer);
}
}
// Return an empty DataTransfer if we couldn't get one from the event
let web_data_transfer = WebDataTransfer::new(web_sys::DataTransfer::new().unwrap());
dioxus_html::DataTransfer::new(web_data_transfer)
}
}
impl HasFileData for Synthetic<DragEvent> {
fn files(&self) -> Vec<FileData> {
use wasm_bindgen::JsCast;
if let Some(target) = self.event.dyn_ref::<web_sys::DragEvent>() {
if let Some(data_transfer) = target.data_transfer() {
if let Some(file_list) = data_transfer.files() {
return WebFileEngine::new(file_list).to_files();
} else {
let items = data_transfer.items();
let mut files = vec![];
for i in 0..items.length() {
if let Some(item) = items.get(i) {
if item.kind() == "file" {
if let Ok(Some(file)) = item.get_as_file() {
let web_data =
WebFileData::new(file, FileReader::new().unwrap());
files.push(FileData::new(web_data));
}
}
}
}
return files;
}
}
} else {
tracing::warn!("DragEvent target was not a DragEvent");
}
vec![]
}
}
impl WebEventExt for dioxus_html::DragData {
type WebEvent = web_sys::DragEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::DragEvent> {
self.downcast::<DragEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/media.rs | packages/web/src/events/media.rs | use super::{Synthetic, WebEventExt};
use dioxus_html::HasMediaData;
impl HasMediaData for Synthetic<web_sys::Event> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::MediaData {
type WebEvent = web_sys::Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::Event>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/toggle.rs | packages/web/src/events/toggle.rs | use super::{Synthetic, WebEventExt};
use dioxus_html::HasToggleData;
impl HasToggleData for Synthetic<web_sys::Event> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::ToggleData {
type WebEvent = web_sys::Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::Event>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/cancel.rs | packages/web/src/events/cancel.rs | use super::{Synthetic, WebEventExt};
use dioxus_html::HasCancelData;
impl HasCancelData for Synthetic<web_sys::Event> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::CancelData {
type WebEvent = web_sys::Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::Event>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/transition.rs | packages/web/src/events/transition.rs | use dioxus_html::HasTransitionData;
use web_sys::TransitionEvent;
use super::Synthetic;
impl HasTransitionData for Synthetic<TransitionEvent> {
fn elapsed_time(&self) -> f32 {
self.event.elapsed_time()
}
fn property_name(&self) -> String {
self.event.property_name()
}
fn pseudo_element(&self) -> String {
self.event.pseudo_element()
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/wheel.rs | packages/web/src/events/wheel.rs | use dioxus_html::{
geometry::{ClientPoint, ElementPoint, PagePoint, ScreenPoint},
input_data::{decode_mouse_button_set, MouseButton},
HasMouseData, HasWheelData, InteractionElementOffset, InteractionLocation, Modifiers,
ModifiersInteraction, PointerInteraction,
};
use web_sys::WheelEvent;
use super::{Synthetic, WebEventExt};
impl HasWheelData for Synthetic<WheelEvent> {
fn delta(&self) -> dioxus_html::geometry::WheelDelta {
dioxus_html::geometry::WheelDelta::from_web_attributes(
self.event.delta_mode(),
self.event.delta_x(),
self.event.delta_y(),
self.event.delta_z(),
)
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl HasMouseData for Synthetic<WheelEvent> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl InteractionLocation for Synthetic<WheelEvent> {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.event.client_x().into(), self.event.client_y().into())
}
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(self.event.screen_x().into(), self.event.screen_y().into())
}
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(self.event.page_x().into(), self.event.page_y().into())
}
}
impl InteractionElementOffset for Synthetic<WheelEvent> {
fn element_coordinates(&self) -> ElementPoint {
ElementPoint::new(self.event.offset_x().into(), self.event.offset_y().into())
}
}
impl ModifiersInteraction for Synthetic<WheelEvent> {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.event.alt_key() {
modifiers.insert(Modifiers::ALT);
}
if self.event.ctrl_key() {
modifiers.insert(Modifiers::CONTROL);
}
if self.event.meta_key() {
modifiers.insert(Modifiers::META);
}
if self.event.shift_key() {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
impl PointerInteraction for Synthetic<WheelEvent> {
fn held_buttons(&self) -> dioxus_html::input_data::MouseButtonSet {
decode_mouse_button_set(self.event.buttons())
}
fn trigger_button(&self) -> Option<MouseButton> {
Some(MouseButton::from_web_code(self.event.button()))
}
}
impl WebEventExt for dioxus_html::WheelData {
type WebEvent = web_sys::WheelEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::WheelEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/file.rs | packages/web/src/events/file.rs | use dioxus_html::{FileData, HasFileData};
use web_sys::FileReader;
use crate::{WebFileData, WebFileEngine};
use super::Synthetic;
impl HasFileData for Synthetic<web_sys::Event> {
fn files(&self) -> Vec<FileData> {
use wasm_bindgen::JsCast;
let target = self.event.target();
if let Some(target) = target
.clone()
.and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
{
if let Some(file_list) = target.files() {
return WebFileEngine::new(file_list).to_files();
}
}
if let Some(target) = target.and_then(|t| t.dyn_into::<web_sys::DragEvent>().ok()) {
if let Some(data_transfer) = target.data_transfer() {
if let Some(file_list) = data_transfer.files() {
return WebFileEngine::new(file_list).to_files();
} else {
let items = data_transfer.items();
let mut files = vec![];
for i in 0..items.length() {
if let Some(item) = items.get(i) {
if item.kind() == "file" {
if let Ok(Some(file)) = item.get_as_file() {
let web_data =
WebFileData::new(file, FileReader::new().unwrap());
files.push(FileData::new(web_data));
}
}
}
}
return files;
}
}
}
vec![]
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/mod.rs | packages/web/src/events/mod.rs | use dioxus_html::{
DragData, FormData, HtmlEventConverter, ImageData, MountedData, PlatformEventData,
};
use form::WebFormData;
use load::WebImageEvent;
use wasm_bindgen::JsCast;
use web_sys::{Document, Element, Event};
mod animation;
mod cancel;
mod clipboard;
mod composition;
mod drag;
mod file;
mod focus;
mod form;
mod keyboard;
mod load;
mod media;
#[cfg(feature = "mounted")]
mod mounted;
mod mouse;
mod pointer;
mod resize;
mod scroll;
mod selection;
mod toggle;
mod touch;
mod transition;
mod visible;
mod wheel;
/// A wrapper for the websys event that allows us to give it the impls from dioxus-html
pub(crate) struct Synthetic<T: 'static> {
/// The inner web sys event that the synthetic event wraps
pub event: T,
}
impl<T: 'static> Synthetic<T> {
/// Create a new synthetic event from a web sys event
pub fn new(event: T) -> Self {
Self { event }
}
}
pub(crate) struct WebEventConverter;
#[inline(always)]
fn downcast_event(event: &dioxus_html::PlatformEventData) -> &GenericWebSysEvent {
event
.downcast::<GenericWebSysEvent>()
.expect("event should be a GenericWebSysEvent")
}
impl HtmlEventConverter for WebEventConverter {
#[inline(always)]
fn convert_animation_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::AnimationData {
Synthetic::<web_sys::AnimationEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_cancel_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::CancelData {
Synthetic::new(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_clipboard_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::ClipboardData {
Synthetic::new(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_composition_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::CompositionData {
Synthetic::<web_sys::CompositionEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_drag_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::DragData {
let event = downcast_event(event);
DragData::new(Synthetic::new(
event.raw.clone().unchecked_into::<web_sys::DragEvent>(),
))
}
#[inline(always)]
fn convert_focus_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::FocusData {
Synthetic::<web_sys::FocusEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_form_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::FormData {
let event = downcast_event(event);
FormData::new(WebFormData::new(event.element.clone(), event.raw.clone()))
}
#[inline(always)]
fn convert_image_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::ImageData {
let event = downcast_event(event);
let error = event.raw.type_() == "error";
ImageData::new(WebImageEvent::new(event.raw.clone(), error))
}
#[inline(always)]
fn convert_keyboard_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::KeyboardData {
Synthetic::<web_sys::KeyboardEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_media_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::MediaData {
Synthetic::new(downcast_event(event).raw.clone()).into()
}
#[allow(unused_variables)]
#[inline(always)]
fn convert_mounted_data(&self, event: &dioxus_html::PlatformEventData) -> MountedData {
#[cfg(feature = "mounted")]
{
Synthetic::new(
event
.downcast::<web_sys::Element>()
.expect("event should be a web_sys::Element")
.clone(),
)
.into()
}
#[cfg(not(feature = "mounted"))]
{
panic!("mounted events are not supported without the mounted feature on the dioxus-web crate enabled")
}
}
#[inline(always)]
fn convert_mouse_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::MouseData {
Synthetic::<web_sys::MouseEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_pointer_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::PointerData {
Synthetic::<web_sys::PointerEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_resize_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::ResizeData {
Synthetic::<web_sys::ResizeObserverEntry>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_scroll_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::ScrollData {
Synthetic::new(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_selection_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::SelectionData {
Synthetic::new(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_toggle_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::ToggleData {
Synthetic::new(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_touch_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::TouchData {
Synthetic::<web_sys::TouchEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_transition_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::TransitionData {
Synthetic::<web_sys::TransitionEvent>::from(downcast_event(event).raw.clone()).into()
}
#[inline(always)]
fn convert_visible_data(
&self,
event: &dioxus_html::PlatformEventData,
) -> dioxus_html::VisibleData {
Synthetic::<web_sys::IntersectionObserverEntry>::from(downcast_event(event).raw.clone())
.into()
}
#[inline(always)]
fn convert_wheel_data(&self, event: &dioxus_html::PlatformEventData) -> dioxus_html::WheelData {
Synthetic::<web_sys::WheelEvent>::from(downcast_event(event).raw.clone()).into()
}
}
/// A extension trait for web-sys events that provides a way to get the event as a web-sys event.
pub trait WebEventExt {
/// The web specific event type
type WebEvent;
/// Try to downcast this event as a `web-sys` event.
fn try_as_web_event(&self) -> Option<Self::WebEvent>;
/// Downcast this event as a `web-sys` event.
#[inline(always)]
fn as_web_event(&self) -> Self::WebEvent
where
Self::WebEvent: 'static,
{
self.try_as_web_event().unwrap_or_else(|| {
panic!(
"Error downcasting to `web-sys`, event should be a {}.",
std::any::type_name::<Self::WebEvent>()
)
})
}
}
struct GenericWebSysEvent {
raw: Event,
element: Element,
}
// todo: some of these events are being casted to the wrong event type.
// We need tests that simulate clicks/etc and make sure every event type works.
pub(crate) fn virtual_event_from_websys_event(
event: web_sys::Event,
target: Element,
) -> PlatformEventData {
PlatformEventData::new(Box::new(GenericWebSysEvent {
raw: event,
element: target,
}))
}
pub(crate) fn load_document() -> Document {
web_sys::window()
.expect("should have access to the Window")
.document()
.expect("should have access to the Document")
}
macro_rules! uncheck_convert {
($t:ty) => {
impl From<Event> for Synthetic<$t> {
#[inline]
fn from(e: Event) -> Self {
let e: $t = e.unchecked_into();
Self::new(e)
}
}
impl From<&Event> for Synthetic<$t> {
#[inline]
fn from(e: &Event) -> Self {
let e: &$t = e.unchecked_ref();
Self::new(e.clone())
}
}
};
($($t:ty),+ $(,)?) => {
$(uncheck_convert!($t);)+
};
}
uncheck_convert![
web_sys::CompositionEvent,
web_sys::KeyboardEvent,
web_sys::TouchEvent,
web_sys::PointerEvent,
web_sys::WheelEvent,
web_sys::AnimationEvent,
web_sys::TransitionEvent,
web_sys::MouseEvent,
web_sys::FocusEvent,
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/selection.rs | packages/web/src/events/selection.rs | use super::{Synthetic, WebEventExt};
use dioxus_html::HasSelectionData;
impl HasSelectionData for Synthetic<web_sys::Event> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl WebEventExt for dioxus_html::SelectionData {
type WebEvent = web_sys::Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Self::WebEvent> {
self.downcast::<web_sys::Event>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/mounted.rs | packages/web/src/events/mounted.rs | use dioxus_html::{
geometry::euclid::{Point2D, Size2D},
MountedData,
};
use wasm_bindgen::JsCast;
use super::{Synthetic, WebEventExt};
impl dioxus_html::RenderedElementBacking for Synthetic<web_sys::Element> {
fn get_scroll_offset(
&self,
) -> std::pin::Pin<
Box<
dyn std::future::Future<
Output = dioxus_html::MountedResult<dioxus_html::geometry::PixelsVector2D>,
>,
>,
> {
let left = self.event.scroll_left();
let top = self.event.scroll_top();
let result = Ok(dioxus_html::geometry::PixelsVector2D::new(
left as f64,
top as f64,
));
Box::pin(async { result })
}
fn get_scroll_size(
&self,
) -> std::pin::Pin<
Box<
dyn std::future::Future<
Output = dioxus_html::MountedResult<dioxus_html::geometry::PixelsSize>,
>,
>,
> {
let width = self.event.scroll_width();
let height = self.event.scroll_height();
let result = Ok(dioxus_html::geometry::PixelsSize::new(
width as f64,
height as f64,
));
Box::pin(async { result })
}
fn get_client_rect(
&self,
) -> std::pin::Pin<
Box<
dyn std::future::Future<
Output = dioxus_html::MountedResult<dioxus_html::geometry::PixelsRect>,
>,
>,
> {
let rect = self.event.get_bounding_client_rect();
let result = Ok(dioxus_html::geometry::PixelsRect::new(
Point2D::new(rect.left(), rect.top()),
Size2D::new(rect.width(), rect.height()),
));
Box::pin(async { result })
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
fn scroll_to(
&self,
input_options: dioxus_html::ScrollToOptions,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = dioxus_html::MountedResult<()>>>> {
let options = web_sys::ScrollIntoViewOptions::new();
options.set_behavior(match input_options.behavior {
dioxus_html::ScrollBehavior::Instant => web_sys::ScrollBehavior::Instant,
dioxus_html::ScrollBehavior::Smooth => web_sys::ScrollBehavior::Smooth,
});
options.set_block(match input_options.vertical {
dioxus_html::ScrollLogicalPosition::Start => web_sys::ScrollLogicalPosition::Start,
dioxus_html::ScrollLogicalPosition::Center => web_sys::ScrollLogicalPosition::Center,
dioxus_html::ScrollLogicalPosition::End => web_sys::ScrollLogicalPosition::End,
dioxus_html::ScrollLogicalPosition::Nearest => web_sys::ScrollLogicalPosition::Nearest,
});
options.set_inline(match input_options.horizontal {
dioxus_html::ScrollLogicalPosition::Start => web_sys::ScrollLogicalPosition::Start,
dioxus_html::ScrollLogicalPosition::Center => web_sys::ScrollLogicalPosition::Center,
dioxus_html::ScrollLogicalPosition::End => web_sys::ScrollLogicalPosition::End,
dioxus_html::ScrollLogicalPosition::Nearest => web_sys::ScrollLogicalPosition::Nearest,
});
self.event
.scroll_into_view_with_scroll_into_view_options(&options);
Box::pin(async { Ok(()) })
}
fn scroll(
&self,
coordinates: dioxus_html::geometry::PixelsVector2D,
behavior: dioxus_html::ScrollBehavior,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = dioxus_html::MountedResult<()>>>> {
let options = web_sys::ScrollToOptions::new();
options.set_top(coordinates.y);
options.set_left(coordinates.x);
match behavior {
dioxus_html::ScrollBehavior::Instant => {
options.set_behavior(web_sys::ScrollBehavior::Instant);
}
dioxus_html::ScrollBehavior::Smooth => {
options.set_behavior(web_sys::ScrollBehavior::Smooth);
}
}
self.event.scroll_with_scroll_to_options(&options);
Box::pin(async { Ok(()) })
}
fn set_focus(
&self,
focus: bool,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = dioxus_html::MountedResult<()>>>> {
#[derive(Debug)]
struct FocusError(wasm_bindgen::JsValue);
impl std::fmt::Display for FocusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "failed to focus element {:?}", self.0)
}
}
impl std::error::Error for FocusError {}
let result = self
.event
.dyn_ref::<web_sys::HtmlElement>()
.ok_or_else(|| {
dioxus_html::MountedError::OperationFailed(Box::new(FocusError(
self.event.clone().into(),
)))
})
.and_then(|e| {
(if focus { e.focus() } else { e.blur() }).map_err(|err| {
dioxus_html::MountedError::OperationFailed(Box::new(FocusError(err)))
})
});
Box::pin(async { result })
}
}
impl WebEventExt for MountedData {
type WebEvent = web_sys::Element;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::Element> {
self.downcast::<web_sys::Element>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/load.rs | packages/web/src/events/load.rs | use std::any::Any;
use dioxus_html::HasImageData;
use web_sys::Event;
use super::WebEventExt;
#[derive(Clone)]
pub(crate) struct WebImageEvent {
raw: Event,
error: bool,
}
impl WebImageEvent {
pub fn new(raw: Event, error: bool) -> Self {
Self { raw, error }
}
}
impl HasImageData for WebImageEvent {
fn load_error(&self) -> bool {
self.error
}
fn as_any(&self) -> &dyn Any {
&self.raw
}
}
impl WebEventExt for dioxus_html::ImageData {
type WebEvent = Event;
#[inline(always)]
fn try_as_web_event(&self) -> Option<Event> {
self.downcast::<WebImageEvent>().map(|e| e.raw.clone())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/keyboard.rs | packages/web/src/events/keyboard.rs | use std::str::FromStr;
use dioxus_html::{
input_data::decode_key_location, Code, HasKeyboardData, Key, Location, Modifiers,
ModifiersInteraction,
};
use web_sys::KeyboardEvent;
use super::{Synthetic, WebEventExt};
impl HasKeyboardData for Synthetic<KeyboardEvent> {
fn key(&self) -> Key {
Key::from_str(self.event.key().as_str()).unwrap_or(Key::Unidentified)
}
fn code(&self) -> Code {
Code::from_str(self.event.code().as_str()).unwrap_or(Code::Unidentified)
}
fn location(&self) -> Location {
decode_key_location(self.event.location() as usize)
}
fn is_auto_repeating(&self) -> bool {
self.event.repeat()
}
fn is_composing(&self) -> bool {
self.event.is_composing()
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl ModifiersInteraction for Synthetic<KeyboardEvent> {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.event.alt_key() {
modifiers.insert(Modifiers::ALT);
}
if self.event.ctrl_key() {
modifiers.insert(Modifiers::CONTROL);
}
if self.event.meta_key() {
modifiers.insert(Modifiers::META);
}
if self.event.shift_key() {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
impl WebEventExt for dioxus_html::KeyboardData {
type WebEvent = web_sys::KeyboardEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::KeyboardEvent> {
self.downcast::<web_sys::KeyboardEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/pointer.rs | packages/web/src/events/pointer.rs | use dioxus_html::{
geometry::{ClientPoint, ElementPoint, PagePoint, ScreenPoint},
input_data::{decode_mouse_button_set, MouseButton},
HasPointerData, InteractionElementOffset, InteractionLocation, Modifiers, ModifiersInteraction,
PointerInteraction,
};
use web_sys::PointerEvent;
use super::{Synthetic, WebEventExt};
impl HasPointerData for Synthetic<PointerEvent> {
fn pointer_id(&self) -> i32 {
self.event.pointer_id()
}
fn width(&self) -> f64 {
self.event.width() as _
}
fn height(&self) -> f64 {
self.event.height() as _
}
fn pressure(&self) -> f32 {
self.event.pressure()
}
fn tangential_pressure(&self) -> f32 {
self.event.tangential_pressure()
}
fn tilt_x(&self) -> i32 {
self.event.tilt_x()
}
fn tilt_y(&self) -> i32 {
self.event.tilt_y()
}
fn twist(&self) -> i32 {
self.event.twist()
}
fn pointer_type(&self) -> String {
self.event.pointer_type()
}
fn is_primary(&self) -> bool {
self.event.is_primary()
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl InteractionLocation for Synthetic<PointerEvent> {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.event.client_x().into(), self.event.client_y().into())
}
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(self.event.screen_x().into(), self.event.screen_y().into())
}
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(self.event.page_x().into(), self.event.page_y().into())
}
}
impl InteractionElementOffset for Synthetic<PointerEvent> {
fn element_coordinates(&self) -> ElementPoint {
ElementPoint::new(self.event.offset_x().into(), self.event.offset_y().into())
}
}
impl ModifiersInteraction for Synthetic<PointerEvent> {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.event.alt_key() {
modifiers.insert(Modifiers::ALT);
}
if self.event.ctrl_key() {
modifiers.insert(Modifiers::CONTROL);
}
if self.event.meta_key() {
modifiers.insert(Modifiers::META);
}
if self.event.shift_key() {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
impl PointerInteraction for Synthetic<PointerEvent> {
fn held_buttons(&self) -> dioxus_html::input_data::MouseButtonSet {
decode_mouse_button_set(self.event.buttons())
}
fn trigger_button(&self) -> Option<MouseButton> {
Some(MouseButton::from_web_code(self.event.button()))
}
}
impl WebEventExt for dioxus_html::PointerData {
type WebEvent = web_sys::PointerEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::PointerEvent> {
self.downcast::<web_sys::PointerEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/visible.rs | packages/web/src/events/visible.rs | use std::time::SystemTime;
use dioxus_html::{
geometry::{
euclid::{Point2D, Size2D},
PixelsRect,
},
HasVisibleData, VisibleData, VisibleError, VisibleResult,
};
use wasm_bindgen::JsCast;
use web_sys::{CustomEvent, DomRectReadOnly, Event, IntersectionObserverEntry};
use super::{Synthetic, WebEventExt};
impl From<Event> for Synthetic<IntersectionObserverEntry> {
#[inline]
fn from(e: Event) -> Self {
<Synthetic<IntersectionObserverEntry> as From<&Event>>::from(&e)
}
}
impl From<&Event> for Synthetic<IntersectionObserverEntry> {
#[inline]
fn from(e: &Event) -> Self {
let e: &CustomEvent = e.unchecked_ref();
let value = e.detail();
Self::new(value.unchecked_into::<IntersectionObserverEntry>())
}
}
fn dom_rect_ro_to_pixel_rect(dom_rect: &DomRectReadOnly) -> PixelsRect {
PixelsRect::new(
Point2D::new(dom_rect.x(), dom_rect.y()),
Size2D::new(dom_rect.width(), dom_rect.height()),
)
}
impl HasVisibleData for Synthetic<IntersectionObserverEntry> {
/// Get the bounds rectangle of the target element
fn get_bounding_client_rect(&self) -> VisibleResult<PixelsRect> {
Ok(dom_rect_ro_to_pixel_rect(
&self.event.bounding_client_rect(),
))
}
/// Get the ratio of the intersectionRect to the boundingClientRect
fn get_intersection_ratio(&self) -> VisibleResult<f64> {
Ok(self.event.intersection_ratio())
}
/// Get the rect representing the target's visible area
fn get_intersection_rect(&self) -> VisibleResult<PixelsRect> {
Ok(dom_rect_ro_to_pixel_rect(&self.event.intersection_rect()))
}
/// Get if the target element intersects with the intersection observer's root
fn is_intersecting(&self) -> VisibleResult<bool> {
Ok(self.event.is_intersecting())
}
/// Get the rect for the intersection observer's root
fn get_root_bounds(&self) -> VisibleResult<PixelsRect> {
match self.event.root_bounds() {
Some(root_bounds) => Ok(dom_rect_ro_to_pixel_rect(&root_bounds)),
None => Err(VisibleError::NotSupported),
}
}
/// Get a timestamp indicating the time at which the intersection was recorded
fn get_time(&self) -> VisibleResult<SystemTime> {
let ms_since_epoch = self.event.time();
let rounded = ms_since_epoch.round() as u64;
let duration = std::time::Duration::from_millis(rounded);
Ok(SystemTime::UNIX_EPOCH + duration)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl WebEventExt for VisibleData {
type WebEvent = IntersectionObserverEntry;
#[inline(always)]
fn try_as_web_event(&self) -> Option<IntersectionObserverEntry> {
self.downcast::<CustomEvent>()
.and_then(|e| e.detail().dyn_into::<IntersectionObserverEntry>().ok())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/resize.rs | packages/web/src/events/resize.rs | use dioxus_html::{geometry::PixelsSize, HasResizeData, ResizeResult};
use wasm_bindgen::JsCast;
use web_sys::{CustomEvent, Event, ResizeObserverEntry};
use super::{Synthetic, WebEventExt};
impl From<Event> for Synthetic<ResizeObserverEntry> {
#[inline]
fn from(e: Event) -> Self {
<Synthetic<ResizeObserverEntry> as From<&Event>>::from(&e)
}
}
impl From<&Event> for Synthetic<ResizeObserverEntry> {
#[inline]
fn from(e: &Event) -> Self {
let e: &CustomEvent = e.unchecked_ref();
let value = e.detail();
Self::new(value.unchecked_into::<ResizeObserverEntry>())
}
}
impl HasResizeData for Synthetic<ResizeObserverEntry> {
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
fn get_border_box_size(&self) -> ResizeResult<PixelsSize> {
extract_first_size(self.event.border_box_size())
}
fn get_content_box_size(&self) -> ResizeResult<PixelsSize> {
extract_first_size(self.event.content_box_size())
}
}
impl WebEventExt for dioxus_html::ResizeData {
type WebEvent = web_sys::ResizeObserverEntry;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::ResizeObserverEntry> {
self.downcast::<web_sys::ResizeObserverEntry>().cloned()
}
}
fn extract_first_size(resize_observer_output: js_sys::Array) -> ResizeResult<PixelsSize> {
let first = resize_observer_output.get(0);
let size = first.unchecked_into::<web_sys::ResizeObserverSize>();
// inline_size matches the width of the element if its writing-mode is horizontal, the height otherwise
let inline_size = size.inline_size();
// block_size matches the height of the element if its writing-mode is horizontal, the width otherwise
let block_size = size.block_size();
Ok(PixelsSize::new(inline_size, block_size))
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/events/touch.rs | packages/web/src/events/touch.rs | use dioxus_html::{
geometry::{ClientPoint, PagePoint, ScreenPoint},
HasTouchPointData, InteractionLocation, Modifiers, ModifiersInteraction, TouchPoint,
};
use web_sys::{Touch, TouchEvent};
use super::{Synthetic, WebEventExt};
impl ModifiersInteraction for Synthetic<TouchEvent> {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.event.alt_key() {
modifiers.insert(Modifiers::ALT);
}
if self.event.ctrl_key() {
modifiers.insert(Modifiers::CONTROL);
}
if self.event.meta_key() {
modifiers.insert(Modifiers::META);
}
if self.event.shift_key() {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
impl dioxus_html::events::HasTouchData for Synthetic<TouchEvent> {
fn touches(&self) -> Vec<TouchPoint> {
let touches = TouchEvent::touches(&self.event);
let mut result = Vec::with_capacity(touches.length() as usize);
for i in 0..touches.length() {
let touch = touches.get(i).unwrap();
result.push(TouchPoint::new(Synthetic::new(touch)));
}
result
}
fn touches_changed(&self) -> Vec<TouchPoint> {
let touches = self.event.changed_touches();
let mut result = Vec::with_capacity(touches.length() as usize);
for i in 0..touches.length() {
let touch = touches.get(i).unwrap();
result.push(TouchPoint::new(Synthetic::new(touch)));
}
result
}
fn target_touches(&self) -> Vec<TouchPoint> {
let touches = self.event.target_touches();
let mut result = Vec::with_capacity(touches.length() as usize);
for i in 0..touches.length() {
let touch = touches.get(i).unwrap();
result.push(TouchPoint::new(Synthetic::new(touch)));
}
result
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl HasTouchPointData for Synthetic<Touch> {
fn identifier(&self) -> i32 {
self.event.identifier()
}
fn radius(&self) -> ScreenPoint {
ScreenPoint::new(self.event.radius_x().into(), self.event.radius_y().into())
}
fn rotation(&self) -> f64 {
self.event.rotation_angle() as f64
}
fn force(&self) -> f64 {
self.event.force() as f64
}
fn as_any(&self) -> &dyn std::any::Any {
&self.event
}
}
impl InteractionLocation for Synthetic<Touch> {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.event.client_x().into(), self.event.client_y().into())
}
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(self.event.screen_x().into(), self.event.screen_y().into())
}
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(self.event.page_x().into(), self.event.page_y().into())
}
}
impl WebEventExt for dioxus_html::TouchData {
type WebEvent = web_sys::TouchEvent;
#[inline(always)]
fn try_as_web_event(&self) -> Option<web_sys::TouchEvent> {
self.downcast::<web_sys::TouchEvent>().cloned()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/hydration/hydrate.rs | packages/web/src/hydration/hydrate.rs | //! When hydrating streaming components:
//! 1. Just hydrate the template on the outside
//! 2. As we render the virtual dom initially, keep track of the server ids of the suspense boundaries
//! 3. Register a callback for dx_hydrate(id, data) that takes some new data, reruns the suspense boundary with that new data and then rehydrates the node
use crate::dom::WebsysDom;
use dioxus_core::{
AttributeValue, DynamicNode, ElementId, ScopeId, ScopeState, SuspenseBoundaryProps,
SuspenseContext, TemplateNode, VNode, VirtualDom,
};
use dioxus_fullstack_core::HydrationContext;
use futures_channel::mpsc::UnboundedReceiver;
use std::fmt::Write;
use RehydrationError::*;
use super::SuspenseMessage;
#[derive(Debug)]
#[non_exhaustive]
pub(crate) enum RehydrationError {
/// The client tried to rehydrate a vnode before the dom was built
VNodeNotInitialized,
/// The client tried to rehydrate a suspense boundary that was not mounted on the server
SuspenseHydrationIdNotFound,
/// The client tried to rehydrate a dom id that was not found on the server
ElementNotFound,
}
#[derive(Debug)]
struct SuspenseHydrationIdsNode {
/// The scope id of the suspense boundary
scope_id: ScopeId,
/// Children of this node
children: Vec<SuspenseHydrationIdsNode>,
}
impl SuspenseHydrationIdsNode {
fn new(scope_id: ScopeId) -> Self {
Self {
scope_id,
children: Vec::new(),
}
}
fn traverse(&self, path: &[u32]) -> Option<&Self> {
match path {
[] => Some(self),
[id, rest @ ..] => self.children.get(*id as usize)?.traverse(rest),
}
}
fn traverse_mut(&mut self, path: &[u32]) -> Option<&mut Self> {
match path {
[] => Some(self),
[id, rest @ ..] => self.children.get_mut(*id as usize)?.traverse_mut(rest),
}
}
}
/// Streaming hydration happens in waves. The server assigns suspense hydrations ids based on the order
/// the suspense boundaries are discovered in which should be consistent on the client and server.
///
/// This struct keeps track of the order the suspense boundaries are discovered in on the client so we can map the id in the dom to the scope we need to rehydrate.
///
/// Diagram: <https://excalidraw.com/#json=4NxmW90g0207Y62lESxfF,vP_Yn6j7k23utq2HZIsuiw>
#[derive(Default, Debug)]
pub(crate) struct SuspenseHydrationIds {
/// A dense mapping from traversal order to the scope id of the suspense boundary
/// The suspense boundary may be unmounted if the component was removed after partial hydration on the client
children: Vec<SuspenseHydrationIdsNode>,
current_path: Vec<u32>,
}
impl SuspenseHydrationIds {
/// Add a suspense boundary to the list of suspense boundaries. This should only be called on the root scope after the first rebuild (which happens on the server) and on suspense boundaries that are resolved from the server.
/// Running this on a scope that is only created on the client may cause hydration issues.
fn add_suspense_boundary(&mut self, id: ScopeId) {
match self.current_path.as_slice() {
// This is a root node, add the new node
[] => {
self.children.push(SuspenseHydrationIdsNode::new(id));
}
// This isn't a root node, traverse into children and add the new node
[first_index, rest @ ..] => {
let child_node = self.children[*first_index as usize]
.traverse_mut(rest)
.unwrap();
child_node.children.push(SuspenseHydrationIdsNode::new(id));
}
}
}
/// Get the scope id of the suspense boundary from the id in the dom
fn get_suspense_boundary(&self, path: &[u32]) -> Option<ScopeId> {
let root = self.children.get(path[0] as usize)?;
root.traverse(&path[1..]).map(|node| node.scope_id)
}
}
impl WebsysDom {
pub fn rehydrate_streaming(&mut self, message: SuspenseMessage, dom: &mut VirtualDom) {
if let Err(err) = self.rehydrate_streaming_inner(message, dom) {
tracing::error!("Rehydration failed. {:?}", err);
}
}
fn rehydrate_streaming_inner(
&mut self,
message: SuspenseMessage,
dom: &mut VirtualDom,
) -> Result<(), RehydrationError> {
let SuspenseMessage {
suspense_path,
data,
#[cfg(debug_assertions)]
debug_types,
#[cfg(debug_assertions)]
debug_locations,
} = message;
let document = web_sys::window().unwrap().document().unwrap();
// Before we start rehydrating the suspense boundary we need to check that the suspense boundary exists. It may have been removed on the client.
let resolved_suspense_id = path_to_resolved_suspense_id(&suspense_path);
let resolved_suspense_element = document
.get_element_by_id(&resolved_suspense_id)
.ok_or(RehydrationError::ElementNotFound)?;
// First convert the dom id into a scope id based on the discovery order of the suspense boundaries.
// This may fail if the id is not parsable, or if the suspense boundary was removed after partial hydration on the client.
let id = self
.suspense_hydration_ids
.get_suspense_boundary(&suspense_path)
.ok_or(RehydrationError::SuspenseHydrationIdNotFound)?;
// Push the new nodes onto the stack
let mut current_child = resolved_suspense_element.first_child();
let mut children = Vec::new();
while let Some(node) = current_child {
children.push(node.clone());
current_child = node.next_sibling();
self.interpreter.base().push_root(node);
}
#[cfg(not(debug_assertions))]
let debug_types = None;
#[cfg(not(debug_assertions))]
let debug_locations = None;
let server_data = HydrationContext::from_serialized(&data, debug_types, debug_locations);
// If the server serialized an error into the suspense boundary, throw it on the client so that it bubbles up to the nearest error boundary
if let Some(error) = server_data.error_entry().get().ok().flatten() {
dom.in_runtime(|| dom.runtime().throw_error(id, error));
}
server_data.in_context(|| {
// rerun the scope with the new data
SuspenseBoundaryProps::resolve_suspense(
id,
dom,
self,
|to| {
// Switch to only writing templates
to.skip_mutations = true;
},
children.len(),
);
self.skip_mutations = false;
});
// Flush the mutations that will swap the placeholder nodes with the resolved nodes
self.flush_edits();
// Remove the streaming div
resolved_suspense_element.remove();
let Some(root_scope) = dom.get_scope(id) else {
// If the scope was removed on the client, we may not be able to rehydrate it, but this shouldn't cause an error
return Ok(());
};
// As we hydrate the suspense boundary, set the current path to the path of the suspense boundary
self.suspense_hydration_ids
.current_path
.clone_from(&suspense_path);
self.start_hydration_at_scope(root_scope, dom, children)?;
Ok(())
}
fn start_hydration_at_scope(
&mut self,
scope: &ScopeState,
dom: &VirtualDom,
under: Vec<web_sys::Node>,
) -> Result<(), RehydrationError> {
let mut ids = Vec::new();
let mut to_mount = Vec::new();
// Recursively rehydrate the nodes under the scope
self.rehydrate_scope(scope, dom, &mut ids, &mut to_mount)?;
self.interpreter.base().hydrate(ids, under);
#[cfg(feature = "mounted")]
for id in to_mount {
self.send_mount_event(id);
}
Ok(())
}
pub fn rehydrate(
&mut self,
vdom: &VirtualDom,
) -> Result<UnboundedReceiver<SuspenseMessage>, RehydrationError> {
let (mut tx, rx) = futures_channel::mpsc::unbounded();
let closure =
move |path: Vec<u32>,
data: js_sys::Uint8Array,
#[allow(unused)] debug_types: Option<Vec<String>>,
#[allow(unused)] debug_locations: Option<Vec<String>>| {
let data = data.to_vec();
_ = tx.start_send(SuspenseMessage {
suspense_path: path,
data,
#[cfg(debug_assertions)]
debug_types,
#[cfg(debug_assertions)]
debug_locations,
});
};
let closure = wasm_bindgen::closure::Closure::new(closure);
dioxus_interpreter_js::minimal_bindings::register_rehydrate_chunk_for_streaming_debug(
&closure,
);
closure.forget();
// Rehydrate the root scope that was rendered on the server. We will likely run into suspense boundaries.
// Any suspense boundaries we run into are stored for hydration later.
self.start_hydration_at_scope(vdom.base_scope(), vdom, vec![self.root.clone()])?;
Ok(rx)
}
fn rehydrate_scope(
&mut self,
scope: &ScopeState,
dom: &VirtualDom,
ids: &mut Vec<u32>,
to_mount: &mut Vec<ElementId>,
) -> Result<(), RehydrationError> {
// If this scope is a suspense boundary that is pending, add it to the list of pending suspense boundaries
if let Some(suspense) =
SuspenseContext::downcast_suspense_boundary_from_scope(&dom.runtime(), scope.id())
{
if suspense.has_suspended_tasks() {
self.suspense_hydration_ids
.add_suspense_boundary(scope.id());
}
}
self.rehydrate_vnode(dom, scope.root_node(), ids, to_mount)
}
fn rehydrate_vnode(
&mut self,
dom: &VirtualDom,
vnode: &VNode,
ids: &mut Vec<u32>,
to_mount: &mut Vec<ElementId>,
) -> Result<(), RehydrationError> {
for (i, root) in vnode.template.roots.iter().enumerate() {
self.rehydrate_template_node(
dom,
vnode,
root,
ids,
to_mount,
Some(vnode.mounted_root(i, dom).ok_or(VNodeNotInitialized)?),
)?;
}
Ok(())
}
fn rehydrate_template_node(
&mut self,
dom: &VirtualDom,
vnode: &VNode,
node: &TemplateNode,
ids: &mut Vec<u32>,
to_mount: &mut Vec<ElementId>,
root_id: Option<ElementId>,
) -> Result<(), RehydrationError> {
match node {
TemplateNode::Element {
children, attrs, ..
} => {
let mut mounted_id = root_id;
for attr in *attrs {
if let dioxus_core::TemplateAttribute::Dynamic { id } = attr {
let attributes = &*vnode.dynamic_attrs[*id];
let id = vnode
.mounted_dynamic_attribute(*id, dom)
.ok_or(VNodeNotInitialized)?;
// We always need to hydrate the node even if the attributes are empty so we have
// a mount for the node later. This could be spread attributes that are currently empty,
// but will be filled later
mounted_id = Some(id);
for attribute in attributes {
let value = &attribute.value;
if let AttributeValue::Listener(_) = value {
if attribute.name == "onmounted" {
to_mount.push(id);
}
}
}
}
}
if let Some(id) = mounted_id {
ids.push(id.0 as u32);
}
if !children.is_empty() {
for child in *children {
self.rehydrate_template_node(dom, vnode, child, ids, to_mount, None)?;
}
}
}
TemplateNode::Dynamic { id } => self.rehydrate_dynamic_node(
dom,
&vnode.dynamic_nodes[*id],
*id,
vnode,
ids,
to_mount,
)?,
TemplateNode::Text { .. } => {
if let Some(id) = root_id {
ids.push(id.0 as u32);
}
}
}
Ok(())
}
fn rehydrate_dynamic_node(
&mut self,
dom: &VirtualDom,
dynamic: &DynamicNode,
dynamic_node_index: usize,
vnode: &VNode,
ids: &mut Vec<u32>,
to_mount: &mut Vec<ElementId>,
) -> Result<(), RehydrationError> {
match dynamic {
dioxus_core::DynamicNode::Text(_) | dioxus_core::DynamicNode::Placeholder(_) => {
ids.push(
vnode
.mounted_dynamic_node(dynamic_node_index, dom)
.ok_or(VNodeNotInitialized)?
.0 as u32,
);
}
dioxus_core::DynamicNode::Component(comp) => {
let scope = comp
.mounted_scope(dynamic_node_index, vnode, dom)
.ok_or(VNodeNotInitialized)?;
self.rehydrate_scope(scope, dom, ids, to_mount)?;
}
dioxus_core::DynamicNode::Fragment(fragment) => {
for vnode in fragment {
self.rehydrate_vnode(dom, vnode, ids, to_mount)?;
}
}
}
Ok(())
}
}
fn write_comma_separated(id: &[u32], into: &mut String) {
let mut iter = id.iter();
if let Some(first) = iter.next() {
write!(into, "{first}").unwrap();
}
for id in iter {
write!(into, ",{id}").unwrap();
}
}
fn path_to_resolved_suspense_id(path: &[u32]) -> String {
let mut resolved_suspense_id_formatted = String::from("ds-");
write_comma_separated(path, &mut resolved_suspense_id_formatted);
resolved_suspense_id_formatted.push_str("-r");
resolved_suspense_id_formatted
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/web/src/hydration/mod.rs | packages/web/src/hydration/mod.rs | #[cfg(feature = "hydrate")]
mod hydrate;
#[cfg(feature = "hydrate")]
#[allow(unused)]
pub use hydrate::*;
/// The message sent from the server to the client to hydrate a suspense boundary
#[derive(Debug)]
pub(crate) struct SuspenseMessage {
#[cfg(feature = "hydrate")]
/// The path to the suspense boundary. Each element in the path is an index into the children of the suspense boundary (or the root node) in the order they are first created
suspense_path: Vec<u32>,
#[cfg(feature = "hydrate")]
/// The data to hydrate the suspense boundary with
data: Vec<u8>,
#[cfg(feature = "hydrate")]
#[cfg(debug_assertions)]
/// The type names of the data
debug_types: Option<Vec<String>>,
#[cfg(feature = "hydrate")]
#[cfg(debug_assertions)]
/// The location of the data in the source code
debug_locations: Option<Vec<String>>,
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.