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/stores/src/impls/vec.rs | packages/stores/src/impls/vec.rs | use crate::store::Store;
use dioxus_signals::Writable;
impl<Lens: Writable<Target = Vec<T>> + 'static, T: 'static> Store<Vec<T>, Lens> {
/// Pushes an item to the end of the vector. This will only mark the length of the vector as dirty.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let mut store = use_store(|| vec![1, 2, 3]);
/// store.push(4);
/// ```
pub fn push(&mut self, value: T) {
self.selector().mark_dirty_shallow();
self.selector().write_untracked().push(value);
}
/// Removes an item from the vector at the specified index and returns it. This will mark items after
/// the index and the length of the vector as dirty.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let mut store = use_store(|| vec![1, 2, 3]);
/// let removed = store.remove(1);
/// assert_eq!(removed, 2);
/// ```
pub fn remove(&mut self, index: usize) -> T {
self.selector().mark_dirty_shallow();
self.selector().mark_dirty_at_and_after_index(index);
self.selector().write_untracked().remove(index)
}
/// Inserts an item at the specified index in the vector. This will mark items at and after the index
/// and the length of the vector as dirty.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let mut store = use_store(|| vec![1, 2, 3]);
/// store.insert(1, 4);
/// ```
pub fn insert(&mut self, index: usize, value: T) {
self.selector().mark_dirty_shallow();
self.selector().mark_dirty_at_and_after_index(index);
self.selector().write_untracked().insert(index, value);
}
/// Clears the vector, marking it as dirty.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let mut store = use_store(|| vec![1, 2, 3]);
/// store.clear();
/// ```
pub fn clear(&mut self) {
self.selector().mark_dirty();
self.selector().write_untracked().clear();
}
/// Retains only the elements specified by the predicate. This will only mark the length of the vector
/// and items after the first removed item as dirty.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let mut store = use_store(|| vec![1, 2, 3, 4, 5]);
/// store.retain(|&x| x % 2 == 0);
/// assert_eq!(store.len(), 2);
/// ```
pub fn retain(&mut self, mut f: impl FnMut(&T) -> bool) {
let mut index = 0;
let mut first_removed_index = None;
self.selector().write_untracked().retain(|item| {
let keep = f(item);
if !keep {
first_removed_index = first_removed_index.or(Some(index));
}
index += 1;
keep
});
if let Some(index) = first_removed_index {
self.selector().mark_dirty_shallow();
self.selector().mark_dirty_at_and_after_index(index);
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/index.rs | packages/stores/src/impls/index.rs | //! Additional utilities for indexing into stores.
use std::{
collections::{BTreeMap, HashMap},
hash::Hash,
ops::{self, Index, IndexMut},
};
use crate::{scope::SelectorScope, store::Store, ReadStore};
use dioxus_signals::{
AnyStorage, BorrowError, BorrowMutError, ReadSignal, Readable, UnsyncStorage, Writable,
WriteLock, WriteSignal,
};
/// The way a data structure index into its children based on a key. The selector must use this indexing
/// method consistently to ensure that the same key always maps to the same child.
pub trait IndexSelector<Idx> {
/// Given a selector and an index, scope the selector to the child at the given index.
fn scope_selector<Lens>(selector: SelectorScope<Lens>, index: &Idx) -> SelectorScope<Lens>;
}
impl<T> IndexSelector<usize> for Vec<T> {
fn scope_selector<Lens>(selector: SelectorScope<Lens>, index: &usize) -> SelectorScope<Lens> {
selector.child_unmapped(*index as _)
}
}
impl<T> IndexSelector<usize> for [T] {
fn scope_selector<Lens>(selector: SelectorScope<Lens>, index: &usize) -> SelectorScope<Lens> {
selector.child_unmapped(*index as _)
}
}
impl<K, V, I> IndexSelector<I> for HashMap<K, V>
where
I: Hash,
{
fn scope_selector<Lens>(selector: SelectorScope<Lens>, index: &I) -> SelectorScope<Lens> {
selector.hash_child_unmapped(&index)
}
}
impl<K, V, I> IndexSelector<I> for BTreeMap<K, V>
where
I: Hash,
{
fn scope_selector<Lens>(selector: SelectorScope<Lens>, index: &I) -> SelectorScope<Lens> {
selector.hash_child_unmapped(&index)
}
}
impl<Lens, T> Store<T, Lens> {
/// Index into the store, returning a store that allows access to the item at the given index. The
/// new store will only update when the item at the index changes.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| vec![1, 2, 3]);
/// let indexed_store = store.index(1);
/// // The indexed store can access the store methods of the indexed store.
/// assert_eq!(indexed_store(), 2);
/// ```
pub fn index<Idx>(self, index: Idx) -> Store<T::Output, IndexWrite<Idx, Lens>>
where
T: IndexMut<Idx> + 'static + IndexSelector<Idx>,
Lens: Readable<Target = T> + 'static,
{
T::scope_selector(self.into_selector(), &index)
.map_writer(move |write| IndexWrite { index, write })
.into()
}
}
/// A specific index in a `Readable` / `Writable` type
#[derive(Clone, Copy)]
pub struct IndexWrite<Index, Write> {
index: Index,
write: Write,
}
impl<Index, Write> Readable for IndexWrite<Index, Write>
where
Write: Readable,
Write::Target: ops::Index<Index> + 'static,
Index: Clone,
{
type Target = <Write::Target as ops::Index<Index>>::Output;
type Storage = Write::Storage;
fn try_read_unchecked(&self) -> Result<dioxus_signals::ReadableRef<'static, Self>, BorrowError>
where
Self::Target: 'static,
{
self.write.try_read_unchecked().map(|value| {
Self::Storage::map(value, |value: &Write::Target| {
value.index(self.index.clone())
})
})
}
fn try_peek_unchecked(&self) -> Result<dioxus_signals::ReadableRef<'static, Self>, BorrowError>
where
Self::Target: 'static,
{
self.write.try_peek_unchecked().map(|value| {
Self::Storage::map(value, |value: &Write::Target| {
value.index(self.index.clone())
})
})
}
fn subscribers(&self) -> dioxus_core::Subscribers
where
Self::Target: 'static,
{
self.write.subscribers()
}
}
impl<Index, Write> Writable for IndexWrite<Index, Write>
where
Write: Writable,
Write::Target: ops::IndexMut<Index> + 'static,
Index: Clone,
{
type WriteMetadata = Write::WriteMetadata;
fn try_write_unchecked(
&self,
) -> Result<dioxus_signals::WritableRef<'static, Self>, BorrowMutError>
where
Self::Target: 'static,
{
self.write.try_write_unchecked().map(|value| {
WriteLock::map(value, |value: &mut Write::Target| {
value.index_mut(self.index.clone())
})
})
}
}
impl<Idx, T, Write> ::std::convert::From<Store<T, IndexWrite<Idx, Write>>>
for Store<T, WriteSignal<T>>
where
Write: Writable<Storage = UnsyncStorage> + 'static,
Write::WriteMetadata: 'static,
Write::Target: ops::IndexMut<Idx, Output = T> + 'static,
Idx: Clone + 'static,
T: 'static,
{
fn from(value: Store<T, IndexWrite<Idx, Write>>) -> Self {
value
.into_selector()
.map_writer(|writer| WriteSignal::new(writer))
.into()
}
}
impl<Idx, T, Write> ::std::convert::From<Store<T, IndexWrite<Idx, Write>>> for ReadStore<T>
where
Write: Readable<Storage = UnsyncStorage> + 'static,
Write::Target: ops::Index<Idx, Output = T> + 'static,
Idx: Clone + 'static,
T: 'static,
{
fn from(value: Store<T, IndexWrite<Idx, Write>>) -> Self {
value
.into_selector()
.map_writer(|writer| ReadSignal::new(writer))
.into()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/result.rs | packages/stores/src/impls/result.rs | use std::fmt::Debug;
use crate::{store::Store, MappedStore};
use dioxus_signals::{Readable, ReadableExt, Writable};
impl<Lens, T, E> Store<Result<T, E>, Lens>
where
Lens: Readable<Target = Result<T, E>> + 'static,
T: 'static,
E: 'static,
{
/// Checks if the `Result` is `Ok`. This will only track the shallow state of the `Result`. It will
/// only cause a re-run if the `Result` could change from `Err` to `Ok` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<u32, ()>(42));
/// assert!(store.is_ok());
/// ```
pub fn is_ok(&self) -> bool {
self.selector().track_shallow();
self.selector().peek().is_ok()
}
/// Returns true if the result is Ok and the closure returns true. This will always track the shallow
/// state of the and will track the inner state of the enum if the enum is Ok.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<u32, ()>(42));
/// assert!(store.is_ok_and(|v| *v == 42));
/// ```
pub fn is_ok_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
self.selector().track_shallow();
let value = self.selector().peek();
if let Ok(v) = &*value {
self.selector().track();
f(v)
} else {
false
}
}
/// Checks if the `Result` is `Err`. This will only track the shallow state of the `Result`. It will
/// only cause a re-run if the `Result` could change from `Ok` to `Err` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Err::<(), u32>(42));
/// assert!(store.is_err());
/// ```
pub fn is_err(&self) -> bool {
self.selector().track_shallow();
self.selector().peek().is_err()
}
/// Returns true if the result is Err and the closure returns true. This will always track the shallow
/// state of the and will track the inner state of the enum if the enum is Err.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Err::<(), u32>(42));
/// assert!(store.is_err_and(|v| *v == 42));
/// ```
pub fn is_err_and(&self, f: impl FnOnce(&E) -> bool) -> bool {
self.selector().track_shallow();
let value = self.selector().peek();
if let Err(e) = &*value {
self.selector().track();
f(e)
} else {
false
}
}
/// Converts `Store<Result<T, E>>` into `Option<Store<T>>`, discarding the error if present. This will
/// only track the shallow state of the `Result`. It will only cause a re-run if the `Result` could
/// change from `Err` to `Ok` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<u32, ()>(42));
/// match store.ok() {
/// Some(ok_store) => assert_eq!(ok_store(), 42),
/// None => panic!("Expected Ok"),
/// }
/// ```
pub fn ok(self) -> Option<MappedStore<T, Lens>> {
let map: fn(&Result<T, E>) -> &T = |value| {
value.as_ref().unwrap_or_else(|_| {
panic!("Tried to access `ok` on an Err value");
})
};
let map_mut: fn(&mut Result<T, E>) -> &mut T = |value| {
value.as_mut().unwrap_or_else(|_| {
panic!("Tried to access `ok` on an Err value");
})
};
self.is_ok()
.then(|| self.into_selector().child(0, map, map_mut).into())
}
/// Converts `Store<Result<T, E>>` into `Option<Store<E>>`, discarding the success if present. This will
/// only track the shallow state of the `Result`. It will only cause a re-run if the `Result` could
/// change from `Ok` to `Err` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Err::<(), u32>(42));
/// match store.err() {
/// Some(err_store) => assert_eq!(err_store(), 42),
/// None => panic!("Expected Err"),
/// }
/// ```
pub fn err(self) -> Option<MappedStore<E, Lens>>
where
Lens: Writable<Target = Result<T, E>> + 'static,
{
self.is_err().then(|| {
let map: fn(&Result<T, E>) -> &E = |value| match value {
Ok(_) => panic!("Tried to access `err` on an Ok value"),
Err(e) => e,
};
let map_mut: fn(&mut Result<T, E>) -> &mut E = |value| match value {
Ok(_) => panic!("Tried to access `err` on an Ok value"),
Err(e) => e,
};
self.into_selector().child(1, map, map_mut).into()
})
}
/// Transposes the `Store<Result<T, E>>` into a `Result<Store<T>, Store<E>>`. This will only track the
/// shallow state of the `Result`. It will only cause a re-run if the `Result` could change from `Err` to
/// `Ok` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<u32, ()>(42));
/// match store.transpose() {
/// Ok(ok_store) => assert_eq!(ok_store(), 42),
/// Err(err_store) => assert_eq!(err_store(), ()),
/// }
/// ```
#[allow(clippy::result_large_err)]
pub fn transpose(self) -> Result<MappedStore<T, Lens>, MappedStore<E, Lens>>
where
Lens: Writable<Target = Result<T, E>> + 'static,
{
if self.is_ok() {
let map: fn(&Result<T, E>) -> &T = |value| match value {
Ok(t) => t,
Err(_) => panic!("Tried to access `ok` on an Err value"),
};
let map_mut: fn(&mut Result<T, E>) -> &mut T = |value| match value {
Ok(t) => t,
Err(_) => panic!("Tried to access `ok` on an Err value"),
};
Ok(self.into_selector().child(0, map, map_mut).into())
} else {
let map: fn(&Result<T, E>) -> &E = |value| match value {
Ok(_) => panic!("Tried to access `err` on an Ok value"),
Err(e) => e,
};
let map_mut: fn(&mut Result<T, E>) -> &mut E = |value| match value {
Ok(_) => panic!("Tried to access `err` on an Ok value"),
Err(e) => e,
};
Err(self.into_selector().child(1, map, map_mut).into())
}
}
/// Unwraps the `Result` and returns a `Store<T>`. This will only track the shallow state of the `Result`.
/// It will only cause a re-run if the `Result` could change from `Err` to `Ok` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<u32, ()>(42));
/// let unwrapped = store.unwrap();
/// assert_eq!(unwrapped(), 42);
/// ```
pub fn unwrap(self) -> MappedStore<T, Lens>
where
Lens: Writable<Target = Result<T, E>> + 'static,
E: Debug,
{
self.transpose().unwrap()
}
/// Expects the `Result` to be `Ok` and returns a `Store<T>`. If the value is `Err`, this will panic with `msg`.
/// This will only track the shallow state of the `Result`. It will only cause a re-run if the `Result` could
/// change from `Err` to `Ok` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<u32, ()>(42));
/// let unwrapped = store.expect("Expected Ok");
/// assert_eq!(unwrapped(), 42);
/// ```
pub fn expect(self, msg: &str) -> MappedStore<T, Lens>
where
Lens: Writable<Target = Result<T, E>> + 'static,
E: Debug,
{
self.transpose().expect(msg)
}
/// Unwraps the error variant of the `Result`. This will only track the shallow state of the `Result`.
/// It will only cause a re-run if the `Result` could change from `Ok` to `Err` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Err::<(), u32>(42));
/// let unwrapped_err = store.unwrap_err();
/// assert_eq!(unwrapped_err(), 42);
/// ```
pub fn unwrap_err(self) -> MappedStore<E, Lens>
where
Lens: Writable<Target = Result<T, E>> + 'static,
T: Debug,
{
self.transpose().unwrap_err()
}
/// Expects the `Result` to be `Err` and returns a `Store<E>`. If the value is `Ok`, this will panic with `msg`.
/// This will only track the shallow state of the `Result`. It will only cause a re-run if the `Result` could
/// change from `Ok` to `Err` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Err::<(), u32>(42));
/// let unwrapped_err = store.expect_err("Expected Err");
/// assert_eq!(unwrapped_err(), 42);
/// ```
pub fn expect_err(self, msg: &str) -> MappedStore<E, Lens>
where
Lens: Writable<Target = Result<T, E>> + 'static,
T: Debug,
{
self.transpose().expect_err(msg)
}
/// Call the function with a reference to the inner value if it is Ok. This will always track the shallow
/// state of the and will track the inner state of the enum if the enum is Ok.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<u32, ()>(42)).inspect(|v| println!("{v}"));
/// ```
pub fn inspect(self, f: impl FnOnce(&T)) -> Self
where
Lens: Writable<Target = Result<T, E>> + 'static,
{
{
self.selector().track_shallow();
let value = self.selector().peek();
if let Ok(value) = &*value {
self.selector().track();
f(value);
}
}
self
}
/// Call the function with a mutable reference to the inner value if it is Err. This will always track the shallow
/// state of the `Result` and will track the inner state of the enum if the enum is Err.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Err::<(), u32>(42)).inspect_err(|v| println!("{v}"));
/// ```
pub fn inspect_err(self, f: impl FnOnce(&E)) -> Self
where
Lens: Writable<Target = Result<T, E>> + 'static,
{
{
self.selector().track_shallow();
let value = self.selector().peek();
if let Err(value) = &*value {
self.selector().track();
f(value);
}
}
self
}
/// Transpose the store then coerce the contents of the Result with deref. This will only track the shallow state of the `Result`. It will
/// only cause a re-run if the `Result` could change from `Err` to `Ok` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Ok::<Box<u32>, ()>(Box::new(42)));
/// let derefed = store.as_deref().unwrap();
/// assert_eq!(derefed(), 42);
/// ```
pub fn as_deref(self) -> Result<MappedStore<T::Target, Lens>, MappedStore<E, Lens>>
where
Lens: Writable<Target = Result<T, E>> + 'static,
T: std::ops::DerefMut,
{
if self.is_ok() {
let map: fn(&Result<T, E>) -> &T::Target = |value| match value {
Ok(t) => t.deref(),
Err(_) => panic!("Tried to access `ok` on an Err value"),
};
let map_mut: fn(&mut Result<T, E>) -> &mut T::Target = |value| match value {
Ok(t) => t.deref_mut(),
Err(_) => panic!("Tried to access `ok` on an Err value"),
};
Ok(self.into_selector().child(0, map, map_mut).into())
} else {
let map: fn(&Result<T, E>) -> &E = |value| match value {
Ok(_) => panic!("Tried to access `err` on an Ok value"),
Err(e) => e,
};
let map_mut: fn(&mut Result<T, E>) -> &mut E = |value| match value {
Ok(_) => panic!("Tried to access `err` on an Ok value"),
Err(e) => e,
};
Err(self.into_selector().child(1, map, map_mut).into())
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/btreemap.rs | packages/stores/src/impls/btreemap.rs | //! Additional utilities for `BTreeMap` stores.
use std::{
borrow::Borrow, collections::BTreeMap, hash::Hash, iter::FusedIterator, panic::Location,
};
use crate::{store::Store, ReadStore};
use dioxus_signals::{
AnyStorage, BorrowError, BorrowMutError, ReadSignal, Readable, ReadableExt, UnsyncStorage,
Writable, WriteLock, WriteSignal,
};
use generational_box::ValueDroppedError;
impl<Lens: Readable<Target = BTreeMap<K, V>> + 'static, K: 'static, V: 'static>
Store<BTreeMap<K, V>, Lens>
{
/// Get the length of the BTreeMap. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// assert_eq!(store.len(), 0);
/// store.insert(0, "value".to_string());
/// assert_eq!(store.len(), 1);
/// ```
pub fn len(&self) -> usize {
self.selector().track_shallow();
self.selector().peek().len()
}
/// Check if the BTreeMap is empty. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// assert!(store.is_empty());
/// store.insert(0, "value".to_string());
/// assert!(!store.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.selector().track_shallow();
self.selector().peek().is_empty()
}
/// Iterate over the current entries in the BTreeMap, returning a tuple of the key and a store for the value. This method
/// will track the store shallowly and only cause re-runs when items are added or removed from the map, not when existing
/// values are modified.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// store.insert(0, "value1".to_string());
/// store.insert(1, "value2".to_string());
/// for (key, value_store) in store.iter() {
/// println!("{}: {}", key, value_store.read());
/// }
/// ```
pub fn iter(
&self,
) -> impl ExactSizeIterator<Item = (K, Store<V, GetWrite<K, Lens>>)>
+ DoubleEndedIterator
+ FusedIterator
+ '_
where
K: Hash + Ord + Clone,
Lens: Clone,
{
self.selector().track_shallow();
let keys: Vec<_> = self.selector().peek_unchecked().keys().cloned().collect();
keys.into_iter().map(move |key| {
let value = self.clone().get_unchecked(key.clone());
(key, value)
})
}
/// Get an iterator over the values in the BTreeMap. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// store.insert(0, "value1".to_string());
/// store.insert(1, "value2".to_string());
/// for value_store in store.values() {
/// println!("{}", value_store.read());
/// }
/// ```
pub fn values(
&self,
) -> impl ExactSizeIterator<Item = Store<V, GetWrite<K, Lens>>>
+ DoubleEndedIterator
+ FusedIterator
+ '_
where
K: Hash + Ord + Clone,
Lens: Clone,
{
self.selector().track_shallow();
let keys = self.selector().peek().keys().cloned().collect::<Vec<_>>();
keys.into_iter()
.map(move |key| self.clone().get_unchecked(key))
}
/// Insert a new key-value pair into the BTreeMap. This method will mark the store as shallowly dirty, causing
/// re-runs of any reactive scopes that depend on the shape of the map.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// assert!(store.get(0).is_none());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get(0).unwrap().cloned(), "value".to_string());
/// ```
pub fn insert(&mut self, key: K, value: V)
where
K: Ord,
Lens: Writable,
{
// TODO: This method was released in 0.7 without the hash bound so we don't have a way
// to mark only the existing value as dirty. Instead we need to check if the value already exists
// in the map and mark the whole map as dirty if it does.
// In the 0.8 release, we should change this method to only mark the existing value as dirty.
if self.peek().contains_key(&key) {
self.selector().mark_dirty();
} else {
self.selector().mark_dirty_shallow();
}
self.selector().write_untracked().insert(key, value);
}
/// Remove a key-value pair from the BTreeMap. This method will mark the store as shallowly dirty, causing
/// re-runs of any reactive scopes that depend on the shape of the map or the value of the removed key.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get(0).unwrap().cloned(), "value".to_string());
/// let removed_value = store.remove(&0);
/// assert_eq!(removed_value, Some("value".to_string()));
/// assert!(store.get(0).is_none());
/// ```
pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
where
Q: ?Sized + Ord + 'static,
K: Borrow<Q> + Ord,
Lens: Writable,
{
self.selector().mark_dirty_shallow();
self.selector().write_untracked().remove(key)
}
/// Clear the BTreeMap, removing all key-value pairs. This method will mark the store as shallowly dirty,
/// causing re-runs of any reactive scopes that depend on the shape of the map.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// store.insert(1, "value1".to_string());
/// store.insert(2, "value2".to_string());
/// assert_eq!(store.len(), 2);
/// store.clear();
/// assert!(store.is_empty());
/// ```
pub fn clear(&mut self)
where
Lens: Writable,
{
self.selector().mark_dirty_shallow();
self.selector().write_untracked().clear();
}
/// Retain only the key-value pairs that satisfy the given predicate. This method will mark the store as shallowly dirty,
/// causing re-runs of any reactive scopes that depend on the shape of the map or the values retained.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// store.insert(1, "value1".to_string());
/// store.insert(2, "value2".to_string());
/// store.retain(|key, value| *key == 1);
/// assert_eq!(store.len(), 1);
/// assert!(store.get(1).is_some());
/// assert!(store.get(2).is_none());
/// ```
pub fn retain(&mut self, mut f: impl FnMut(&K, &V) -> bool)
where
Lens: Writable,
K: Ord,
{
self.selector().mark_dirty_shallow();
self.selector().write_untracked().retain(|k, v| f(k, v));
}
/// Check if the BTreeMap contains a key. This method will track the store shallowly and only cause
/// re-runs when items are added or removed from the map, not when existing values are modified.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// assert!(!store.contains_key(&0));
/// store.insert(0, "value".to_string());
/// assert!(store.contains_key(&0));
/// ```
pub fn contains_key<Q>(&self, key: &Q) -> bool
where
Q: ?Sized + Ord + 'static,
K: Borrow<Q> + Ord,
{
self.selector().track_shallow();
self.selector().peek().contains_key(key)
}
/// Get a store for the value associated with the given key. This method creates a new store scope
/// that tracks just changes to the value associated with the key.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// assert!(store.get(0).is_none());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get(0).unwrap().cloned(), "value".to_string());
/// ```
pub fn get<Q>(self, key: Q) -> Option<Store<V, GetWrite<Q, Lens>>>
where
Q: Hash + Ord + 'static,
K: Borrow<Q> + Ord,
{
self.contains_key(&key).then(|| self.get_unchecked(key))
}
/// Get a store for the value associated with the given key without checking if the key exists.
/// This method creates a new store scope that tracks just changes to the value associated with the key.
///
/// This is not unsafe, but it will panic when you try to read the value if it does not exist.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// use dioxus::prelude::*;
/// use std::collections::BTreeMap;
/// let mut store = use_store(|| BTreeMap::new());
/// store.insert(0, "value".to_string());
/// assert_eq!(store.get_unchecked(0).cloned(), "value".to_string());
/// ```
#[track_caller]
pub fn get_unchecked<Q>(self, key: Q) -> Store<V, GetWrite<Q, Lens>>
where
Q: Hash + Ord + 'static,
K: Borrow<Q> + Ord,
{
let created = std::panic::Location::caller();
self.into_selector()
.hash_child_unmapped(key.borrow())
.map_writer(move |writer| GetWrite {
index: key,
write: writer,
created,
})
.into()
}
}
/// A specific index in a `Readable` / `Writable` BTreeMap
#[derive(Clone, Copy)]
pub struct GetWrite<Index, Write> {
index: Index,
write: Write,
created: &'static Location<'static>,
}
impl<Index, Write, K, V> Readable for GetWrite<Index, Write>
where
Write: Readable<Target = BTreeMap<K, V>>,
Index: Ord + 'static,
K: Borrow<Index> + Ord + 'static,
{
type Target = V;
type Storage = Write::Storage;
fn try_read_unchecked(&self) -> Result<dioxus_signals::ReadableRef<'static, Self>, BorrowError>
where
Self::Target: 'static,
{
self.write.try_read_unchecked().and_then(|value| {
Self::Storage::try_map(value, |value: &Write::Target| value.get(&self.index))
.ok_or_else(|| BorrowError::Dropped(ValueDroppedError::new(self.created)))
})
}
fn try_peek_unchecked(&self) -> Result<dioxus_signals::ReadableRef<'static, Self>, BorrowError>
where
Self::Target: 'static,
{
self.write.try_peek_unchecked().and_then(|value| {
Self::Storage::try_map(value, |value: &Write::Target| value.get(&self.index))
.ok_or_else(|| BorrowError::Dropped(ValueDroppedError::new(self.created)))
})
}
fn subscribers(&self) -> dioxus_core::Subscribers
where
Self::Target: 'static,
{
self.write.subscribers()
}
}
impl<Index, Write, K, V> Writable for GetWrite<Index, Write>
where
Write: Writable<Target = BTreeMap<K, V>>,
Index: Ord + 'static,
K: Borrow<Index> + Ord + 'static,
{
type WriteMetadata = Write::WriteMetadata;
fn try_write_unchecked(
&self,
) -> Result<dioxus_signals::WritableRef<'static, Self>, BorrowMutError>
where
Self::Target: 'static,
{
self.write.try_write_unchecked().and_then(|value| {
WriteLock::filter_map(value, |value: &mut Write::Target| {
value.get_mut(&self.index)
})
.ok_or_else(|| BorrowMutError::Dropped(ValueDroppedError::new(self.created)))
})
}
}
impl<Index, Write, K, V> ::std::convert::From<Store<V, GetWrite<Index, Write>>>
for Store<V, WriteSignal<V>>
where
Write::WriteMetadata: 'static,
Write: Writable<Target = BTreeMap<K, V>, Storage = UnsyncStorage> + 'static,
Index: Ord + 'static,
K: Borrow<Index> + Ord + 'static,
V: 'static,
{
fn from(value: Store<V, GetWrite<Index, Write>>) -> Self {
value
.into_selector()
.map_writer(|writer| WriteSignal::new(writer))
.into()
}
}
impl<Index, Write, K, V> ::std::convert::From<Store<V, GetWrite<Index, Write>>> for ReadStore<V>
where
Write: Readable<Target = BTreeMap<K, V>, Storage = UnsyncStorage> + 'static,
Index: Ord + 'static,
K: Borrow<Index> + Ord + 'static,
V: 'static,
{
fn from(value: Store<V, GetWrite<Index, Write>>) -> Self {
value
.into_selector()
.map_writer(|writer| ReadSignal::new(writer))
.into()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/option.rs | packages/stores/src/impls/option.rs | use std::ops::DerefMut;
use crate::{store::Store, MappedStore};
use dioxus_signals::{Readable, ReadableExt};
impl<Lens: Readable<Target = Option<T>> + 'static, T: 'static> Store<Option<T>, Lens> {
/// Checks if the `Option` is `Some`. This will only track the shallow state of the `Option`. It will
/// only cause a re-run if the `Option` could change from `None` to `Some` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// assert!(store.is_some());
/// ```
pub fn is_some(&self) -> bool {
self.selector().track_shallow();
self.selector().peek().is_some()
}
/// Returns true if the option is Some and the closure returns true. This will always track the shallow
/// state of the and will track the inner state of the enum if the enum is Some.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// assert!(store.is_some_and(|v| *v == 42));
/// ```
pub fn is_some_and(&self, f: impl FnOnce(&T) -> bool) -> bool {
self.selector().track_shallow();
let value = self.selector().peek();
if let Some(v) = &*value {
self.selector().track();
f(v)
} else {
false
}
}
/// Checks if the `Option` is `None`. This will only track the shallow state of the `Option`. It will
/// only cause a re-run if the `Option` could change from `Some` to `None` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| None::<i32>);
/// assert!(store.is_none());
/// ```
pub fn is_none(&self) -> bool {
self.selector().track_shallow();
self.selector().peek().is_none()
}
/// Returns true if the option is None or the closure returns true. This will always track the shallow
/// state of the and will track the inner state of the enum if the enum is Some.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// assert!(store.is_none_or(|v| *v == 42));
/// ```
pub fn is_none_or(&self, f: impl FnOnce(&T) -> bool) -> bool {
self.selector().track_shallow();
let value = self.selector().peek();
if let Some(v) = &*value {
self.selector().track();
f(v)
} else {
true
}
}
/// Transpose the `Store<Option<T>>` into a `Option<Store<T>>`. This will only track the shallow state of the `Option`. It will
/// only cause a re-run if the `Option` could change from `None` to `Some` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// let transposed = store.transpose();
/// match transposed {
/// Some(inner_store) => assert_eq!(inner_store(), 42),
/// None => panic!("Expected Some"),
/// }
/// ```
pub fn transpose(self) -> Option<MappedStore<T, Lens>> {
self.is_some().then(move || {
let map: fn(&Option<T>) -> &T = |value| {
value.as_ref().unwrap_or_else(|| {
panic!("Tried to access `Some` on an Option value");
})
};
let map_mut: fn(&mut Option<T>) -> &mut T = |value| {
value.as_mut().unwrap_or_else(|| {
panic!("Tried to access `Some` on an Option value");
})
};
self.into_selector().child(0, map, map_mut).into()
})
}
/// Unwraps the `Option` and returns a `Store<T>`. This will only track the shallow state of the `Option`. It will
/// only cause a re-run if the `Option` could change from `None` to `Some` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// let unwrapped = store.unwrap();
/// assert_eq!(unwrapped(), 42);
/// ```
pub fn unwrap(self) -> MappedStore<T, Lens> {
self.transpose().unwrap()
}
/// Expects the `Option` to be `Some` and returns a `Store<T>`. If the value is `None`, this will panic with `msg`. This will
/// only track the shallow state of the `Option`. It will only cause a re-run if the `Option` could change from `None`
/// to `Some` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// let unwrapped = store.expect("the answer to life the universe and everything");
/// assert_eq!(unwrapped(), 42);
/// ```
pub fn expect(self, msg: &str) -> MappedStore<T, Lens> {
self.transpose().expect(msg)
}
/// Returns a slice of the contained value, or an empty slice. This will not subscribe to any part of the store.
///
/// # Example
/// ```rust, no_run
/// use dioxus::prelude::*;
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// let slice = store.as_slice();
/// assert_eq!(&*slice.read(), [42]);
/// ```
pub fn as_slice(self) -> MappedStore<[T], Lens> {
let map: fn(&Option<T>) -> &[T] = |value| value.as_slice();
let map_mut: fn(&mut Option<T>) -> &mut [T] = |value| value.as_mut_slice();
self.into_selector().map(map, map_mut).into()
}
/// Transpose the store then coerce the contents of the Option with deref. This will only track the shallow state of the `Option`. It will
/// only cause a re-run if the `Option` could change from `None` to `Some` or vice versa.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(Box::new(42)));
/// let derefed = store.as_deref().unwrap();
/// assert_eq!(derefed(), 42);
/// ```
pub fn as_deref(self) -> Option<MappedStore<T::Target, Lens>>
where
T: DerefMut,
{
self.is_some().then(move || {
let map: fn(&Option<T>) -> &T::Target = |value| {
value
.as_ref()
.unwrap_or_else(|| {
panic!("Tried to access `Some` on an Option value");
})
.deref()
};
let map_mut: fn(&mut Option<T>) -> &mut T::Target = |value| {
value
.as_mut()
.unwrap_or_else(|| {
panic!("Tried to access `Some` on an Option value");
})
.deref_mut()
};
self.into_selector().child(0, map, map_mut).into()
})
}
/// Transpose the store then filter the contents of the Option with a closure. This will always track the shallow
/// state of the and will track the inner state of the enum if the enum is Some.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42));
/// let option = store.filter(|&v| v > 40);
/// let value = option.unwrap();
/// assert_eq!(value(), 42);
/// ```
pub fn filter(self, f: impl FnOnce(&T) -> bool) -> Option<MappedStore<T, Lens>> {
self.is_some_and(f).then(move || {
let map: fn(&Option<T>) -> &T = |value| {
value.as_ref().unwrap_or_else(|| {
panic!("Tried to access `Some` on an Option value");
})
};
let map_mut: fn(&mut Option<T>) -> &mut T = |value| {
value.as_mut().unwrap_or_else(|| {
panic!("Tried to access `Some` on an Option value");
})
};
self.into_selector().child(0, map, map_mut).into()
})
}
/// Call the function with a reference to the inner value if it is Some. This will always track the shallow
/// state of the and will track the inner state of the enum if the enum is Some.
///
/// # Example
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Some(42)).inspect(|v| println!("{v}"));
/// ```
pub fn inspect(self, f: impl FnOnce(&T)) -> Self {
{
self.selector().track_shallow();
let value = self.selector().peek();
if let Some(v) = &*value {
self.selector().track();
f(v);
}
}
self
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/mod.rs | packages/stores/src/impls/mod.rs | pub mod btreemap;
mod deref;
pub mod hashmap;
pub mod index;
mod option;
mod result;
mod slice;
mod vec;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/src/impls/deref.rs | packages/stores/src/impls/deref.rs | use std::ops::DerefMut;
use crate::{store::Store, MappedStore};
use dioxus_signals::Readable;
impl<Lens, T> Store<T, Lens>
where
Lens: Readable<Target = T> + 'static,
T: DerefMut + 'static,
{
/// Returns a store that dereferences the original value. The dereferenced store shares the same
/// subscriptions and tracking as the original store, but allows you to access the methods of the underlying type.
///
/// # Example
///
/// ```rust, no_run
/// use dioxus_stores::*;
/// let store = use_store(|| Box::new(vec![1, 2, 3]));
/// let deref_store = store.deref();
/// // The dereferenced store can access the store methods of the underlying type.
/// assert_eq!(deref_store.len(), 3);
/// ```
pub fn deref(self) -> MappedStore<T::Target, Lens> {
let map: fn(&T) -> &T::Target = |value| value.deref();
let map_mut: fn(&mut T) -> &mut T::Target = |value| value.deref_mut();
self.into_selector().map(map, map_mut).into()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/tests/marco.rs | packages/stores/tests/marco.rs | #[allow(unused)]
#[allow(clippy::disallowed_names)]
mod macro_tests {
use dioxus_signals::*;
use dioxus_stores::*;
use std::collections::HashMap;
fn derive_unit() {
#[derive(Store)]
struct TodoItem;
}
fn derive_struct() {
#[derive(Store)]
struct TodoItem {
checked: bool,
contents: String,
}
#[store]
impl Store<TodoItem> {
fn is_checked(&self) -> bool {
self.checked().cloned()
}
fn check(&mut self) {
self.checked().set(true);
}
}
let mut 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();
let checked: bool = checked();
let contents: String = 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();
let is_checked = store.is_checked();
store.check();
}
fn derive_generic_struct() {
#[derive(Store)]
struct Item<T> {
checked: bool,
contents: T,
}
#[store]
impl<T> Store<Item<T>> {
fn is_checked(&self) -> bool
where
T: 'static,
{
self.checked().cloned()
}
fn check(&mut self)
where
T: 'static,
{
self.checked().set(true);
}
}
let mut store = use_store(|| Item {
checked: false,
contents: "Learn about stores".to_string(),
});
let checked: Store<bool, _> = store.checked();
let contents: Store<String, _> = store.contents();
let checked: bool = checked();
let contents: String = contents();
let ItemStoreTransposed { checked, contents } = store.transpose();
let checked: bool = checked();
let contents: String = contents();
let is_checked = store.is_checked();
store.check();
}
fn derive_generic_struct_with_bounds() {
#[derive(Store)]
struct Item<T: ?Sized>
where
T: 'static,
{
checked: bool,
contents: &'static T,
}
#[store]
impl<T: ?Sized + 'static> Store<Item<T>> {
fn is_checked(&self) -> bool
where
T: 'static,
{
self.checked().cloned()
}
fn check(&mut self)
where
T: 'static,
{
self.checked().set(true);
}
}
let mut store = use_store(|| Item {
checked: false,
contents: "Learn about stores",
});
let checked: Store<bool, _> = store.checked();
let contents: Store<&'static str, _> = store.contents();
let checked: bool = checked();
let contents: &'static str = contents();
let ItemStoreTransposed { checked, contents } = store.transpose();
let checked: bool = checked();
let contents: &'static str = contents();
let is_checked = store.is_checked();
store.check();
}
fn derive_generic_struct_transposed_passthrough() {
#[derive(Store)]
struct Item<const COUNT: usize, T> {
contents: T,
}
let mut store = use_store(|| Item::<0, _> {
contents: "Learn about stores".to_string(),
});
let Item { contents } = store.transpose();
let contents: String = contents();
}
fn derive_tuple() {
#[derive(Store, PartialEq, Clone, Debug)]
struct Item(bool, String);
let store = use_store(|| Item(true, "Hello".to_string()));
let first = store.field_0();
let first: bool = first();
let transposed = store.transpose();
let first = transposed.0;
let second = transposed.1;
let first: bool = first();
let second: String = second();
}
fn derive_enum() {
#[derive(Store, PartialEq, Clone, Debug)]
#[non_exhaustive]
enum Enum {
Foo,
Bar(String),
Baz { foo: i32, bar: String },
FooBar(u32, String),
BarFoo { foo: String },
}
#[store]
impl Store<Enum> {
fn is_foo_or_bar(&self) -> bool {
matches!(self.cloned(), Enum::Foo | Enum::Bar(_))
}
fn make_foo(&mut self) {
self.set(Enum::Foo);
}
}
let mut store = use_store(|| Enum::Bar("Hello".to_string()));
let foo = store.is_foo();
let bar = store.is_bar();
let baz = store.is_baz();
let foobar = store.is_foo_bar();
let barfoo = store.is_bar_foo();
let foo = store.bar().unwrap();
let foo: String = foo();
let bar = store.bar_foo().unwrap();
let bar: String = bar();
let transposed = store.transpose();
use EnumStoreTransposed::*;
match transposed {
EnumStoreTransposed::Foo => {}
Bar(bar) => {
let bar: String = bar();
}
Baz { foo, bar } => {
let foo: i32 = foo();
let bar: String = bar();
}
FooBar(foo, bar) => {
let foo: u32 = foo();
let bar: String = bar();
}
BarFoo { foo } => {
let foo: String = foo();
}
}
let is_foo_or_bar = store.is_foo_or_bar();
store.make_foo();
}
fn derive_generic_enum() {
#[derive(Store, PartialEq, Clone, Debug)]
#[non_exhaustive]
enum Enum<T> {
Foo,
Bar(T),
Baz { foo: i32, bar: T },
FooBar(u32, T),
BarFoo { foo: T },
}
#[store]
impl<T> Store<Enum<T>> {
fn is_foo_or_bar(&self) -> bool
where
T: Clone + 'static,
{
matches!(self.cloned(), Enum::Foo | Enum::Bar(_))
}
fn make_foo(&mut self)
where
T: 'static,
{
self.set(Enum::Foo);
}
}
let mut store = use_store(|| Enum::Bar("Hello".to_string()));
let foo = store.is_foo();
let bar = store.is_bar();
let baz = store.is_baz();
let foobar = store.is_foo_bar();
let barfoo = store.is_bar_foo();
let foo = store.bar().unwrap();
let foo: String = foo();
let bar = store.bar_foo().unwrap();
let bar: String = bar();
let transposed = store.transpose();
use EnumStoreTransposed::*;
match transposed {
EnumStoreTransposed::Foo => {}
Bar(bar) => {
let bar: String = bar();
}
Baz { foo, bar } => {
let foo: i32 = foo();
let bar: String = bar();
}
FooBar(foo, bar) => {
let foo: u32 = foo();
let bar: String = bar();
}
BarFoo { foo } => {
let foo: String = foo();
}
}
let is_foo_or_bar = store.is_foo_or_bar();
store.make_foo();
}
fn derive_generic_enum_with_bounds() {
#[derive(Store, PartialEq, Clone, Debug)]
#[non_exhaustive]
enum Enum<T: ?Sized>
where
T: 'static,
{
Foo,
Bar(&'static T),
Baz { foo: i32, bar: &'static T },
FooBar(u32, &'static T),
BarFoo { foo: &'static T },
}
#[store]
impl<T: ?Sized + 'static> Store<Enum<T>> {
fn is_foo_or_bar(&self) -> bool
where
T: Clone + 'static,
{
matches!(self.cloned(), Enum::Foo | Enum::Bar(_))
}
fn make_foo(&mut self)
where
T: 'static,
{
self.set(Enum::Foo);
}
}
let mut store = use_store(|| Enum::Bar("Hello"));
let foo = store.is_foo();
let bar = store.is_bar();
let baz = store.is_baz();
let foobar = store.is_foo_bar();
let barfoo = store.is_bar_foo();
let foo = store.bar().unwrap();
let foo: &'static str = foo();
let bar = store.bar_foo().unwrap();
let bar: &'static str = bar();
let transposed = store.transpose();
use EnumStoreTransposed::*;
match transposed {
EnumStoreTransposed::Foo => {}
Bar(bar) => {
let bar: &'static str = bar();
}
Baz { foo, bar } => {
let foo: i32 = foo();
let bar: &'static str = bar();
}
FooBar(foo, bar) => {
let foo: u32 = foo();
let bar: &'static str = bar();
}
BarFoo { foo } => {
let foo: &'static str = foo();
}
}
}
fn derive_generic_enum_transpose_passthrough() {
#[derive(Store, PartialEq, Clone, Debug)]
#[non_exhaustive]
enum Enum<const COUNT: usize, T> {
Foo,
Bar(T),
BarFoo { foo: T },
}
let mut store = use_store(|| Enum::<0, _>::Bar("Hello".to_string()));
let transposed = store.transpose();
use Enum::*;
match transposed {
Enum::Foo => {}
Bar(bar) => {
let bar: String = bar();
}
BarFoo { foo } => {
let foo: String = foo();
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/stores/tests/coercions.rs | packages/stores/tests/coercions.rs | #![allow(unused)]
use dioxus::prelude::*;
use dioxus_stores::*;
#[derive(Store)]
struct TodoItem {
checked: bool,
contents: String,
}
fn app() -> Element {
let item = use_store(|| TodoItem {
checked: false,
contents: "Learn about stores".to_string(),
});
rsx! {
TakesReadSignal {
item,
}
TakesReadStore {
item,
}
TakesStr {
item: item.contents().deref(),
}
TakesStrStore {
item: item.contents().deref(),
}
}
}
#[component]
fn TakesStr(item: ReadSignal<str>) -> Element {
rsx! {
TakesStr {
item,
}
}
}
#[component]
fn TakesStrStore(item: ReadStore<str>) -> Element {
rsx! {
TakesStrStore {
item,
}
}
}
#[component]
fn TakesReadSignal(item: ReadSignal<TodoItem>) -> Element {
rsx! {
TakesReadSignal {
item,
}
}
}
#[component]
fn TakesReadStore(item: ReadStore<TodoItem>) -> Element {
rsx! {
TakesReadStore {
item,
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/component-manifest/src/lib.rs | packages/component-manifest/src/lib.rs | use std::process::Command;
use schemars::{schema_for, JsonSchema, Schema};
use serde::{Deserialize, Serialize};
/// A component compatible with the dioxus components system.
/// This may be a "virtual" component which is empty except for a list of members.
#[derive(Deserialize, Serialize, JsonSchema, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Component {
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub authors: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub component_dependencies: Vec<ComponentDependency>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub cargo_dependencies: Vec<CargoDependency>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub members: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub exclude: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub global_assets: Vec<String>,
}
/// A dependency on another component, either built-in or third-party.
#[derive(Deserialize, Serialize, JsonSchema, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum ComponentDependency {
Builtin(String),
ThirdParty {
name: String,
git: String,
#[serde(default)]
rev: Option<String>,
},
}
/// A dependency on a cargo crate required for a component.
#[derive(Deserialize, Serialize, JsonSchema, Clone, Debug, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum CargoDependency {
Simple(String),
Detailed {
name: String,
#[serde(default)]
version: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
features: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
default_features: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
git: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
rev: Option<String>,
},
}
impl CargoDependency {
/// Get the `cargo add` command for this dependency.
pub fn add_command(&self) -> Command {
let mut cmd = Command::new("cargo");
cmd.arg("add");
match self {
CargoDependency::Simple(name) => {
cmd.arg(name);
}
CargoDependency::Detailed {
name,
version,
features,
default_features,
git,
rev,
} => {
cmd.arg(format!(
"{name}{}",
version
.as_ref()
.map(|version| format!("@{version}"))
.unwrap_or_default()
));
if !features.is_empty() {
cmd.arg("--features").arg(features.join(","));
}
if !*default_features {
cmd.arg("--no-default-features");
}
if let Some(git) = git {
cmd.arg("--git").arg(git);
}
if let Some(rev) = rev {
cmd.arg("--rev").arg(rev);
}
}
}
cmd
}
/// Get the name of the dependency.
pub fn name(&self) -> &str {
match self {
CargoDependency::Simple(name) => name,
CargoDependency::Detailed { name, .. } => name,
}
}
}
/// Get the JSON schema for the `Component` struct.
pub fn component_manifest_schema() -> Schema {
schema_for!(Component)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/src/lib.rs | packages/autofmt/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 crate::writer::*;
use dioxus_rsx::{BodyNode, CallBody};
use proc_macro2::{LineColumn, Span};
use syn::parse::Parser;
mod buffer;
mod collect_macros;
mod indent;
mod prettier_please;
mod writer;
pub use indent::{IndentOptions, IndentType};
/// A modification to the original file to be applied by an IDE
///
/// Right now this re-writes entire rsx! blocks at a time, instead of precise line-by-line changes.
///
/// In a "perfect" world we would have tiny edits to preserve things like cursor states and selections. The API here makes
/// it possible to migrate to a more precise modification approach in the future without breaking existing code.
///
/// Note that this is tailored to VSCode's TextEdit API and not a general Diff API. Line numbers are not accurate if
/// multiple edits are applied in a single file without tracking text shifts.
#[derive(serde::Deserialize, serde::Serialize, Clone, Debug, PartialEq, Eq, Hash)]
pub struct FormattedBlock {
/// The new contents of the block
pub formatted: String,
/// The line number of the first line of the block.
pub start: usize,
/// The end of the block, exclusive.
pub end: usize,
}
/// Format a file into a list of `FormattedBlock`s to be applied by an IDE for autoformatting.
///
/// It accepts
#[deprecated(note = "Use try_fmt_file instead - this function panics on error.")]
pub fn fmt_file(contents: &str, indent: IndentOptions) -> Vec<FormattedBlock> {
let parsed =
syn::parse_file(contents).expect("fmt_file should only be called on valid syn::File files");
try_fmt_file(contents, &parsed, indent).expect("Failed to format file")
}
/// Format a file into a list of `FormattedBlock`s to be applied by an IDE for autoformatting.
///
/// This function expects a complete file, not just a block of code. To format individual rsx! blocks, use fmt_block instead.
///
/// The point here is to provide precise modifications of a source file so an accompanying IDE tool can map these changes
/// back to the file precisely.
///
/// Nested blocks of RSX will be handled automatically
///
/// This returns an error if the rsx itself is invalid.
///
/// Will early return if any of the expressions are not complete. Even though we *could* return the
/// expressions, eventually we'll want to pass off expression formatting to rustfmt which will reject
/// those.
pub fn try_fmt_file(
contents: &str,
parsed: &syn::File,
indent: IndentOptions,
) -> syn::Result<Vec<FormattedBlock>> {
let mut formatted_blocks = Vec::new();
let macros = collect_macros::collect_from_file(parsed);
// No macros, no work to do
if macros.is_empty() {
return Ok(formatted_blocks);
}
let mut writer = Writer::new(contents, indent);
// Don't parse nested macros
let mut end_span = LineColumn { column: 0, line: 0 };
for item in macros {
let macro_path = &item.path.segments[0].ident;
// this macro is inside the last macro we parsed, skip it
if macro_path.span().start() < end_span {
continue;
}
let body = item.parse_body_with(CallBody::parse_strict)?;
let rsx_start = macro_path.span().start();
writer.out.indent_level = writer
.out
.indent
.count_indents(writer.src.get(rsx_start.line - 1).unwrap_or(&""));
// TESTME
// Writing *should* not fail but it's possible that it does
if writer.write_rsx_call(&body).is_err() {
let span = writer.invalid_exprs.pop().unwrap_or_else(Span::call_site);
return Err(syn::Error::new(span, "Failed emit valid rsx - likely due to partially complete expressions in the rsx! macro"));
}
// writing idents leaves the final line ended at the end of the last ident
if writer.out.buf.contains('\n') {
_ = writer.out.new_line();
_ = writer.out.tab();
}
let span = item.delimiter.span().join();
let mut formatted = writer.out.buf.split_off(0);
let start = collect_macros::byte_offset(contents, span.start()) + 1;
let end = collect_macros::byte_offset(contents, span.end()) - 1;
// Rustfmt will remove the space between the macro and the opening paren if the macro is a single expression
let body_is_solo_expr = body.body.roots.len() == 1
&& matches!(body.body.roots[0], BodyNode::RawExpr(_) | BodyNode::Text(_));
// If it's short, and it's not a single expression, and it's not empty, then we can collapse it
if formatted.len() <= 80
&& !formatted.contains('\n')
&& !body_is_solo_expr
&& !formatted.trim().is_empty()
{
formatted = format!(" {formatted} ");
}
end_span = span.end();
if contents[start..end] == formatted {
continue;
}
formatted_blocks.push(FormattedBlock {
formatted,
start,
end,
});
}
Ok(formatted_blocks)
}
/// Write a Callbody (the rsx block) to a string
///
/// If the tokens can't be formatted, this returns None. This is usually due to an incomplete expression
/// that passed partial expansion but failed to parse.
pub fn write_block_out(body: &CallBody) -> Option<String> {
let mut buf = Writer::new("", IndentOptions::default());
buf.write_rsx_call(body).ok()?;
buf.consume()
}
pub fn fmt_block(block: &str, indent_level: usize, indent: IndentOptions) -> Option<String> {
let body = CallBody::parse_strict.parse_str(block).unwrap();
let mut buf = Writer::new(block, indent);
buf.out.indent_level = indent_level;
buf.write_rsx_call(&body).ok()?;
// writing idents leaves the final line ended at the end of the last ident
if buf.out.buf.contains('\n') {
buf.out.new_line().unwrap();
}
buf.consume()
}
// Apply all the blocks
pub fn apply_formats(input: &str, blocks: Vec<FormattedBlock>) -> String {
let mut out = String::new();
let mut last = 0;
for FormattedBlock {
formatted,
start,
end,
} in blocks
{
let prefix = &input[last..start];
out.push_str(prefix);
out.push_str(&formatted);
last = end;
}
let suffix = &input[last..];
out.push_str(suffix);
out
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/src/indent.rs | packages/autofmt/src/indent.rs | #[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum IndentType {
Spaces,
Tabs,
}
#[derive(Debug, Clone)]
pub struct IndentOptions {
width: usize,
indent_string: String,
split_line_attributes: bool,
}
impl IndentOptions {
pub fn new(ty: IndentType, width: usize, split_line_attributes: bool) -> Self {
assert_ne!(width, 0, "Cannot have an indent width of 0");
Self {
width,
indent_string: match ty {
IndentType::Tabs => "\t".into(),
IndentType::Spaces => " ".repeat(width),
},
split_line_attributes,
}
}
/// Gets a string containing one indent worth of whitespace
pub fn indent_str(&self) -> &str {
&self.indent_string
}
/// Computes the line length in characters, counting tabs as the indent width.
pub fn line_length(&self, line: &str) -> usize {
line.chars()
.map(|ch| if ch == '\t' { self.width } else { 1 })
.sum()
}
/// Estimates how many times the line has been indented.
pub fn count_indents(&self, mut line: &str) -> usize {
let mut indent = 0;
while !line.is_empty() {
// Try to count tabs
let num_tabs = line.chars().take_while(|ch| *ch == '\t').count();
if num_tabs > 0 {
indent += num_tabs;
line = &line[num_tabs..];
continue;
}
// Try to count spaces
let num_spaces = line.chars().take_while(|ch| *ch == ' ').count();
if num_spaces >= self.width {
// Intentionally floor here to take only the amount of space that matches an indent
let num_space_indents = num_spaces / self.width;
indent += num_space_indents;
line = &line[num_space_indents * self.width..];
continue;
}
// Line starts with either non-indent characters or an unevent amount of spaces,
// so no more indent remains.
break;
}
indent
}
pub fn split_line_attributes(&self) -> bool {
self.split_line_attributes
}
}
impl Default for IndentOptions {
fn default() -> Self {
Self::new(IndentType::Spaces, 4, false)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn count_indents() {
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4, false).count_indents("no indentation here!"),
0
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4, false).count_indents(" v += 2"),
1
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4, false).count_indents(" v += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4, false).count_indents(" v += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4, false).count_indents("\t\tv += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 4, false).count_indents("\t\t v += 2"),
2
);
assert_eq!(
IndentOptions::new(IndentType::Spaces, 2, false).count_indents(" v += 2"),
2
);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/src/prettier_please.rs | packages/autofmt/src/prettier_please.rs | use dioxus_rsx::CallBody;
use syn::{parse::Parser, visit_mut::VisitMut, Expr, File, Item, MacroDelimiter};
use crate::{IndentOptions, Writer};
impl Writer<'_> {
pub fn unparse_expr(&mut self, expr: &Expr) -> String {
unparse_expr(expr, self.raw_src, &self.out.indent)
}
}
// we use weird unicode alternatives to avoid conflicts with the actual rsx! macro
const MARKER: &str = "𝕣𝕤𝕩";
const MARKER_REPLACE: &str = "𝕣𝕤𝕩! {}";
pub fn unparse_expr(expr: &Expr, src: &str, cfg: &IndentOptions) -> String {
struct ReplaceMacros<'a> {
src: &'a str,
formatted_stack: Vec<String>,
cfg: &'a IndentOptions,
}
impl VisitMut for ReplaceMacros<'_> {
fn visit_macro_mut(&mut self, i: &mut syn::Macro) {
// replace the macro with a block that roughly matches the macro
if let Some("rsx" | "render") = i
.path
.segments
.last()
.map(|i| i.ident.to_string())
.as_deref()
{
// format the macro in place
// we'll use information about the macro to replace it with another formatted block
// once we've written out the unparsed expr from prettyplease, we can replace
// this dummy block with the actual formatted block
let body = CallBody::parse_strict.parse2(i.tokens.clone()).unwrap();
let multiline = !Writer::is_short_rsx_call(&body.body.roots);
let mut formatted = {
let mut writer = Writer::new(self.src, self.cfg.clone());
_ = writer.write_body_nodes(&body.body.roots).ok();
writer.consume()
}
.unwrap();
i.path = syn::parse_str(MARKER).unwrap();
i.tokens = Default::default();
// make sure to transform the delimiter to a brace so the marker can be found
// an alternative approach would be to use multiple different markers that are not
// sensitive to the delimiter.
i.delimiter = MacroDelimiter::Brace(Default::default());
// Push out the indent level of the formatted block if it's multiline
if multiline || formatted.contains('\n') {
formatted = formatted
.lines()
.map(|line| format!("{}{line}", self.cfg.indent_str()))
.collect::<Vec<_>>()
.join("\n");
}
// Save this formatted block for later, when we apply it to the original expr
self.formatted_stack.push(formatted)
}
syn::visit_mut::visit_macro_mut(self, i);
}
}
// Visit the expr and replace the macros with formatted blocks
let mut replacer = ReplaceMacros {
src,
cfg,
formatted_stack: vec![],
};
// builds the expression stack
let mut modified_expr = expr.clone();
replacer.visit_expr_mut(&mut modified_expr);
// now unparsed with the modified expression
let mut unparsed = unparse_inner(&modified_expr);
// now we can replace the macros with the formatted blocks
for fmted in replacer.formatted_stack.drain(..) {
let is_multiline = fmted.ends_with('}') || fmted.contains('\n');
let is_empty = fmted.trim().is_empty();
let mut out_fmt = String::from("rsx! {");
if is_multiline {
out_fmt.push('\n');
} else if !is_empty {
out_fmt.push(' ');
}
let mut whitespace = 0;
for line in unparsed.lines() {
if line.contains(MARKER) {
whitespace = line.matches(cfg.indent_str()).count();
break;
}
}
let mut lines = fmted.lines().enumerate().peekable();
while let Some((_idx, fmt_line)) = lines.next() {
// Push the indentation
if is_multiline {
out_fmt.push_str(&cfg.indent_str().repeat(whitespace));
}
// Calculate delta between indentations - the block indentation is too much
out_fmt.push_str(fmt_line);
// Push a newline if there's another line
if lines.peek().is_some() {
out_fmt.push('\n');
}
}
if is_multiline {
out_fmt.push('\n');
out_fmt.push_str(&cfg.indent_str().repeat(whitespace));
} else if !is_empty {
out_fmt.push(' ');
}
// Replace the dioxus_autofmt_block__________ token with the formatted block
out_fmt.push('}');
unparsed = unparsed.replacen(MARKER_REPLACE, &out_fmt, 1);
continue;
}
// stylistic choice to trim whitespace around the expr
if unparsed.starts_with("{ ") && unparsed.ends_with(" }") {
let mut out_fmt = String::new();
out_fmt.push('{');
out_fmt.push_str(&unparsed[2..unparsed.len() - 2]);
out_fmt.push('}');
out_fmt
} else {
unparsed
}
}
/// Unparse an expression back into a string
///
/// This creates a new temporary file, parses the expression into it, and then formats the file.
/// This is a bit of a hack, but dtonlay doesn't want to support this very simple usecase, forcing us to clone the expr
pub fn unparse_inner(expr: &Expr) -> String {
let file = wrapped(expr);
let wrapped = prettyplease::unparse(&file);
unwrapped(wrapped)
}
// Split off the fn main and then cut the tabs off the front
fn unwrapped(raw: String) -> String {
let mut o = raw
.strip_prefix("fn main() {\n")
.unwrap()
.strip_suffix("}\n")
.unwrap()
.lines()
.map(|line| line.strip_prefix(" ").unwrap_or_default()) // todo: set this to tab level
.collect::<Vec<_>>()
.join("\n");
// remove the semicolon
if o.ends_with(';') {
o.pop();
}
o
}
fn wrapped(expr: &Expr) -> File {
File {
shebang: None,
attrs: vec![],
items: vec![
//
Item::Verbatim(quote::quote! {
fn main() {
#expr;
}
}),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
use proc_macro2::TokenStream;
fn fmt_block_from_expr(raw: &str, tokens: TokenStream, cfg: IndentOptions) -> Option<String> {
let body = CallBody::parse_strict.parse2(tokens).unwrap();
let mut writer = Writer::new(raw, cfg);
writer.write_body_nodes(&body.body.roots).ok()?;
writer.consume()
}
#[test]
fn unparses_raw() {
let expr = syn::parse_str("1 + 1").expect("Failed to parse");
let unparsed = prettyplease::unparse(&wrapped(&expr));
assert_eq!(unparsed, "fn main() {\n 1 + 1;\n}\n");
}
#[test]
fn weird_ifcase() {
let contents = r##"
fn main() {
move |_| timer.with_mut(|t| if t.started_at.is_none() { Some(Instant::now()) } else { None })
}
"##;
let expr: File = syn::parse_file(contents).unwrap();
let out = prettyplease::unparse(&expr);
println!("{}", out);
}
#[test]
fn multiline_madness() {
let contents = r##"
{
{children.is_some().then(|| rsx! {
span {
class: "inline-block ml-auto hover:bg-gray-500",
onclick: move |evt| {
evt.cancel_bubble();
},
icons::icon_5 {}
{rsx! {
icons::icon_6 {}
}}
}
})}
{children.is_some().then(|| rsx! {
span {
class: "inline-block ml-auto hover:bg-gray-500",
onclick: move |evt| {
evt.cancel_bubble();
},
icons::icon_10 {}
}
})}
}
"##;
let expr: Expr = syn::parse_str(contents).unwrap();
let out = unparse_expr(&expr, contents, &IndentOptions::default());
println!("{}", out);
}
#[test]
fn write_body_no_indent() {
let src = r##"
span {
class: "inline-block ml-auto hover:bg-gray-500",
onclick: move |evt| {
evt.cancel_bubble();
},
icons::icon_10 {}
icons::icon_10 {}
icons::icon_10 {}
icons::icon_10 {}
div { "hi" }
div { div {} }
div { div {} div {} div {} }
{children}
{
some_big_long()
.some_big_long()
.some_big_long()
.some_big_long()
.some_big_long()
.some_big_long()
}
div { class: "px-4", {is_current.then(|| rsx! { {children} })} }
Thing {
field: rsx! {
div { "hi" }
Component {
onrender: rsx! {
div { "hi" }
Component {
onclick: move |_| {
another_macro! {
div { class: "max-w-lg lg:max-w-2xl mx-auto mb-16 text-center",
"gomg"
"hi!!"
"womh"
}
};
rsx! {
div { class: "max-w-lg lg:max-w-2xl mx-auto mb-16 text-center",
"gomg"
"hi!!"
"womh"
}
};
println!("hi")
},
onrender: move |_| {
let _ = 12;
let r = rsx! {
div { "hi" }
};
rsx! {
div { "hi" }
}
}
}
{
rsx! {
BarChart {
id: "bar-plot".to_string(),
x: value,
y: label
}
}
}
}
}
}
}
}
"##;
let tokens: TokenStream = syn::parse_str(src).unwrap();
let out = fmt_block_from_expr(src, tokens, IndentOptions::default()).unwrap();
println!("{}", out);
}
#[test]
fn write_component_body() {
let src = r##"
div { class: "px-4", {is_current.then(|| rsx! { {children} })} }
"##;
let tokens: TokenStream = syn::parse_str(src).unwrap();
let out = fmt_block_from_expr(src, tokens, IndentOptions::default()).unwrap();
println!("{}", out);
}
#[test]
fn weird_macro() {
let contents = r##"
fn main() {
move |_| {
drop_macro_semi! {
"something_very_long_something_very_long_something_very_long_something_very_long"
};
let _ = drop_macro_semi! {
"something_very_long_something_very_long_something_very_long_something_very_long"
};
drop_macro_semi! {
"something_very_long_something_very_long_something_very_long_something_very_long"
};
};
}
"##;
let expr: File = syn::parse_file(contents).unwrap();
let out = prettyplease::unparse(&expr);
println!("{}", out);
}
#[test]
fn comments_on_nodes() {
let src = r##"// hiasdasds
div {
attr: "value", // comment
div {}
"hi" // hello!
"hi" // hello!
"hi" // hello!
// hi!
}
"##;
let tokens: TokenStream = syn::parse_str(src).unwrap();
let out = fmt_block_from_expr(src, tokens, IndentOptions::default()).unwrap();
println!("{}", out);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/src/collect_macros.rs | packages/autofmt/src/collect_macros.rs | //! Collect macros from a file
//!
//! Returns all macros that match a pattern. You can use this information to autoformat them later
use proc_macro2::LineColumn;
use syn::{visit::Visit, File, Macro, Meta};
type CollectedMacro<'a> = &'a Macro;
pub fn collect_from_file(file: &File) -> Vec<CollectedMacro<'_>> {
let mut macros = vec![];
let mut collector = MacroCollector::new(&mut macros);
MacroCollector::visit_file(&mut collector, file);
macros
}
struct MacroCollector<'a, 'b> {
macros: &'a mut Vec<CollectedMacro<'b>>,
skip_count: usize,
}
impl<'a, 'b> MacroCollector<'a, 'b> {
fn new(macros: &'a mut Vec<CollectedMacro<'b>>) -> Self {
Self {
macros,
skip_count: 0,
}
}
}
impl<'b> Visit<'b> for MacroCollector<'_, 'b> {
fn visit_macro(&mut self, i: &'b Macro) {
// Visit the regular stuff - this will also ensure paths/attributes are visited
syn::visit::visit_macro(self, i);
let name = &i.path.segments.last().map(|i| i.ident.to_string());
if let Some("rsx" | "render") = name.as_deref() {
if self.skip_count == 0 {
self.macros.push(i)
}
}
}
// attributes can occur on stmts and items - we need to make sure the stack is reset when we exit
// this means we save the skipped length and set it back to its original length
fn visit_stmt(&mut self, i: &'b syn::Stmt) {
let skipped_len = self.skip_count;
syn::visit::visit_stmt(self, i);
self.skip_count = skipped_len;
}
fn visit_item(&mut self, i: &'b syn::Item) {
let skipped_len = self.skip_count;
syn::visit::visit_item(self, i);
self.skip_count = skipped_len;
}
fn visit_attribute(&mut self, i: &'b syn::Attribute) {
// we need to communicate that this stmt is skipped up the tree
if attr_is_rustfmt_skip(i) {
self.skip_count += 1;
}
syn::visit::visit_attribute(self, i);
}
}
pub fn byte_offset(input: &str, location: LineColumn) -> usize {
let mut offset = 0;
for _ in 1..location.line {
offset += input[offset..].find('\n').unwrap() + 1;
}
offset
+ input[offset..]
.chars()
.take(location.column)
.map(char::len_utf8)
.sum::<usize>()
}
/// Check if an attribute is a rustfmt skip attribute
fn attr_is_rustfmt_skip(i: &syn::Attribute) -> bool {
match &i.meta {
Meta::Path(path) => {
path.segments.len() == 2
&& matches!(i.style, syn::AttrStyle::Outer)
&& path.segments[0].ident == "rustfmt"
&& path.segments[1].ident == "skip"
}
_ => false,
}
}
#[test]
fn parses_file_and_collects_rsx_macros() {
let contents = include_str!("../tests/samples/long.rsx");
let parsed = syn::parse_file(contents).expect("parse file okay");
let macros = collect_from_file(&parsed);
assert_eq!(macros.len(), 3);
}
/// Ensure that we only collect non-skipped macros
#[test]
fn dont_collect_skipped_macros() {
let contents = include_str!("../tests/samples/skip.rsx");
let parsed = syn::parse_file(contents).expect("parse file okay");
let macros = collect_from_file(&parsed);
assert_eq!(macros.len(), 2);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/src/writer.rs | packages/autofmt/src/writer.rs | use crate::{buffer::Buffer, IndentOptions};
use dioxus_rsx::*;
use proc_macro2::{LineColumn, Span};
use quote::ToTokens;
use regex::Regex;
use std::{
borrow::Cow,
collections::{HashMap, VecDeque},
fmt::{Result, Write},
};
use syn::{spanned::Spanned, token::Brace, Expr};
#[derive(Debug)]
pub struct Writer<'a> {
pub raw_src: &'a str,
pub src: Vec<&'a str>,
pub cached_formats: HashMap<LineColumn, String>,
pub out: Buffer,
pub invalid_exprs: Vec<Span>,
}
impl<'a> Writer<'a> {
pub fn new(raw_src: &'a str, indent: IndentOptions) -> Self {
Self {
src: raw_src.lines().collect(),
raw_src,
out: Buffer {
indent,
..Default::default()
},
cached_formats: HashMap::new(),
invalid_exprs: Vec::new(),
}
}
pub fn consume(self) -> Option<String> {
Some(self.out.buf)
}
pub fn write_rsx_call(&mut self, body: &CallBody) -> Result {
if body.body.roots.is_empty() {
return Ok(());
}
if Self::is_short_rsx_call(&body.body.roots) {
write!(self.out, " ")?;
self.write_ident(&body.body.roots[0])?;
write!(self.out, " ")?;
} else {
self.out.new_line()?;
self.write_body_indented(&body.body.roots)?;
self.write_trailing_body_comments(body)?;
}
Ok(())
}
fn write_trailing_body_comments(&mut self, body: &CallBody) -> Result {
if let Some(span) = body.span {
self.out.indent_level += 1;
let comments = self.accumulate_full_line_comments(span.span().end());
if !comments.is_empty() {
self.out.new_line()?;
self.apply_line_comments(comments)?;
self.out.buf.pop(); // remove the trailing newline, forcing us to end at the end of the comment
}
self.out.indent_level -= 1;
}
Ok(())
}
// Expects to be written directly into place
pub fn write_ident(&mut self, node: &BodyNode) -> Result {
match node {
BodyNode::Element(el) => self.write_element(el),
BodyNode::Component(component) => self.write_component(component),
BodyNode::Text(text) => self.write_text_node(text),
BodyNode::RawExpr(expr) => self.write_expr_node(expr),
BodyNode::ForLoop(forloop) => self.write_for_loop(forloop),
BodyNode::IfChain(ifchain) => self.write_if_chain(ifchain),
}?;
let span = Self::final_span_of_node(node);
self.write_inline_comments(span.end(), 0)?;
Ok(())
}
/// Check if the rsx call is short enough to be inlined
pub(crate) fn is_short_rsx_call(roots: &[BodyNode]) -> bool {
// eventually I want to use the _text length, so shutup now
#[allow(clippy::match_like_matches_macro)]
match roots {
[] => true,
[BodyNode::Text(_text)] => true,
_ => false,
}
}
fn write_element(&mut self, el: &Element) -> Result {
let Element {
name,
raw_attributes: attributes,
children,
spreads,
brace,
..
} = el;
write!(self.out, "{name} ")?;
self.write_rsx_block(attributes, spreads, children, &brace.unwrap_or_default())?;
Ok(())
}
fn write_component(
&mut self,
Component {
name,
fields,
children,
generics,
spreads,
brace,
..
}: &Component,
) -> Result {
// Write the path by to_tokensing it and then removing all whitespace
let mut name = name.to_token_stream().to_string();
name.retain(|c| !c.is_whitespace());
write!(self.out, "{name}")?;
// Same idea with generics, write those via the to_tokens method and then remove all whitespace
if let Some(generics) = generics {
let mut written = generics.to_token_stream().to_string();
written.retain(|c| !c.is_whitespace());
write!(self.out, "{written}")?;
}
write!(self.out, " ")?;
self.write_rsx_block(fields, spreads, &children.roots, &brace.unwrap_or_default())?;
Ok(())
}
fn write_text_node(&mut self, text: &TextNode) -> Result {
self.out.write_text(&text.input)
}
fn write_expr_node(&mut self, expr: &ExprNode) -> Result {
self.write_partial_expr(expr.expr.as_expr(), expr.span())
}
fn write_for_loop(&mut self, forloop: &ForLoop) -> std::fmt::Result {
write!(
self.out,
"for {} in ",
forloop.pat.clone().into_token_stream(),
)?;
self.write_inline_expr(&forloop.expr)?;
if forloop.body.is_empty() {
write!(self.out, "}}")?;
return Ok(());
}
self.out.new_line()?;
self.write_body_indented(&forloop.body.roots)?;
self.out.tabbed_line()?;
write!(self.out, "}}")?;
Ok(())
}
fn write_if_chain(&mut self, ifchain: &IfChain) -> std::fmt::Result {
// Recurse in place by setting the next chain
let mut branch = Some(ifchain);
while let Some(chain) = branch {
let IfChain {
if_token,
cond,
then_branch,
else_if_branch,
else_branch,
..
} = chain;
write!(self.out, "{} ", if_token.to_token_stream(),)?;
self.write_inline_expr(cond)?;
self.out.new_line()?;
self.write_body_indented(&then_branch.roots)?;
if let Some(else_if_branch) = else_if_branch {
// write the closing bracket and else
self.out.tabbed_line()?;
write!(self.out, "}} else ")?;
branch = Some(else_if_branch);
} else if let Some(else_branch) = else_branch {
self.out.tabbed_line()?;
write!(self.out, "}} else {{")?;
self.out.new_line()?;
self.write_body_indented(&else_branch.roots)?;
branch = None;
} else {
branch = None;
}
}
self.out.tabbed_line()?;
write!(self.out, "}}")?;
Ok(())
}
/// An expression within a for or if block that might need to be spread out across several lines
fn write_inline_expr(&mut self, expr: &Expr) -> std::fmt::Result {
let unparsed = self.unparse_expr(expr);
let mut lines = unparsed.lines();
let first_line = lines.next().ok_or(std::fmt::Error)?;
write!(self.out, "{first_line}")?;
let mut was_multiline = false;
for line in lines {
was_multiline = true;
self.out.tabbed_line()?;
write!(self.out, "{line}")?;
}
if was_multiline {
self.out.tabbed_line()?;
write!(self.out, "{{")?;
} else {
write!(self.out, " {{")?;
}
Ok(())
}
// Push out the indent level and write each component, line by line
fn write_body_indented(&mut self, children: &[BodyNode]) -> Result {
self.out.indent_level += 1;
self.write_body_nodes(children)?;
self.out.indent_level -= 1;
Ok(())
}
pub fn write_body_nodes(&mut self, children: &[BodyNode]) -> Result {
let mut iter = children.iter().peekable();
while let Some(child) = iter.next() {
if self.current_span_is_primary(child.span().start()) {
self.write_comments(child.span().start())?;
};
self.out.tab()?;
self.write_ident(child)?;
if iter.peek().is_some() {
self.out.new_line()?;
}
}
Ok(())
}
/// Basically elements and components are the same thing
///
/// This writes the contents out for both in one function, centralizing the annoying logic like
/// key handling, breaks, closures, etc
fn write_rsx_block(
&mut self,
attributes: &[Attribute],
spreads: &[Spread],
children: &[BodyNode],
brace: &Brace,
) -> Result {
#[derive(Debug)]
enum ShortOptimization {
/// Special because we want to print the closing bracket immediately
///
/// IE
/// `div {}` instead of `div { }`
Empty,
/// Special optimization to put everything on the same line and add some buffer spaces
///
/// IE
///
/// `div { "asdasd" }` instead of a multiline variant
Oneliner,
/// Optimization where children flow but props remain fixed on top
PropsOnTop,
/// The noisiest optimization where everything flows
NoOpt,
}
// Write the opening brace
write!(self.out, "{{")?;
// decide if we have any special optimizations
// Default with none, opt the cases in one-by-one
let mut opt_level = ShortOptimization::NoOpt;
// check if we have a lot of attributes
let attr_len = self.is_short_attrs(brace, attributes, spreads);
let has_postbrace_comments = self.brace_has_trailing_comments(brace);
let is_short_attr_list =
((attr_len + self.out.indent_level * 4) < 80) && !has_postbrace_comments;
let children_len = self
.is_short_children(children)
.map_err(|_| std::fmt::Error)?;
let has_trailing_comments = self.has_trailing_comments(children, brace);
let is_small_children = children_len.is_some() && !has_trailing_comments;
// if we have one long attribute and a lot of children, place the attrs on top
if is_short_attr_list && !is_small_children {
opt_level = ShortOptimization::PropsOnTop;
}
// even if the attr is long, it should be put on one line
// However if we have childrne we need to just spread them out for readability
if !is_short_attr_list
&& attributes.len() <= 1
&& spreads.is_empty()
&& !has_trailing_comments
&& !has_postbrace_comments
{
if children.is_empty() {
opt_level = ShortOptimization::Oneliner;
} else {
opt_level = ShortOptimization::PropsOnTop;
}
}
// if we have few children and few attributes, make it a one-liner
if is_short_attr_list && is_small_children {
if children_len.unwrap() + attr_len + self.out.indent_level * 4 < 100 {
opt_level = ShortOptimization::Oneliner;
} else {
opt_level = ShortOptimization::PropsOnTop;
}
}
// If there's nothing at all, empty optimization
if attributes.is_empty()
&& children.is_empty()
&& spreads.is_empty()
&& !has_trailing_comments
{
opt_level = ShortOptimization::Empty;
// Write comments if they exist
self.write_inline_comments(brace.span.span().start(), 1)?;
self.write_todo_body(brace)?;
}
// multiline handlers bump everything down
if attr_len > 1000 || self.out.indent.split_line_attributes() {
opt_level = ShortOptimization::NoOpt;
}
let has_children = !children.is_empty();
match opt_level {
ShortOptimization::Empty => {}
ShortOptimization::Oneliner => {
write!(self.out, " ")?;
self.write_attributes(attributes, spreads, true, brace, has_children)?;
if !children.is_empty() && !attributes.is_empty() {
write!(self.out, " ")?;
}
let mut children_iter = children.iter().peekable();
while let Some(child) = children_iter.next() {
self.write_ident(child)?;
if children_iter.peek().is_some() {
write!(self.out, " ")?;
}
}
write!(self.out, " ")?;
}
ShortOptimization::PropsOnTop => {
if !attributes.is_empty() {
write!(self.out, " ")?;
}
self.write_attributes(attributes, spreads, true, brace, has_children)?;
if !children.is_empty() {
self.out.new_line()?;
self.write_body_indented(children)?;
}
self.out.tabbed_line()?;
}
ShortOptimization::NoOpt => {
self.write_inline_comments(brace.span.span().start(), 1)?;
self.out.new_line()?;
self.write_attributes(attributes, spreads, false, brace, has_children)?;
if !children.is_empty() {
self.out.new_line()?;
self.write_body_indented(children)?;
}
self.out.tabbed_line()?;
}
}
// Write trailing comments
if matches!(
opt_level,
ShortOptimization::NoOpt | ShortOptimization::PropsOnTop
) && self.leading_row_is_empty(brace.span.span().end())
{
let comments = self.accumulate_full_line_comments(brace.span.span().end());
if !comments.is_empty() {
self.apply_line_comments(comments)?;
self.out.tab()?;
}
}
write!(self.out, "}}")?;
Ok(())
}
fn write_attributes(
&mut self,
attributes: &[Attribute],
spreads: &[Spread],
props_same_line: bool,
brace: &Brace,
has_children: bool,
) -> Result {
enum AttrType<'a> {
Attr(&'a Attribute),
Spread(&'a Spread),
}
let mut attr_iter = attributes
.iter()
.map(AttrType::Attr)
.chain(spreads.iter().map(AttrType::Spread))
.peekable();
let has_attributes = !attributes.is_empty() || !spreads.is_empty();
while let Some(attr) = attr_iter.next() {
self.out.indent_level += 1;
if !props_same_line {
self.write_attr_comments(
brace,
match attr {
AttrType::Attr(attr) => attr.span(),
AttrType::Spread(attr) => attr.expr.span(),
},
)?;
}
self.out.indent_level -= 1;
if !props_same_line {
self.out.indented_tab()?;
}
match attr {
AttrType::Attr(attr) => self.write_attribute(attr)?,
AttrType::Spread(attr) => self.write_spread_attribute(&attr.expr)?,
}
let span = match attr {
AttrType::Attr(attr) => attr
.comma
.as_ref()
.map(|c| c.span())
.unwrap_or_else(|| self.total_span_of_attr(attr)),
AttrType::Spread(attr) => attr.span(),
};
let has_more = attr_iter.peek().is_some();
let should_finish_comma = has_attributes && has_children || !props_same_line;
if has_more || should_finish_comma {
write!(self.out, ",")?;
}
if !props_same_line {
self.write_inline_comments(span.end(), 0)?;
}
if props_same_line && !has_more {
self.write_inline_comments(span.end(), 0)?;
}
if props_same_line && has_more {
write!(self.out, " ")?;
}
if !props_same_line && has_more {
self.out.new_line()?;
}
}
Ok(())
}
fn write_attribute(&mut self, attr: &Attribute) -> Result {
self.write_attribute_name(&attr.name)?;
// if the attribute is a shorthand, we don't need to write the colon, just the name
if !attr.can_be_shorthand() {
write!(self.out, ": ")?;
self.write_attribute_value(&attr.value)?;
}
Ok(())
}
fn write_attribute_name(&mut self, attr: &AttributeName) -> Result {
match attr {
AttributeName::BuiltIn(name) => write!(self.out, "{}", name),
AttributeName::Custom(name) => write!(self.out, "{}", name.to_token_stream()),
AttributeName::Spread(_) => unreachable!(),
}
}
fn write_attribute_value(&mut self, value: &AttributeValue) -> Result {
match value {
AttributeValue::IfExpr(if_chain) => {
self.write_attribute_if_chain(if_chain)?;
}
AttributeValue::AttrLiteral(value) => {
write!(self.out, "{value}")?;
}
AttributeValue::Shorthand(value) => {
write!(self.out, "{value}")?;
}
AttributeValue::EventTokens(closure) => {
self.out.indent_level += 1;
self.write_partial_expr(closure.as_expr(), closure.span())?;
self.out.indent_level -= 1;
}
AttributeValue::AttrExpr(value) => {
self.out.indent_level += 1;
self.write_partial_expr(value.as_expr(), value.span())?;
self.out.indent_level -= 1;
}
}
Ok(())
}
fn write_attribute_if_chain(&mut self, if_chain: &IfAttributeValue) -> Result {
let cond = self.unparse_expr(&if_chain.if_expr.cond);
write!(self.out, "if {cond} {{ ")?;
self.write_attribute_value(&if_chain.then_value)?;
write!(self.out, " }}")?;
match if_chain.else_value.as_deref() {
Some(AttributeValue::IfExpr(else_if_chain)) => {
write!(self.out, " else ")?;
self.write_attribute_if_chain(else_if_chain)?;
}
Some(other) => {
write!(self.out, " else {{ ")?;
self.write_attribute_value(other)?;
write!(self.out, " }}")?;
}
None => {}
}
Ok(())
}
fn write_attr_comments(&mut self, brace: &Brace, attr_span: Span) -> Result {
// There's a chance this line actually shares the same line as the previous
// Only write comments if the comments actually belong to this line
//
// to do this, we check if the attr span starts on the same line as the brace
// if it doesn't, we write the comments
let brace_line = brace.span.span().start().line;
let attr_line = attr_span.start().line;
if brace_line != attr_line {
// Get the raw line of the attribute
let line = self.src.get(attr_line - 1).unwrap_or(&"");
// Only write comments if the line is empty before the attribute start
let row_start = line.get(..attr_span.start().column - 1).unwrap_or("");
if !row_start.trim().is_empty() {
return Ok(());
}
self.write_comments(attr_span.start())?;
}
Ok(())
}
fn write_inline_comments(&mut self, final_span: LineColumn, offset: usize) -> Result {
let line = final_span.line;
let column = final_span.column;
let Some(src_line) = self.src.get(line - 1) else {
return Ok(());
};
// the line might contain emoji or other unicode characters - this will cause issues
let Some(mut whitespace) = src_line.get(column..).map(|s| s.trim()) else {
return Ok(());
};
if whitespace.is_empty() {
return Ok(());
}
whitespace = whitespace[offset..].trim();
// don't emit whitespace if the span is messed up for some reason
if final_span.line == 1 && final_span.column == 0 {
return Ok(());
};
if whitespace.starts_with("//") {
write!(self.out, " {whitespace}")?;
}
Ok(())
}
fn accumulate_full_line_comments(&mut self, loc: LineColumn) -> VecDeque<usize> {
// collect all comments upwards
// make sure we don't collect the comments of the node that we're currently under.
let start = loc;
let line_start = start.line - 1;
let mut comments = VecDeque::new();
// don't emit whitespace if the span is messed up for some reason
if loc.line == 1 && loc.column == 0 {
return comments;
};
let Some(lines) = self.src.get(..line_start) else {
return comments;
};
// We go backwards to collect comments and empty lines. We only want to keep one empty line,
// the rest should be `//` comments
let mut last_line_was_empty = false;
for (id, line) in lines.iter().enumerate().rev() {
let trimmed = line.trim();
if trimmed.starts_with("//") {
comments.push_front(id);
last_line_was_empty = false;
} else if trimmed.is_empty() {
if !last_line_was_empty {
comments.push_front(id);
last_line_was_empty = true;
}
continue;
} else {
break;
}
}
// If there is more than 1 comment, make sure the first comment is not an empty line
if comments.len() > 1 {
if let Some(&first) = comments.back() {
if self.src[first].trim().is_empty() {
comments.pop_back();
}
}
}
comments
}
fn apply_line_comments(&mut self, mut comments: VecDeque<usize>) -> Result {
while let Some(comment_line) = comments.pop_front() {
let Some(line) = self.src.get(comment_line) else {
continue;
};
let line = &line.trim();
if line.is_empty() {
self.out.new_line()?;
} else {
self.out.tab()?;
writeln!(self.out, "{}", line.trim())?;
}
}
Ok(())
}
fn write_comments(&mut self, loc: LineColumn) -> Result {
let comments = self.accumulate_full_line_comments(loc);
self.apply_line_comments(comments)?;
Ok(())
}
fn attr_value_len(&mut self, value: &AttributeValue) -> usize {
match value {
AttributeValue::IfExpr(if_chain) => {
let condition_len = self.retrieve_formatted_expr(&if_chain.if_expr.cond).len();
let value_len = self.attr_value_len(&if_chain.then_value);
let if_len = 2;
let brace_len = 2;
let space_len = 2;
let else_len = if_chain
.else_value
.as_ref()
.map(|else_value| self.attr_value_len(else_value) + 1)
.unwrap_or_default();
condition_len + value_len + if_len + brace_len + space_len + else_len
}
AttributeValue::AttrLiteral(lit) => lit.to_string().len(),
AttributeValue::Shorthand(expr) => {
let span = &expr.span();
span.end().line - span.start().line
}
AttributeValue::AttrExpr(expr) => expr
.as_expr()
.map(|expr| self.attr_expr_len(&expr))
.unwrap_or(100000),
AttributeValue::EventTokens(closure) => closure
.as_expr()
.map(|expr| self.attr_expr_len(&expr))
.unwrap_or(100000),
}
}
fn attr_expr_len(&mut self, expr: &Expr) -> usize {
let out = self.retrieve_formatted_expr(expr);
if out.contains('\n') {
100000
} else {
out.len()
}
}
fn is_short_attrs(
&mut self,
_brace: &Brace,
attributes: &[Attribute],
spreads: &[Spread],
) -> usize {
let mut total = 0;
// No more than 3 attributes before breaking the line
if attributes.len() > 3 {
return 100000;
}
for attr in attributes {
if self.current_span_is_primary(attr.span().start()) {
if let Some(lines) = self.src.get(..attr.span().start().line - 1) {
'line: for line in lines.iter().rev() {
match (line.trim().starts_with("//"), line.is_empty()) {
(true, _) => return 100000,
(_, true) => continue 'line,
_ => break 'line,
}
}
};
}
total += match &attr.name {
AttributeName::BuiltIn(name) => {
let name = name.to_string();
name.len()
}
AttributeName::Custom(name) => name.value().len() + 2,
AttributeName::Spread(_) => unreachable!(),
};
if attr.can_be_shorthand() {
total += 2;
} else {
total += self.attr_value_len(&attr.value);
}
total += 6;
}
for spread in spreads {
let expr_len = self.retrieve_formatted_expr(&spread.expr).len();
total += expr_len + 3;
}
total
}
fn write_todo_body(&mut self, brace: &Brace) -> std::fmt::Result {
let span = brace.span.span();
let start = span.start();
let end = span.end();
if start.line == end.line {
return Ok(());
}
writeln!(self.out)?;
for idx in start.line..end.line {
let Some(line) = self.src.get(idx) else {
continue;
};
if line.trim().starts_with("//") {
for _ in 0..self.out.indent_level + 1 {
write!(self.out, " ")?
}
writeln!(self.out, "{}", line.trim())?;
}
}
for _ in 0..self.out.indent_level {
write!(self.out, " ")?
}
Ok(())
}
fn write_partial_expr(&mut self, expr: syn::Result<Expr>, src_span: Span) -> Result {
let Ok(expr) = expr else {
self.invalid_exprs.push(src_span);
return Err(std::fmt::Error);
};
thread_local! {
static COMMENT_REGEX: Regex = Regex::new("\"[^\"]*\"|(//.*)").unwrap();
}
let pretty_expr = self.retrieve_formatted_expr(&expr).to_string();
// Adding comments back to the formatted expression
let source_text = src_span.source_text().unwrap_or_default();
let mut source_lines = source_text.lines().peekable();
let mut output = String::from("");
let mut printed_empty_line = false;
if source_lines.peek().is_none() {
output = pretty_expr;
} else {
for line in pretty_expr.lines() {
let compacted_pretty_line = line.replace(" ", "").replace(",", "");
let trimmed_pretty_line = line.trim();
// Nested expressions might have comments already. We handle writing all of those
// at the outer level, so we skip them here
if trimmed_pretty_line.starts_with("//") {
continue;
}
if !output.is_empty() {
output.push('\n');
}
// pull down any source lines with whitespace until we hit a line that matches our current line.
while let Some(src) = source_lines.peek() {
let trimmed_src = src.trim();
// Write comments and empty lines as they are
if trimmed_src.starts_with("//") || trimmed_src.is_empty() {
if !trimmed_src.is_empty() {
// Match the whitespace of the incoming source line
for s in line.chars().take_while(|c| c.is_whitespace()) {
output.push(s);
}
// Bump out the indent level if the line starts with a closing brace (ie we're at the end of a block)
if matches!(trimmed_pretty_line.chars().next(), Some(')' | '}' | ']')) {
output.push_str(self.out.indent.indent_str());
}
printed_empty_line = false;
output.push_str(trimmed_src);
output.push('\n');
} else if !printed_empty_line {
output.push('\n');
printed_empty_line = true;
}
_ = source_lines.next();
continue;
}
let compacted_src_line = src.replace(" ", "").replace(",", "");
// If this source line matches our pretty line, we stop pulling down
if compacted_src_line.contains(&compacted_pretty_line) {
break;
}
// Otherwise, consume this source line and keep going
_ = source_lines.next();
}
// Once all whitespace is written, write the pretty line
output.push_str(line);
printed_empty_line = false;
// And then pull the corresponding source line
let source_line = source_lines.next();
// And then write any inline comments
if let Some(source_line) = source_line {
if let Some(captures) = COMMENT_REGEX.with(|f| f.captures(source_line)) {
if let Some(comment) = captures.get(1) {
output.push_str(" // ");
output.push_str(comment.as_str().replace("//", "").trim());
}
}
}
}
}
self.write_mulitiline_tokens(output)?;
Ok(())
}
fn write_mulitiline_tokens(&mut self, out: String) -> Result {
let mut lines = out.split('\n').peekable();
let first = lines.next().unwrap();
// a one-liner for whatever reason
// Does not need a new line
if lines.peek().is_none() {
write!(self.out, "{first}")?;
} else {
writeln!(self.out, "{first}")?;
while let Some(line) = lines.next() {
if !line.trim().is_empty() {
self.out.tab()?;
}
write!(self.out, "{line}")?;
if lines.peek().is_none() {
write!(self.out, "")?;
} else {
writeln!(self.out)?;
}
}
}
Ok(())
}
fn write_spread_attribute(&mut self, attr: &Expr) -> Result {
let formatted = self.unparse_expr(attr);
let mut lines = formatted.lines();
let first_line = lines.next().unwrap();
write!(self.out, "..{first_line}")?;
for line in lines {
self.out.indented_tabbed_line()?;
write!(self.out, "{line}")?;
}
Ok(())
}
// check if the children are short enough to be on the same line
// We don't have the notion of current line depth - each line tries to be < 80 total
// returns the total line length if it's short
// returns none if the length exceeds the limit
// I think this eventually becomes quadratic :(
fn is_short_children(&mut self, children: &[BodyNode]) -> syn::Result<Option<usize>> {
if children.is_empty() {
return Ok(Some(0));
}
// Any comments push us over the limit automatically
if self.children_have_comments(children) {
return Ok(None);
}
let res = match children {
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/src/buffer.rs | packages/autofmt/src/buffer.rs | //! The output buffer that supports some helpful methods
//! These are separate from the input so we can lend references between the two
use std::fmt::{Result, Write};
use dioxus_rsx::IfmtInput;
use crate::indent::IndentOptions;
/// The output buffer that tracks indent and string
#[derive(Debug, Default)]
pub struct Buffer {
pub buf: String,
pub indent_level: usize,
pub indent: IndentOptions,
}
impl Buffer {
// Create a new line and tab it to the current tab level
pub fn tabbed_line(&mut self) -> Result {
self.new_line()?;
self.tab()
}
// Create a new line and tab it to the current tab level
pub fn indented_tabbed_line(&mut self) -> Result {
self.new_line()?;
self.indented_tab()
}
pub fn tab(&mut self) -> Result {
self.write_tabs(self.indent_level)
}
pub fn indented_tab(&mut self) -> Result {
self.write_tabs(self.indent_level + 1)
}
pub fn write_tabs(&mut self, num: usize) -> std::fmt::Result {
for _ in 0..num {
write!(self.buf, "{}", self.indent.indent_str())?
}
Ok(())
}
pub fn new_line(&mut self) -> Result {
writeln!(self.buf)
}
pub fn write_text(&mut self, text: &IfmtInput) -> Result {
write!(self.buf, "{}", text.to_string_with_quotes())
}
}
impl std::fmt::Write for Buffer {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.buf.push_str(s);
Ok(())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/tests/srcless.rs | packages/autofmt/tests/srcless.rs | use dioxus_rsx::CallBody;
use syn::parse_quote;
macro_rules! test_case {
(
$path:literal
) => {
works(include!($path), include_str!($path))
};
}
/// Ensure we can write RSX blocks without a source file
///
/// Useful in code generation use cases where we still want formatted code.
#[test]
fn write_block_out() {
test_case!("./srcless/basic_expr.rsx");
test_case!("./srcless/asset.rsx");
}
fn works(parsed: CallBody, src: &str) {
let block = dioxus_autofmt::write_block_out(&parsed).unwrap();
let src = src
.trim()
.trim_start_matches("parse_quote! {")
.trim_end_matches('}');
// normalize line endings for windows tests to pass
pretty_assertions::assert_eq!(
block.trim().lines().collect::<Vec<_>>().join("\n"),
src.trim().lines().collect::<Vec<_>>().join("\n")
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/tests/wrong.rs | packages/autofmt/tests/wrong.rs | #![allow(deprecated)]
use dioxus_autofmt::{IndentOptions, IndentType};
macro_rules! twoway {
($val:literal => $name:ident ($indent:expr)) => {
#[test]
fn $name() {
let src_right = include_str!(concat!("./wrong/", $val, ".rsx"));
let src_wrong = include_str!(concat!("./wrong/", $val, ".wrong.rsx"));
let parsed = syn::parse_file(src_wrong)
.expect("fmt_file should only be called on valid syn::File files");
let formatted =
dioxus_autofmt::try_fmt_file(src_wrong, &parsed, $indent).unwrap_or_default();
let out = dioxus_autofmt::apply_formats(src_wrong, formatted);
// normalize line endings
let out = out.replace("\r", "");
let src_right = src_right.replace("\r", "");
pretty_assertions::assert_eq!(&src_right, &out);
}
};
}
twoway!("comments-4sp" => comments_4sp (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("comments-tab" => comments_tab (IndentOptions::new(IndentType::Tabs, 4, false)));
twoway!("multi-4sp" => multi_4sp (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("multi-tab" => multi_tab (IndentOptions::new(IndentType::Tabs, 4, false)));
twoway!("multiexpr-4sp" => multiexpr_4sp (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("multiexpr-tab" => multiexpr_tab (IndentOptions::new(IndentType::Tabs, 4, false)));
twoway!("multiexpr-many" => multiexpr_many (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("simple-combo-expr" => simple_combo_expr (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("oneline-expand" => online_expand (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("shortened" => shortened (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("syntax_error" => syntax_error (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("skipfail" => skipfail (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("comments-inline-4sp" => comments_inline_4sp (IndentOptions::new(IndentType::Spaces, 4, false)));
twoway!("comments-attributes-4sp" => comments_attributes_4sp (IndentOptions::new(IndentType::Spaces, 4, false)));
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/tests/samples.rs | packages/autofmt/tests/samples.rs | #![allow(deprecated)]
macro_rules! twoway {
(
$(
// doc attrs
$( #[doc = $doc:expr] )*
$name:ident,
)*
) => {
$(
$( #[doc = $doc] )*
#[test]
fn $name() {
let src = include_str!(concat!("./samples/", stringify!($name), ".rsx"));
let formatted = dioxus_autofmt::fmt_file(src, Default::default());
let out = dioxus_autofmt::apply_formats(src, formatted);
// normalize line endings
let out = out.replace("\r", "");
let src = src.replace("\r", "");
pretty_assertions::assert_eq!(&src, &out);
}
)*
};
}
twoway![
attributes,
basic_expr,
collapse_expr,
comments,
commentshard,
complex,
docsite,
emoji,
fat_exprs,
ifchain_forloop,
immediate_expr,
key,
letsome,
long_exprs,
long,
manual_props,
many_exprs,
messy_indent,
misplaced,
multirsx,
nested,
raw_strings,
reallylong,
shorthand,
simple,
skip,
spaces,
staged,
t2,
tiny,
tinynoopt,
trailing_expr,
oneline,
prop_rsx,
asset,
collapse,
expr_on_conditional,
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/autofmt/tests/error_handling.rs | packages/autofmt/tests/error_handling.rs | #[test]
fn no_parse() {
let src = include_str!("./partials/no_parse.rsx");
assert!(syn::parse_file(src).is_err());
}
#[test]
fn parses_but_fmt_fails() {
let src = include_str!("./partials/wrong.rsx");
let file = syn::parse_file(src).unwrap();
let formatted = dioxus_autofmt::try_fmt_file(src, &file, Default::default());
assert!(&formatted.is_err());
}
#[test]
fn parses_and_is_okay() {
let src = include_str!("./partials/okay.rsx");
let file = syn::parse_file(src).unwrap();
let formatted = dioxus_autofmt::try_fmt_file(src, &file, Default::default()).unwrap();
assert_ne!(formatted.len(), 0);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-telemetry/src/lib.rs | packages/cli-telemetry/src/lib.rs | //! # Telemetry for the Dioxus CLI
//!
//! Dioxus uses telemetry in the CLI to get insight into metrics like performance, panics, and usage
//! of various arguments. This data helps us track down bugs and improve quality of the tooling.
//!
//! Usage of telemetry in open source products can be controversial. Our goal here is to collect
//! minimally invasive data used exclusively to improve our tooling. Github issues only show *some*
//! of the problem, but many users stumble into issues which go unreported.
//!
//! Our policy follows:
//! - minimally invasive
//! - anonymous
//! - periodic
//! - transparent
//! - easy to disable
//!
//! We send a heartbeat when the CLI is executed and then rollups of logs over time.
//! - Heartbeat: helps us track version distribution of the CLI and critical "failures on launch" useful during new version rollouts.
//! - Rollups: helps us track performance and issues over time, as well as usage of various commands.
//!
//! Rollups are not done in background processes, but rather directly by the `dx` CLI.
//! If you don't run the CLI, then we won't send any data.
//!
//! We don't collect any PII, but we do collect three "controversial" pieces of data:
//! - the target triple of your system (OS, arch, etc)
//! - a session ID which is a random number generated on each run
//! - a distinct ID per `.dx` installation which is a random number generated on initial run.
//!
//! The distinct ID is used to track the same installation over time, but it is not tied to any user
//! account or PII. Since `dx` doesn't have any accounts or authentication mechanism, this ID is used
//! as a "best effort" identifier. If you still want to participate in telemetry but don't want a
//! distinct ID, you can replace the stable_id.json file in the `.dx` directory with an empty string.
//!
//! In the CLI, you can disable this by using any of the methods:
//! - installing with the "disable-telemetry" feature flag
//! - setting TELEMETRY=false in your env
//! - setting `dx config set disable-telemetry true`
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashMap},
time::SystemTime,
};
/// An event's data, corresponding roughly to data collected from an individual trace.
///
/// This can be something like a build, bundle, translate, etc
/// We collect the phases of the build in a list of events to get a better sense of how long
/// it took.
///
/// Note that this is just the data and does not include the reporter information.
///
/// On the analytics, side, we reconstruct the trace messages into a sequence of events, using
/// the stage as a marker.
///
/// If the event contains a stack trace, it is considered a crash event and will be sent to the crash reporting service.
///
/// We store this type on disk without the reporter information or any information about the CLI.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TelemetryEventData {
/// The name of the command that was run, e.g. "dx build", "dx bundle", "dx serve"
pub command: String,
/// The action that was taken, e.g. "build", "bundle", "cli_invoked", "cli_crashed" etc
pub action: String,
/// An additional message to include in the event, e.g. "start", "end", "error", etc
pub message: String,
/// The "name" of the error. In our case, usually" "RustError" or "RustPanic". In other languages
/// this might be the exception type. In Rust, this is usually the name of the error type. (e.g. "std::io::Error", etc)
pub error_type: Option<String>,
/// Whether the event was handled or not. Unhandled errors are the default, but some we recover from (like hotpatching issues).
pub error_handled: bool,
/// Additional values to include in the event, e.g. "duration", "enabled", etc.
pub values: HashMap<String, serde_json::Value>,
/// Timestamp of the event, in UTC, derived from the user's system time. Might not be reliable.
pub time: DateTime<Utc>,
/// The module where the event occurred, stripped of paths for privacy.
pub module: Option<String>,
/// The file or module where the event occurred, stripped of paths for privacy, relative to the monorepo root.
pub file: Option<String>,
/// The line and column where the event occurred, if applicable.
pub line: Option<u32>,
/// The column where the event occurred, if applicable.
pub column: Option<u32>,
/// The stack frames of the event, if applicable.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stack_frames: Vec<StackFrame>,
}
impl TelemetryEventData {
pub fn new(name: impl ToString, message: impl ToString) -> Self {
Self {
command: std::env::args()
.nth(1)
.unwrap_or_else(|| "unknown".to_string()),
action: strip_paths(&name.to_string()),
message: strip_paths(&message.to_string()),
file: None,
module: None,
time: DateTime::<Utc>::from(SystemTime::now()),
values: HashMap::new(),
error_type: None,
column: None,
line: None,
stack_frames: vec![],
error_handled: false,
}
}
pub fn with_value<K: ToString, V: serde::Serialize>(mut self, key: K, value: V) -> Self {
let mut value = serde_json::to_value(value).unwrap();
strip_paths_value(&mut value);
self.values.insert(key.to_string(), value);
self
}
pub fn with_module(mut self, module: impl ToString) -> Self {
self.module = Some(strip_paths(&module.to_string()));
self
}
pub fn with_file(mut self, file: impl ToString) -> Self {
self.file = Some(strip_paths(&file.to_string()));
self
}
pub fn with_line_column(mut self, line: u32, column: u32) -> Self {
self.line = Some(line);
self.column = Some(column);
self
}
pub fn with_error_handled(mut self, error_handled: bool) -> Self {
self.error_handled = error_handled;
self
}
pub fn with_error_type(mut self, error_type: String) -> Self {
self.error_type = Some(error_type);
self
}
pub fn with_stack_frames(mut self, stack_frames: Vec<StackFrame>) -> Self {
self.stack_frames = stack_frames;
self
}
pub fn with_values(mut self, fields: serde_json::Map<String, serde_json::Value>) -> Self {
for (key, value) in fields {
self = self.with_value(key, value);
}
self
}
pub fn to_json(&self) -> serde_json::Value {
serde_json::to_value(self).unwrap()
}
}
/// Display implementation for TelemetryEventData, such that you can use it in tracing macros with the "%" syntax.
impl std::fmt::Display for TelemetryEventData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", serde_json::to_string(self).unwrap())
}
}
/// A serialized stack frame, in a format that matches PostHog's stack frame format.
///
/// Read more:
/// <https://github.com/PostHog/posthog-js/blob/6e35a639a4d06804f6844cbde15adf11a069b92b/packages/node/src/extensions/error-tracking/types.ts#L55>
///
/// Supposedly, this is compatible with Sentry's stack frames as well. In the CLI we use sentry-backtrace
/// even though we don't actually use sentry.
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case")]
pub struct StackFrame {
pub raw_id: String,
pub mangled_name: String,
pub resolved_name: String,
pub lang: String,
pub resolved: bool,
pub platform: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filename: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub module: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lineno: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub colno: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub abs_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_line: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub pre_context: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub post_context: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub in_app: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instruction_addr: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub addr_mode: Option<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub vars: BTreeMap<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub chunk_id: Option<String>,
}
// If the CLI is compiled locally, it can contain backtraces which contain the home path with the username in it.
pub fn strip_paths(string: &str) -> String {
// Strip the home path from any paths in the backtrace
let home_dir = dirs::home_dir().unwrap_or_default();
// Strip every path between the current path and the home directory
let mut cwd = std::env::current_dir().unwrap_or_default();
let mut string = string.to_string();
loop {
string = string.replace(&*cwd.to_string_lossy(), "<stripped>");
let Some(parent) = cwd.parent() else {
break;
};
cwd = parent.to_path_buf();
if cwd == home_dir {
break;
}
}
// Finally, strip the home directory itself (in case the cwd is outside the home directory)
string.replace(&*home_dir.to_string_lossy(), "~")
}
fn strip_paths_value(value: &mut serde_json::Value) {
match value {
serde_json::Value::String(s) => *s = strip_paths(s),
serde_json::Value::Object(map) => map.values_mut().for_each(strip_paths_value),
serde_json::Value::Array(arr) => arr.iter_mut().for_each(strip_paths_value),
_ => {}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/history/src/lib.rs | packages/history/src/lib.rs | use dioxus_core::{provide_context, provide_root_context};
use std::{rc::Rc, sync::Arc};
mod memory;
pub use memory::*;
/// Get the history provider for the current platform if the platform doesn't implement a history functionality.
pub fn history() -> Rc<dyn History> {
match dioxus_core::try_consume_context::<Rc<dyn History>>() {
Some(history) => history,
None => {
tracing::error!("Unable to find a history provider in the renderer. Make sure your renderer supports the Router. Falling back to the in-memory history provider.");
provide_root_context(Rc::new(MemoryHistory::default()))
}
}
}
/// Provide a history context to the current component.
pub fn provide_history_context(history: Rc<dyn History>) {
provide_context(history);
}
pub trait History {
/// Get the path of the current URL.
///
/// **Must start** with `/`. **Must _not_ contain** the prefix.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # #[component]
/// # fn OtherPage() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/some-other-page")]
/// OtherPage {},
/// }
/// let mut history = dioxus::history::MemoryHistory::default();
/// assert_eq!(history.current_route(), "/");
///
/// history.push(Route::OtherPage {}.to_string());
/// assert_eq!(history.current_route(), "/some-other-page");
/// ```
#[must_use]
fn current_route(&self) -> String;
/// Get the current path prefix of the URL.
///
/// Not all [`History`]s need a prefix feature. It is meant for environments where a
/// dioxus-router-core-routed application is not running on `/`. The [`History`] is responsible
/// for removing the prefix from the dioxus-router-core-internal path, and also for adding it back in
/// during navigation. This functions value is only used for creating `href`s (e.g. for SSR or
/// display (but not navigation) in a web app).
fn current_prefix(&self) -> Option<String> {
None
}
/// Check whether there is a previous page to navigate back to.
///
/// If a [`History`] cannot know this, it should return [`true`].
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # fn Other() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/other")]
/// Other {},
/// }
/// let mut history = dioxus::history::MemoryHistory::default();
/// assert_eq!(history.can_go_back(), false);
///
/// history.push(Route::Other {}.to_string());
/// assert_eq!(history.can_go_back(), true);
/// ```
#[must_use]
fn can_go_back(&self) -> bool {
true
}
/// Go back to a previous page.
///
/// If a [`History`] cannot go to a previous page, it should do nothing. This method
/// might be called, even if `can_go_back` returns [`false`].
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # #[component]
/// # fn OtherPage() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/some-other-page")]
/// OtherPage {},
/// }
/// let mut history = dioxus::history::MemoryHistory::default();
/// assert_eq!(history.current_route(), "/");
///
/// history.go_back();
/// assert_eq!(history.current_route(), "/");
///
/// history.push(Route::OtherPage {}.to_string());
/// assert_eq!(history.current_route(), "/some-other-page");
///
/// history.go_back();
/// assert_eq!(history.current_route(), "/");
/// ```
fn go_back(&self);
/// Check whether there is a future page to navigate forward to.
///
/// If a [`History`] cannot know this, it should return [`true`].
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # #[component]
/// # fn OtherPage() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/some-other-page")]
/// OtherPage {},
/// }
/// let mut history = dioxus::history::MemoryHistory::default();
/// assert_eq!(history.can_go_forward(), false);
///
/// history.push(Route::OtherPage {}.to_string());
/// assert_eq!(history.can_go_forward(), false);
///
/// history.go_back();
/// assert_eq!(history.can_go_forward(), true);
/// ```
#[must_use]
fn can_go_forward(&self) -> bool {
true
}
/// Go forward to a future page.
///
/// If a [`History`] cannot go to a previous page, it should do nothing. This method
/// might be called, even if `can_go_forward` returns [`false`].
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # #[component]
/// # fn OtherPage() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/some-other-page")]
/// OtherPage {},
/// }
/// let mut history = dioxus::history::MemoryHistory::default();
/// history.push(Route::OtherPage {}.to_string());
/// assert_eq!(history.current_route(), Route::OtherPage {}.to_string());
///
/// history.go_back();
/// assert_eq!(history.current_route(), Route::Index {}.to_string());
///
/// history.go_forward();
/// assert_eq!(history.current_route(), Route::OtherPage {}.to_string());
/// ```
fn go_forward(&self);
/// Go to another page.
///
/// This should do three things:
/// 1. Merge the current URL with the `path` parameter (which may also include a query part).
/// 2. Remove the previous URL to the navigation history.
/// 3. Clear the navigation future.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # #[component]
/// # fn OtherPage() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/some-other-page")]
/// OtherPage {},
/// }
/// let mut history = dioxus::history::MemoryHistory::default();
/// assert_eq!(history.current_route(), Route::Index {}.to_string());
///
/// history.push(Route::OtherPage {}.to_string());
/// assert_eq!(history.current_route(), Route::OtherPage {}.to_string());
/// assert!(history.can_go_back());
/// ```
fn push(&self, route: String);
/// Replace the current page with another one.
///
/// This should merge the current URL with the `path` parameter (which may also include a query
/// part). In contrast to the `push` function, the navigation history and future should stay
/// untouched.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # #[component]
/// # fn OtherPage() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/some-other-page")]
/// OtherPage {},
/// }
/// let mut history = dioxus::history::MemoryHistory::default();
/// assert_eq!(history.current_route(), Route::Index {}.to_string());
///
/// history.replace(Route::OtherPage {}.to_string());
/// assert_eq!(history.current_route(), Route::OtherPage {}.to_string());
/// assert!(!history.can_go_back());
/// ```
fn replace(&self, path: String);
/// Navigate to an external URL.
///
/// This should navigate to an external URL, which isn't controlled by the router. If a
/// [`History`] cannot do that, it should return [`false`], otherwise [`true`].
///
/// Returning [`false`] will cause the router to handle the external navigation failure.
#[allow(unused_variables)]
fn external(&self, url: String) -> bool {
false
}
/// Provide the [`History`] with an update callback.
///
/// Some [`History`]s may receive URL updates from outside the router. When such
/// updates are received, they should call `callback`, which will cause the router to update.
#[allow(unused_variables)]
fn updater(&self, callback: Arc<dyn Fn() + Send + Sync>) {}
/// Whether the router should include the legacy prevent default attribute instead of the new
/// prevent default method. This should only be used by liveview.
fn include_prevent_default(&self) -> bool {
false
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/history/src/memory.rs | packages/history/src/memory.rs | use std::cell::RefCell;
use crate::History;
struct MemoryHistoryState {
current: String,
history: Vec<String>,
future: Vec<String>,
}
/// A [`History`] provider that stores all navigation information in memory.
pub struct MemoryHistory {
state: RefCell<MemoryHistoryState>,
base_path: Option<String>,
}
impl Default for MemoryHistory {
fn default() -> Self {
Self::with_initial_path("/")
}
}
impl MemoryHistory {
/// Create a [`MemoryHistory`] starting at `path`.
///
/// ```rust
/// # use dioxus::prelude::*;
/// # #[component]
/// # fn Index() -> Element { VNode::empty() }
/// # #[component]
/// # fn OtherPage() -> Element { VNode::empty() }
/// #[derive(Clone, Routable, Debug, PartialEq)]
/// enum Route {
/// #[route("/")]
/// Index {},
/// #[route("/some-other-page")]
/// OtherPage {},
/// }
///
/// let mut history = dioxus_history::MemoryHistory::with_initial_path(Route::Index {});
/// assert_eq!(history.current_route(), Route::Index {}.to_string());
/// assert_eq!(history.can_go_back(), false);
/// ```
pub fn with_initial_path(path: impl ToString) -> Self {
Self {
state: MemoryHistoryState{
current: path.to_string().parse().unwrap_or_else(|err| {
panic!("index route does not exist:\n{err}\n use MemoryHistory::with_initial_path to set a custom path")
}),
history: Vec::new(),
future: Vec::new(),
}.into(),
base_path: None,
}
}
/// Set the base path for the history. All routes will be prefixed with this path when rendered.
///
/// ```rust
/// # use dioxus_history::*;
/// let mut history = MemoryHistory::default().with_prefix("/my-app");
///
/// // The base path is set to "/my-app"
/// assert_eq!(history.current_prefix(), Some("/my-app".to_string()));
/// ```
pub fn with_prefix(mut self, prefix: impl ToString) -> Self {
self.base_path = Some(prefix.to_string());
self
}
}
impl History for MemoryHistory {
fn current_prefix(&self) -> Option<String> {
self.base_path.clone()
}
fn current_route(&self) -> String {
self.state.borrow().current.clone()
}
fn can_go_back(&self) -> bool {
!self.state.borrow().history.is_empty()
}
fn go_back(&self) {
let mut write = self.state.borrow_mut();
if let Some(last) = write.history.pop() {
let old = std::mem::replace(&mut write.current, last);
write.future.push(old);
}
}
fn can_go_forward(&self) -> bool {
!self.state.borrow().future.is_empty()
}
fn go_forward(&self) {
let mut write = self.state.borrow_mut();
if let Some(next) = write.future.pop() {
let old = std::mem::replace(&mut write.current, next);
write.history.push(old);
}
}
fn push(&self, new: String) {
let mut write = self.state.borrow_mut();
// don't push the same route twice
if write.current == new {
return;
}
let old = std::mem::replace(&mut write.current, new);
write.history.push(old);
write.future.clear();
}
fn replace(&self, path: String) {
let mut write = self.state.borrow_mut();
write.current = path;
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/attribute_groups.rs | packages/html/src/attribute_groups.rs | #![allow(non_upper_case_globals)]
#![allow(deprecated)]
use dioxus_core::HasAttributes;
use dioxus_core::IntoAttributeValue;
use dioxus_html_internal_macro::impl_extension_attributes;
use crate::AttributeDescription;
#[cfg(feature = "hot-reload-context")]
macro_rules! mod_method_mapping {
(
$matching:ident;
$(#[$attr:meta])*
$name:ident;
) => {
if $matching == stringify!($name) {
return Some((stringify!($name), None));
}
};
(
$matching:ident;
$(#[$attr:meta])*
$name:ident: $lit:literal;
) => {
if $matching == stringify!($name) {
return Some(($lit, None));
}
};
(
$matching:ident;
$(#[$attr:meta])*
$name:ident: $lit:literal in $ns:literal;
) => {
if $matching == stringify!($name) {
return Some(($lit, Some($ns)));
}
};
(
$matching:ident;
$(#[$attr:meta])*
$name:ident in $ns:literal;
) => {
if $matching == stringify!($name) {
return Some((stringify!($name), Some($ns)));
}
};
}
#[cfg(feature = "html-to-rsx")]
macro_rules! html_to_rsx_attribute_mapping {
(
$matching:ident;
$(#[$attr:meta])*
$name:ident;
) => {
if $matching == stringify!($name) {
return Some(stringify!($name));
}
};
(
$matching:ident;
$(#[$attr:meta])*
$name:ident: $lit:literal;
) => {
if $matching == $lit {
return Some(stringify!($name));
}
};
(
$matching:ident;
$(#[$attr:meta])*
$name:ident: $lit:literal in $ns:literal;
) => {
if $matching == $lit {
return Some(stringify!($name));
}
};
(
$matching:ident;
$(#[$attr:meta])*
$name:ident in $ns:literal;
) => {
if $matching == stringify!($name) {
return Some(stringify!($name));
}
};
}
macro_rules! mod_methods {
(
@base
$(#[$mod_attr:meta])*
$mod:ident;
$fn:ident;
$fn_html_to_rsx:ident;
$(
$(#[$attr:meta])*
$name:ident $(: $(no-$alias:ident)? $js_name:literal)? $(in $ns:literal)?;
)+
) => {
$(#[$mod_attr])*
pub mod $mod {
use super::*;
$(
mod_methods! {
@attr
$(#[$attr])*
$name $(: $(no-$alias)? $js_name)? $(in $ns)?;
}
)+
}
#[cfg(feature = "hot-reload-context")]
pub(crate) fn $fn(attr: &str) -> Option<(&'static str, Option<&'static str>)> {
$(
mod_method_mapping! {
attr;
$name $(: $js_name)? $(in $ns)?;
}
)*
None
}
#[cfg(feature = "html-to-rsx")]
#[doc = "Converts an HTML attribute to an RSX attribute"]
pub(crate) fn $fn_html_to_rsx(html: &str) -> Option<&'static str> {
$(
html_to_rsx_attribute_mapping! {
html;
$name $(: $js_name)? $(in $ns)?;
}
)*
None
}
impl_extension_attributes![$mod { $($name,)* }];
};
(
@attr
$(#[$attr:meta])*
$name:ident $(: no-alias $js_name:literal)? $(in $ns:literal)?;
) => {
$(#[$attr])*
///
/// ## Usage in rsx
///
/// ```rust, ignore
/// # use dioxus::prelude::*;
#[doc = concat!("let ", stringify!($name), " = \"value\";")]
///
/// rsx! {
/// // Attributes need to be under the element they modify
/// div {
/// // Attributes are followed by a colon and then the value of the attribute
#[doc = concat!(" ", stringify!($name), ": \"value\"")]
/// }
/// div {
/// // Or you can use the shorthand syntax if you have a variable in scope that has the same name as the attribute
#[doc = concat!(" ", stringify!($name), ",")]
/// }
/// };
/// ```
pub const $name: AttributeDescription = mod_methods! { $name $(: $js_name)? $(in $ns)?; };
};
(
@attr
$(#[$attr:meta])*
$name:ident $(: $js_name:literal)? $(in $ns:literal)?;
) => {
$(#[$attr])*
///
/// ## Usage in rsx
///
/// ```rust, ignore
/// # use dioxus::prelude::*;
#[doc = concat!("let ", stringify!($name), " = \"value\";")]
///
/// rsx! {
/// // Attributes need to be under the element they modify
/// div {
/// // Attributes are followed by a colon and then the value of the attribute
#[doc = concat!(" ", stringify!($name), ": \"value\"")]
/// }
/// div {
/// // Or you can use the shorthand syntax if you have a variable in scope that has the same name as the attribute
#[doc = concat!(" ", stringify!($name), ",")]
/// }
/// };
/// ```
$(
#[doc(alias = $js_name)]
)?
pub const $name: AttributeDescription = mod_methods! { $name $(: $js_name)? $(in $ns)?; };
};
// Rename the incoming ident and apply a custom namespace
( $name:ident: $lit:literal in $ns:literal; ) => { ($lit, Some($ns), false) };
// Custom namespace
( $name:ident in $ns:literal; ) => { (stringify!($name), Some($ns), false) };
// Rename the incoming ident
( $name:ident: $lit:literal; ) => { ($lit, None, false ) };
// Don't rename the incoming ident
( $name:ident; ) => { (stringify!($name), None, false) };
}
mod_methods! {
@base
global_attributes;
map_global_attributes;
map_html_global_attributes_to_rsx;
#[deprecated(note = "This attribute does nothing. For most renderers, you should prefer calling [`dioxus_core::Event::prevent_default`] on the event instead. For liveview, you can use `\"onclick\": (evt) => evt.prevent_default()` to prevent the default action for this element.")]
/// This attribute has been deprecated in favor of [`dioxus_core::Event::prevent_default`]
prevent_default: "dioxus-prevent-default";
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/accesskey>
accesskey;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autocapitalize>
autocapitalize;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/autofocus>
autofocus;
/// The HTML class attribute is used to specify a class for an HTML element.
///
/// ## Details
/// Multiple HTML elements can share the same class.
///
/// The class global attribute is a space-separated list of the case-sensitive classes of the element.
/// Classes allow CSS and Javascript to select and access specific elements via the class selectors or
/// functions like the DOM method document.getElementsByClassName.
///
/// ## Multiple Classes
///
/// If you include multiple classes in a single element dioxus will automatically join them with a space.
///
/// ```rust
/// # use dioxus::prelude::*;
/// rsx! {
/// div {
/// class: "my-class",
/// class: "my-other-class"
/// }
/// };
/// ```
///
/// ## Optional Classes
///
/// You can include optional attributes with an unterminated if statement as the value of the attribute. This is very useful for conditionally applying css classes:
///
/// ```rust
/// # use dioxus::prelude::*;
/// rsx! {
/// div {
/// class: if true {
/// "my-class"
/// },
/// class: if false {
/// "my-other-class"
/// }
/// }
/// };
/// ```
///
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class>
class;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable>
contenteditable;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir>
dir;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/draggable>
draggable;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/enterkeyhint>
enterkeyhint;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/exportparts>
exportparts;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden>
hidden;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id>
id;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode>
inputmode;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/is>
is;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemid>
itemid;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemprop>
itemprop;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemref>
itemref;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemscope>
itemscope;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/itemtype>
itemtype;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang>
lang;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce>
nonce;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/part>
part;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/popover>
popover;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/role>
role;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/slot>
slot;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/spellcheck>
spellcheck;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/style>
style;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex>
tabindex;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/title>
title;
/// <https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/translate>
translate;
/// dangerous_inner_html is Dioxus's replacement for using innerHTML in the browser DOM. In general, setting
/// HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS)
/// attack. So, you can set HTML directly from Dioxus, but you have to type out dangerous_inner_html to remind
/// yourself that it’s dangerous
dangerous_inner_html;
// This macro creates an explicit method call for each of the style attributes.
//
// The left token specifies the name of the attribute in the rsx! macro, and the right string literal specifies the
// actual name of the attribute generated.
//
// This roughly follows the html spec
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/align-content>
align_content: "align-content" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/align-items>
align_items: "align-items" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/align-self>
align_self: "align-self" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/alignment-adjust>
alignment_adjust: "alignment-adjust" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/alignment-baseline>
alignment_baseline: "alignment-baseline" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/all>
all in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/alt>
alt in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation>
animation in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay>
animation_delay: "animation-delay" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction>
animation_direction: "animation-direction" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-duration>
animation_duration: "animation-duration" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode>
animation_fill_mode: "animation-fill-mode" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-iteration-count>
animation_iteration_count: "animation-iteration-count" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-name>
animation_name: "animation-name" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state>
animation_play_state: "animation-play-state" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timing-function>
animation_timing_function: "animation-timing-function" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio>
aspect_ratio: "aspect-ratio" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/azimuth>
azimuth in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter>
backdrop_filter: "backdrop-filter" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/backface-visibility>
backface_visibility: "backface-visibility" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background>
background in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-attachment>
background_attachment: "background-attachment" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip>
background_clip: "background-clip" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-color>
background_color: "background-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-image>
background_image: "background-image" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-origin>
background_origin: "background-origin" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-position>
background_position: "background-position" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat>
background_repeat: "background-repeat" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-size>
background_size: "background-size" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/background-blend-mode>
background_blend_mode: "background-blend-mode" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/baseline-shift>
baseline_shift: "baseline-shift" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/bleed>
bleed in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/bookmark-label>
bookmark_label: "bookmark-label" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/bookmark-level>
bookmark_level: "bookmark-level" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/bookmark-state>
bookmark_state: "bookmark-state" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border>
border in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-color>
border_color: "border-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-style>
border_style: "border-style" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-width>
border_width: "border-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom>
border_bottom: "border-bottom" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-color>
border_bottom_color: "border-bottom-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-style>
border_bottom_style: "border-bottom-style" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-width>
border_bottom_width: "border-bottom-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-left>
border_left: "border-left" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-color>
border_left_color: "border-left-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-style>
border_left_style: "border-left-style" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width>
border_left_width: "border-left-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-right>
border_right: "border-right" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-color>
border_right_color: "border-right-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-style>
border_right_style: "border-right-style" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-width>
border_right_width: "border-right-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-top>
border_top: "border-top" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-color>
border_top_color: "border-top-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-style>
border_top_style: "border-top-style" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width>
border_top_width: "border-top-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse>
border_collapse: "border-collapse" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-image>
border_image: "border-image" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-outset>
border_image_outset: "border-image-outset" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-repeat>
border_image_repeat: "border-image-repeat" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-slice>
border_image_slice: "border-image-slice" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-source>
border_image_source: "border-image-source" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-width>
border_image_width: "border-image-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius>
border_radius: "border-radius" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-left-radius>
border_bottom_left_radius: "border-bottom-left-radius" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius>
border_bottom_right_radius: "border-bottom-right-radius" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-left-radius>
border_top_left_radius: "border-top-left-radius" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-right-radius>
border_top_right_radius: "border-top-right-radius" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing>
border_spacing: "border-spacing" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/bottom>
bottom in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/box-decoration-break>
box_decoration_break: "box-decoration-break" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow>
box_shadow: "box-shadow" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing>
box_sizing: "box-sizing" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/box-snap>
box_snap: "box-snap" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/break-after>
break_after: "break-after" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/break-before>
break_before: "break-before" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/break-inside>
break_inside: "break-inside" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/buffered-rendering>
buffered_rendering: "buffered-rendering" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/caption-side>
caption_side: "caption-side" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/clear>
clear in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/clear-side>
clear_side: "clear-side" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/clip>
clip in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path>
clip_path: "clip-path" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/clip-rule>
clip_rule: "clip-rule" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color>
color in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-adjust>
color_adjust: "color-adjust" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-correction>
color_correction: "color-correction" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation>
color_interpolation: "color-interpolation" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-interpolation-filters>
color_interpolation_filters: "color-interpolation-filters" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-profile>
color_profile: "color-profile" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/color-rendering>
color_rendering: "color-rendering" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-fill>
column_fill: "column-fill" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-gap>
column_gap: "column-gap" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule>
column_rule: "column-rule" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-color>
column_rule_color: "column-rule-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-style>
column_rule_style: "column-rule-style" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-width>
column_rule_width: "column-rule-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-span>
column_span: "column-span" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/columns>
columns in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-count>
column_count: "column-count" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/column-width>
column_width: "column-width" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/contain>
contain in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/content>
content in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/counter-increment>
counter_increment: "counter-increment" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/counter-reset>
counter_reset: "counter-reset" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/counter-set>
counter_set: "counter-set" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/cue>
cue in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/cue-after>
cue_after: "cue-after" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/cue-before>
cue_before: "cue-before" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/cursor>
cursor in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/direction>
direction in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/display>
display in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/display-inside>
display_inside: "display-inside" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/display-outside>
display_outside: "display-outside" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/display-extras>
display_extras: "display-extras" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/display-box>
display_box: "display-box" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/dominant-baseline>
dominant_baseline: "dominant-baseline" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/elevation>
elevation in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/empty-cells>
empty_cells: "empty-cells" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/enable-background>
enable_background: "enable-background" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/fill>
fill in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/fill-opacity>
fill_opacity: "fill-opacity" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/fill-rule>
fill_rule: "fill-rule" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/filter>
filter in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/float>
float in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/float-defer-column>
float_defer_column: "float-defer-column" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/float-defer-page>
float_defer_page: "float-defer-page" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/float-offset>
float_offset: "float-offset" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/float-wrap>
float_wrap: "float-wrap" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flow-into>
flow_into: "flow-into" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flow-from>
flow_from: "flow-from" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex>
flex in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis>
flex_basis: "flex-basis" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow>
flex_grow: "flex-grow" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-shrink>
flex_shrink: "flex-shrink" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-flow>
flex_flow: "flex-flow" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction>
flex_direction: "flex-direction" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap>
flex_wrap: "flex-wrap" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flood-color>
flood_color: "flood-color" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/flood-opacity>
flood_opacity: "flood-opacity" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font>
font in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-family>
font_family: "font-family" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-size>
font_size: "font-size" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-stretch>
font_stretch: "font-stretch" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-style>
font_style: "font-style" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight>
font_weight: "font-weight" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-feature-settings>
font_feature_settings: "font-feature-settings" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-kerning>
font_kerning: "font-kerning" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-language-override>
font_language_override: "font-language-override" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-size-adjust>
font_size_adjust: "font-size-adjust" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-synthesis>
font_synthesis: "font-synthesis" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant>
font_variant: "font-variant" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-alternates>
font_variant_alternates: "font-variant-alternates" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-caps>
font_variant_caps: "font-variant-caps" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-east-asian>
font_variant_east_asian: "font-variant-east-asian" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-ligatures>
font_variant_ligatures: "font-variant-ligatures" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-numeric>
font_variant_numeric: "font-variant-numeric" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-position>
font_variant_position: "font-variant-position" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/footnote-policy>
footnote_policy: "footnote-policy" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/glyph-orientation-horizontal>
glyph_orientation_horizontal: "glyph-orientation-horizontal" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/glyph-orientation-vertical>
glyph_orientation_vertical: "glyph-orientation-vertical" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid>
grid in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-flow>
grid_auto_flow: "grid-auto-flow" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-columns>
grid_auto_columns: "grid-auto-columns" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-rows>
grid_auto_rows: "grid-auto-rows" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template>
grid_template: "grid-template" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-areas>
grid_template_areas: "grid-template-areas" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns>
grid_template_columns: "grid-template-columns" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-rows>
grid_template_rows: "grid-template-rows" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-area>
grid_area: "grid-area" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column>
grid_column: "grid-column" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-start>
grid_column_start: "grid-column-start" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-end>
grid_column_end: "grid-column-end" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row>
grid_row: "grid-row" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-start>
grid_row_start: "grid-row-start" in "style";
/// <https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-end>
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/input_data.rs | packages/html/src/input_data.rs | //! Data structures representing user input, such as modifier keys and mouse buttons
use enumset::{EnumSet, EnumSetType};
/// A re-export of keyboard_types
pub use keyboard_types;
use keyboard_types::Location;
/// A mouse button type (such as Primary/Secondary)
// note: EnumSetType also derives Copy and Clone for some reason
#[allow(clippy::unused_unit)]
#[derive(EnumSetType, Debug, Default)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub enum MouseButton {
#[default]
/// Primary button (typically the left button)
Primary,
/// Secondary button (typically the right button)
Secondary,
/// Auxiliary button (typically the middle button)
Auxiliary,
/// Fourth button (typically the "Browser Back" button)
Fourth,
/// Fifth button (typically the "Browser Forward" button)
Fifth,
/// A button with an unknown code
Unknown,
}
impl MouseButton {
/// Constructs a MouseButton for the specified button code
///
/// E.g. 0 => Primary; 1 => Auxiliary
///
/// Unknown codes get mapped to MouseButton::Unknown.
pub fn from_web_code(code: i16) -> Self {
match code {
0 => MouseButton::Primary,
// not a typo; auxiliary and secondary are swapped unlike in the `buttons` field.
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
1 => MouseButton::Auxiliary,
2 => MouseButton::Secondary,
3 => MouseButton::Fourth,
4 => MouseButton::Fifth,
_ => MouseButton::Unknown,
}
}
/// Converts MouseButton into the corresponding button code
///
/// MouseButton::Unknown will get mapped to -1
pub fn into_web_code(self) -> i16 {
match self {
MouseButton::Primary => 0,
// not a typo; auxiliary and secondary are swapped unlike in the `buttons` field.
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
MouseButton::Auxiliary => 1,
MouseButton::Secondary => 2,
MouseButton::Fourth => 3,
MouseButton::Fifth => 4,
MouseButton::Unknown => -1,
}
}
}
/// A set of mouse buttons
pub type MouseButtonSet = EnumSet<MouseButton>;
pub fn decode_mouse_button_set(code: u16) -> MouseButtonSet {
let mut set = EnumSet::empty();
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
#[allow(deprecated)]
{
if code & 0b1 != 0 {
set |= MouseButton::Primary;
}
if code & 0b10 != 0 {
set |= MouseButton::Secondary;
}
if code & 0b100 != 0 {
set |= MouseButton::Auxiliary;
}
if code & 0b1000 != 0 {
set |= MouseButton::Fourth;
}
if code & 0b10000 != 0 {
set |= MouseButton::Fifth;
}
if code & (!0b11111) != 0 {
set |= MouseButton::Unknown;
}
}
set
}
pub fn encode_mouse_button_set(set: MouseButtonSet) -> u16 {
let mut code = 0;
// https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
{
if set.contains(MouseButton::Primary) {
code |= 0b1;
}
if set.contains(MouseButton::Secondary) {
code |= 0b10;
}
if set.contains(MouseButton::Auxiliary) {
code |= 0b100;
}
if set.contains(MouseButton::Fourth) {
code |= 0b1000;
}
if set.contains(MouseButton::Fifth) {
code |= 0b10000;
}
if set.contains(MouseButton::Unknown) {
code |= 0b100000;
}
}
code
}
pub fn decode_key_location(code: usize) -> Location {
match code {
0 => Location::Standard,
1 => Location::Left,
2 => Location::Right,
3 => Location::Numpad,
// keyboard_types doesn't yet support mobile/joystick locations
4 | 5 => Location::Standard,
// unknown location; Standard seems better than panicking
_ => Location::Standard,
}
}
pub fn encode_key_location(location: Location) -> usize {
match location {
Location::Standard => 0,
Location::Left => 1,
Location::Right => 2,
Location::Numpad => 3,
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/lib.rs | packages/html/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")]
#![allow(non_snake_case)]
//! # Dioxus Namespace for HTML
//!
//! This crate provides a set of compile-time correct HTML elements that can be used with the Rsx and Html macros.
//! This system allows users to easily build new tags, new types, and customize the output of the Rsx and Html macros.
//!
//! An added benefit of this approach is the ability to lend comprehensive documentation on how to use these elements inside
//! of the Rsx and Html macros. Each element comes with a substantial amount of documentation on how to best use it, hopefully
//! making the development cycle quick.
//!
//! All elements are used as zero-sized unit structs with trait impls.
//!
//! Currently, we don't validate for structures, but do validate attributes.
pub mod elements;
#[cfg(feature = "hot-reload-context")]
pub use elements::HtmlCtx;
#[cfg(feature = "html-to-rsx")]
pub use elements::{map_html_attribute_to_rsx, map_html_element_to_rsx};
pub mod events;
pub(crate) mod file_data;
pub use file_data::*;
mod attribute_groups;
mod data_transfer;
pub mod geometry;
pub mod input_data;
pub mod point_interaction;
mod render_template;
pub use data_transfer::*;
pub use bytes;
#[cfg(feature = "serialize")]
mod transit;
#[cfg(feature = "serialize")]
pub use transit::*;
pub use attribute_groups::*;
pub use elements::*;
pub use events::*;
pub use render_template::*;
pub use crate::attribute_groups::{GlobalAttributesExtension, SvgAttributesExtension};
pub use crate::elements::extensions::*;
pub use crate::point_interaction::*;
pub use keyboard_types::{self, Code, Key, Location, Modifiers};
pub mod traits {
pub use crate::events::*;
pub use crate::point_interaction::*;
}
pub mod extensions {
pub use crate::attribute_groups::{GlobalAttributesExtension, SvgAttributesExtension};
pub use crate::elements::extensions::*;
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/transit.rs | packages/html/src/transit.rs | use std::{any::Any, rc::Rc};
use crate::events::*;
use dioxus_core::ElementId;
use serde::{Deserialize, Serialize};
#[cfg(feature = "serialize")]
#[derive(Serialize, Debug, PartialEq)]
pub struct HtmlEvent {
pub element: ElementId,
pub name: String,
pub bubbles: bool,
pub data: EventData,
}
#[cfg(feature = "serialize")]
impl<'de> Deserialize<'de> for HtmlEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize, Debug, Clone)]
struct Inner {
element: ElementId,
name: String,
bubbles: bool,
data: serde_json::Value,
}
let Inner {
element,
name,
bubbles,
data,
} = Inner::deserialize(deserializer)?;
// in debug mode let's try and be helpful as to why the deserialization failed
let data = deserialize_raw(&name, &data).map_err(|e| {
serde::de::Error::custom(format!(
"Failed to deserialize event data for event {}: {}\n'{:#?}'",
name, e, data,
))
})?;
Ok(HtmlEvent {
data,
element,
bubbles,
name,
})
}
}
#[cfg(feature = "serialize")]
fn deserialize_raw(name: &str, data: &serde_json::Value) -> Result<EventData, serde_json::Error> {
use EventData::*;
// a little macro-esque thing to make the code below more readable
#[inline]
fn de<'de, F>(f: &'de serde_json::Value) -> Result<F, serde_json::Error>
where
F: Deserialize<'de>,
{
F::deserialize(f)
}
let data = match name {
// Cancel
"cancel" => Cancel(de(data)?),
// Mouse
"click" | "contextmenu" | "dblclick" | "doubleclick" | "mousedown" | "mouseenter"
| "mouseleave" | "mousemove" | "mouseout" | "mouseover" | "mouseup" => Mouse(de(data)?),
// Clipboard
"copy" | "cut" | "paste" => Clipboard(de(data)?),
// Composition
"compositionend" | "compositionstart" | "compositionupdate" => Composition(de(data)?),
// Keyboard
"keydown" | "keypress" | "keyup" => Keyboard(de(data)?),
// Focus
"blur" | "focus" | "focusin" | "focusout" => Focus(de(data)?),
// Form
"change" | "input" | "invalid" | "reset" | "submit" => Form(de(data)?),
// Drag
"drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart"
| "drop" => Drag(de(data)?),
// Pointer
"pointerlockchange" | "pointerlockerror" | "pointerdown" | "pointermove" | "pointerup"
| "pointerover" | "pointerout" | "pointerenter" | "pointerleave" | "gotpointercapture"
| "lostpointercapture" | "auxclick" => Pointer(de(data)?),
// Selection
"selectstart" | "selectionchange" | "select" => Selection(de(data)?),
// Touch
"touchcancel" | "touchend" | "touchmove" | "touchstart" => Touch(de(data)?),
// Resize
"resize" => Resize(de(data)?),
// Scroll
"scroll" | "scrollend" => Scroll(de(data)?),
// Visible
"visible" => Visible(de(data)?),
// Wheel
"wheel" => Wheel(de(data)?),
// Media
"abort" | "canplay" | "canplaythrough" | "durationchange" | "emptied" | "encrypted"
| "ended" | "interruptbegin" | "interruptend" | "loadeddata" | "loadedmetadata"
| "loadstart" | "pause" | "play" | "playing" | "progress" | "ratechange" | "seeked"
| "seeking" | "stalled" | "suspend" | "timeupdate" | "volumechange" | "waiting"
| "loadend" | "timeout" => Media(de(data)?),
// Animation
"animationstart" | "animationend" | "animationiteration" => Animation(de(data)?),
// Transition
"transitionend" => Transition(de(data)?),
// Toggle
"toggle" => Toggle(de(data)?),
"load" | "error" => Image(de(data)?),
// Mounted
"mounted" => Mounted,
// OtherData => "abort" | "afterprint" | "beforeprint" | "beforeunload" | "hashchange" | "languagechange" | "message" | "offline" | "online" | "pagehide" | "pageshow" | "popstate" | "rejectionhandled" | "storage" | "unhandledrejection" | "unload" | "userproximity" | "vrdisplayactivate" | "vrdisplayblur" | "vrdisplayconnect" | "vrdisplaydeactivate" | "vrdisplaydisconnect" | "vrdisplayfocus" | "vrdisplaypointerrestricted" | "vrdisplaypointerunrestricted" | "vrdisplaypresentchange";
other => {
return Err(serde::de::Error::custom(format!(
"Unknown event type: {other}"
)))
}
};
Ok(data)
}
#[cfg(feature = "serialize")]
impl HtmlEvent {
pub fn bubbles(&self) -> bool {
self.bubbles
}
}
#[derive(Deserialize, Serialize, Debug, PartialEq)]
#[serde(untagged)]
#[non_exhaustive]
pub enum EventData {
Cancel(SerializedCancelData),
Mouse(SerializedMouseData),
Clipboard(SerializedClipboardData),
Composition(SerializedCompositionData),
Keyboard(SerializedKeyboardData),
Focus(SerializedFocusData),
Form(SerializedFormData),
Drag(SerializedDragData),
Pointer(SerializedPointerData),
Selection(SerializedSelectionData),
Touch(SerializedTouchData),
Resize(SerializedResizeData),
Scroll(SerializedScrollData),
Visible(SerializedVisibleData),
Wheel(SerializedWheelData),
Media(SerializedMediaData),
Animation(SerializedAnimationData),
Transition(SerializedTransitionData),
Toggle(SerializedToggleData),
Image(SerializedImageData),
Mounted,
}
impl EventData {
pub fn into_any(self) -> Rc<dyn Any> {
match self {
EventData::Cancel(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Mouse(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Clipboard(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Composition(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Keyboard(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Focus(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Form(data) => Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>,
EventData::Drag(data) => Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>,
EventData::Pointer(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Selection(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Touch(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Resize(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Scroll(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Visible(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Wheel(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Media(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Animation(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Transition(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Toggle(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Image(data) => {
Rc::new(PlatformEventData::new(Box::new(data))) as Rc<dyn Any>
}
EventData::Mounted => {
Rc::new(PlatformEventData::new(Box::new(MountedData::new(())))) as Rc<dyn Any>
}
}
}
}
#[test]
fn test_back_and_forth() {
let data = HtmlEvent {
element: ElementId(0),
data: EventData::Mouse(SerializedMouseData::default()),
name: "click".to_string(),
bubbles: true,
};
println!("{}", serde_json::to_string_pretty(&data).unwrap());
let o = r#"
{
"element": 0,
"name": "click",
"bubbles": true,
"data": {
"alt_key": false,
"button": 0,
"buttons": 0,
"client_x": 0,
"client_y": 0,
"ctrl_key": false,
"meta_key": false,
"offset_x": 0,
"offset_y": 0,
"page_x": 0,
"page_y": 0,
"screen_x": 0,
"screen_y": 0,
"shift_key": false
}
}
"#;
let p: HtmlEvent = serde_json::from_str(o).unwrap();
assert_eq!(data, p);
}
/// A trait for converting from a serialized event to a concrete event type.
pub struct SerializedHtmlEventConverter;
impl HtmlEventConverter for SerializedHtmlEventConverter {
fn convert_animation_data(&self, event: &PlatformEventData) -> AnimationData {
event
.downcast::<SerializedAnimationData>()
.cloned()
.unwrap()
.into()
}
fn convert_cancel_data(&self, event: &PlatformEventData) -> CancelData {
event
.downcast::<SerializedCancelData>()
.cloned()
.unwrap()
.into()
}
fn convert_clipboard_data(&self, event: &PlatformEventData) -> ClipboardData {
event
.downcast::<SerializedClipboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_composition_data(&self, event: &PlatformEventData) -> CompositionData {
event
.downcast::<SerializedCompositionData>()
.cloned()
.unwrap()
.into()
}
fn convert_drag_data(&self, event: &PlatformEventData) -> DragData {
event
.downcast::<SerializedDragData>()
.cloned()
.unwrap()
.into()
}
fn convert_focus_data(&self, event: &PlatformEventData) -> FocusData {
event
.downcast::<SerializedFocusData>()
.cloned()
.unwrap()
.into()
}
fn convert_form_data(&self, event: &PlatformEventData) -> FormData {
event
.downcast::<SerializedFormData>()
.cloned()
.unwrap()
.into()
}
fn convert_image_data(&self, event: &PlatformEventData) -> ImageData {
event
.downcast::<SerializedImageData>()
.cloned()
.unwrap()
.into()
}
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData {
event
.downcast::<SerializedKeyboardData>()
.cloned()
.unwrap()
.into()
}
fn convert_media_data(&self, event: &PlatformEventData) -> MediaData {
event
.downcast::<SerializedMediaData>()
.cloned()
.unwrap()
.into()
}
fn convert_mounted_data(&self, _: &PlatformEventData) -> MountedData {
MountedData::from(())
}
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData {
event
.downcast::<SerializedMouseData>()
.cloned()
.unwrap()
.into()
}
fn convert_pointer_data(&self, event: &PlatformEventData) -> PointerData {
event
.downcast::<SerializedPointerData>()
.cloned()
.unwrap()
.into()
}
fn convert_resize_data(&self, event: &PlatformEventData) -> ResizeData {
event
.downcast::<SerializedResizeData>()
.cloned()
.unwrap()
.into()
}
fn convert_scroll_data(&self, event: &PlatformEventData) -> ScrollData {
event
.downcast::<SerializedScrollData>()
.cloned()
.unwrap()
.into()
}
fn convert_selection_data(&self, event: &PlatformEventData) -> SelectionData {
event
.downcast::<SerializedSelectionData>()
.cloned()
.unwrap()
.into()
}
fn convert_toggle_data(&self, event: &PlatformEventData) -> ToggleData {
event
.downcast::<SerializedToggleData>()
.cloned()
.unwrap()
.into()
}
fn convert_touch_data(&self, event: &PlatformEventData) -> TouchData {
event
.downcast::<SerializedTouchData>()
.cloned()
.unwrap()
.into()
}
fn convert_transition_data(&self, event: &PlatformEventData) -> TransitionData {
event
.downcast::<SerializedTransitionData>()
.cloned()
.unwrap()
.into()
}
fn convert_visible_data(&self, event: &PlatformEventData) -> VisibleData {
event
.downcast::<SerializedVisibleData>()
.cloned()
.unwrap()
.into()
}
fn convert_wheel_data(&self, event: &PlatformEventData) -> WheelData {
event
.downcast::<SerializedWheelData>()
.cloned()
.unwrap()
.into()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/point_interaction.rs | packages/html/src/point_interaction.rs | use keyboard_types::Modifiers;
use crate::{
geometry::{ClientPoint, Coordinates, ElementPoint, PagePoint, ScreenPoint},
input_data::{MouseButton, MouseButtonSet},
};
/// A interaction that contains data about the location of the event.
pub trait InteractionLocation {
/// Gets the coordinates of the event relative to the browser viewport.
fn client_coordinates(&self) -> ClientPoint;
/// Gets the coordinates of the event relative to the screen.
fn screen_coordinates(&self) -> ScreenPoint;
/// Gets the coordinates of the event relative to the page.
fn page_coordinates(&self) -> PagePoint;
}
/// A interaction that contains data about the location of the event.
pub trait InteractionElementOffset: InteractionLocation {
/// Gets the coordinates of the event.
fn coordinates(&self) -> Coordinates {
Coordinates::new(
self.screen_coordinates(),
self.client_coordinates(),
self.element_coordinates(),
self.page_coordinates(),
)
}
/// Gets the coordinates of the event relative to the target element.
fn element_coordinates(&self) -> ElementPoint;
}
/// A interaction that contains data about the pointer button(s) that triggered the event.
pub trait PointerInteraction: InteractionElementOffset + ModifiersInteraction {
/// Gets the button that triggered the event.
fn trigger_button(&self) -> Option<MouseButton>;
/// Gets the buttons that are currently held down.
fn held_buttons(&self) -> MouseButtonSet;
}
/// A interaction that contains data about the current state of the keyboard modifiers.
pub trait ModifiersInteraction {
/// Gets the modifiers of the pointer event.
fn modifiers(&self) -> Modifiers;
}
#[cfg(feature = "serialize")]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone, Default)]
pub struct SerializedPointInteraction {
pub alt_key: bool,
/// The button number that was pressed (if applicable) when the mouse event was fired.
pub button: i16,
/// Indicates which buttons are pressed on the mouse (or other input device) when a mouse event is triggered.
///
/// Each button that can be pressed is represented by a given number (see below). If more than one button is pressed, the button values are added together to produce a new number. For example, if the secondary (2) and auxiliary (4) buttons are pressed simultaneously, the value is 6 (i.e., 2 + 4).
///
/// - 1: Primary button (usually the left button)
/// - 2: Secondary button (usually the right button)
/// - 4: Auxiliary button (usually the mouse wheel button or middle button)
/// - 8: 4th button (typically the "Browser Back" button)
/// - 16 : 5th button (typically the "Browser Forward" button)
pub buttons: u16,
/// The horizontal coordinate within the application's viewport at which the event occurred (as opposed to the coordinate within the page).
///
/// For example, clicking on the left edge of the viewport will always result in a mouse event with a clientX value of 0, regardless of whether the page is scrolled horizontally.
pub client_x: f64,
/// The vertical coordinate within the application's viewport at which the event occurred (as opposed to the coordinate within the page).
///
/// For example, clicking on the top edge of the viewport will always result in a mouse event with a clientY value of 0, regardless of whether the page is scrolled vertically.
pub client_y: f64,
/// True if the control key was down when the mouse event was fired.
pub ctrl_key: bool,
/// True if the meta key was down when the mouse event was fired.
pub meta_key: bool,
/// The offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
pub offset_x: f64,
/// The offset in the Y coordinate of the mouse pointer between that event and the padding edge of the target node.
pub offset_y: f64,
/// The X (horizontal) coordinate (in pixels) of the mouse, relative to the left edge of the entire document. This includes any portion of the document not currently visible.
///
/// Being based on the edge of the document as it is, this property takes into account any horizontal scrolling of the page. For example, if the page is scrolled such that 200 pixels of the left side of the document are scrolled out of view, and the mouse is clicked 100 pixels inward from the left edge of the view, the value returned by pageX will be 300.
pub page_x: f64,
/// The Y (vertical) coordinate in pixels of the event relative to the whole document.
///
/// See `page_x`.
pub page_y: f64,
/// The X coordinate of the mouse pointer in global (screen) coordinates.
pub screen_x: f64,
/// The Y coordinate of the mouse pointer in global (screen) coordinates.
pub screen_y: f64,
/// True if the shift key was down when the mouse event was fired.
pub shift_key: bool,
}
#[cfg(feature = "serialize")]
impl SerializedPointInteraction {
pub fn new(
trigger_button: Option<MouseButton>,
held_buttons: MouseButtonSet,
coordinates: Coordinates,
modifiers: Modifiers,
) -> Self {
let alt_key = modifiers.contains(Modifiers::ALT);
let ctrl_key = modifiers.contains(Modifiers::CONTROL);
let meta_key = modifiers.contains(Modifiers::META);
let shift_key = modifiers.contains(Modifiers::SHIFT);
let [client_x, client_y]: [f64; 2] = coordinates.client().cast().into();
let [offset_x, offset_y]: [f64; 2] = coordinates.element().cast().into();
let [page_x, page_y]: [f64; 2] = coordinates.page().cast().into();
let [screen_x, screen_y]: [f64; 2] = coordinates.screen().cast().into();
Self {
button: trigger_button
.map_or(MouseButton::default(), |b| b)
.into_web_code(),
buttons: crate::input_data::encode_mouse_button_set(held_buttons),
meta_key,
ctrl_key,
shift_key,
alt_key,
client_x,
client_y,
screen_x,
screen_y,
offset_x,
offset_y,
page_x,
page_y,
}
}
}
#[cfg(feature = "serialize")]
impl<E: PointerInteraction> From<&E> for SerializedPointInteraction {
fn from(data: &E) -> Self {
let trigger_button = data.trigger_button();
let held_buttons = data.held_buttons();
let coordinates = data.coordinates();
let modifiers = data.modifiers();
Self::new(trigger_button, held_buttons, coordinates, modifiers)
}
}
#[cfg(feature = "serialize")]
impl PointerInteraction for SerializedPointInteraction {
fn held_buttons(&self) -> MouseButtonSet {
crate::input_data::decode_mouse_button_set(self.buttons)
}
fn trigger_button(&self) -> Option<MouseButton> {
Some(MouseButton::from_web_code(self.button))
}
}
#[cfg(feature = "serialize")]
impl ModifiersInteraction for SerializedPointInteraction {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.alt_key {
modifiers.insert(Modifiers::ALT);
}
if self.ctrl_key {
modifiers.insert(Modifiers::CONTROL);
}
if self.meta_key {
modifiers.insert(Modifiers::META);
}
if self.shift_key {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
#[cfg(feature = "serialize")]
impl InteractionLocation for SerializedPointInteraction {
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.client_x, self.client_y)
}
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(self.screen_x, self.screen_y)
}
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(self.page_x, self.page_y)
}
}
#[cfg(feature = "serialize")]
impl InteractionElementOffset for SerializedPointInteraction {
fn element_coordinates(&self) -> ElementPoint {
ElementPoint::new(self.offset_x, self.offset_y)
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/geometry.rs | packages/html/src/geometry.rs | //! Geometry primitives for representing e.g. mouse events
/// A re-export of euclid, which we use for geometry primitives
pub use euclid;
use euclid::*;
/// Coordinate space relative to the screen
pub struct ScreenSpace;
/// A point in ScreenSpace
pub type ScreenPoint = Point2D<f64, ScreenSpace>;
/// Coordinate space relative to the viewport
pub struct ClientSpace;
/// A point in ClientSpace
pub type ClientPoint = Point2D<f64, ClientSpace>;
/// Coordinate space relative to an element
pub struct ElementSpace;
/// A point in ElementSpace
pub type ElementPoint = Point2D<f64, ElementSpace>;
/// Coordinate space relative to the page
pub struct PageSpace;
/// A point in PageSpace
pub type PagePoint = Point2D<f64, PageSpace>;
/// A pixel unit: one unit corresponds to 1 pixel
pub struct Pixels;
/// A size expressed in Pixels
pub type PixelsSize = Size2D<f64, Pixels>;
/// A rectangle expressed in Pixels
pub type PixelsRect = Rect<f64, Pixels>;
/// A 2D vector expressed in Pixels
pub type PixelsVector2D = Vector2D<f64, Pixels>;
/// A 3D vector expressed in Pixels
pub type PixelsVector3D = Vector3D<f64, Pixels>;
/// A unit in terms of Lines
///
/// One unit is relative to the size of one line
pub struct Lines;
/// A vector expressed in Lines
pub type LinesVector = Vector3D<f64, Lines>;
/// A unit in terms of Screens:
///
/// One unit is relative to the size of a page
pub struct Pages;
/// A vector expressed in Pages
pub type PagesVector = Vector3D<f64, Pages>;
/// A vector representing the amount the mouse wheel was moved
///
/// This may be expressed in Pixels, Lines or Pages
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub enum WheelDelta {
/// Movement in Pixels
Pixels(PixelsVector3D),
/// Movement in Lines
Lines(LinesVector),
/// Movement in Pages
Pages(PagesVector),
}
impl WheelDelta {
/// Construct from the attributes of the web wheel event
pub fn from_web_attributes(delta_mode: u32, delta_x: f64, delta_y: f64, delta_z: f64) -> Self {
match delta_mode {
0 => WheelDelta::Pixels(PixelsVector3D::new(delta_x, delta_y, delta_z)),
1 => WheelDelta::Lines(LinesVector::new(delta_x, delta_y, delta_z)),
2 => WheelDelta::Pages(PagesVector::new(delta_x, delta_y, delta_z)),
_ => panic!("Invalid delta mode, {:?}", delta_mode),
}
}
/// Convenience function for constructing a WheelDelta with pixel units
pub fn pixels(x: f64, y: f64, z: f64) -> Self {
WheelDelta::Pixels(PixelsVector3D::new(x, y, z))
}
/// Convenience function for constructing a WheelDelta with line units
pub fn lines(x: f64, y: f64, z: f64) -> Self {
WheelDelta::Lines(LinesVector::new(x, y, z))
}
/// Convenience function for constructing a WheelDelta with page units
pub fn pages(x: f64, y: f64, z: f64) -> Self {
WheelDelta::Pages(PagesVector::new(x, y, z))
}
/// Returns true iff there is no wheel movement
///
/// i.e. the x, y and z delta is zero (disregards units)
pub fn is_zero(&self) -> bool {
self.strip_units() == Vector3D::new(0., 0., 0.)
}
/// A Vector3D proportional to the amount scrolled
///
/// Note that this disregards the 3 possible units: this could be expressed in terms of pixels, lines, or pages.
///
/// In most cases, to properly handle scrolling, you should handle all 3 possible enum variants instead of stripping units. Otherwise, if you assume that the units will always be pixels, the user may experience some unexpectedly slow scrolling if their mouse/OS sends values expressed in lines or pages.
pub fn strip_units(&self) -> Vector3D<f64, UnknownUnit> {
match self {
WheelDelta::Pixels(v) => v.cast_unit(),
WheelDelta::Lines(v) => v.cast_unit(),
WheelDelta::Pages(v) => v.cast_unit(),
}
}
}
/// Coordinates of a point in the app's interface
#[derive(Debug, PartialEq)]
pub struct Coordinates {
screen: ScreenPoint,
client: ClientPoint,
element: ElementPoint,
page: PagePoint,
}
impl Coordinates {
/// Construct new coordinates with the specified screen-, client-, element- and page-relative points
pub fn new(
screen: ScreenPoint,
client: ClientPoint,
element: ElementPoint,
page: PagePoint,
) -> Self {
Self {
screen,
client,
element,
page,
}
}
/// Coordinates relative to the entire screen. This takes into account the window's offset.
pub fn screen(&self) -> ScreenPoint {
self.screen
}
/// Coordinates relative to the application's viewport (as opposed to the coordinate within the page).
///
/// For example, clicking in the top left corner of the viewport will always result in a mouse event with client coordinates (0., 0.), regardless of whether the page is scrolled horizontally.
pub fn client(&self) -> ClientPoint {
self.client
}
/// Coordinates relative to the padding edge of the target element
///
/// For example, clicking in the top left corner of an element will result in element coordinates (0., 0.)
pub fn element(&self) -> ElementPoint {
self.element
}
/// Coordinates relative to the entire document. This includes any portion of the document not currently visible.
///
/// For example, if the page is scrolled 200 pixels to the right and 300 pixels down, clicking in the top left corner of the viewport would result in page coordinates (200., 300.)
pub fn page(&self) -> PagePoint {
self.page
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/render_template.rs | packages/html/src/render_template.rs | use dioxus_core::{Template, TemplateAttribute, TemplateNode};
use std::fmt::Write;
/// Render a template to an HTML string
///
/// Useful for sending over the wire. Can be used to with innerHtml to create templates with little work
pub fn render_template_to_html(template: &Template) -> String {
let mut out = String::new();
for root in template.roots {
render_template_node(root, &mut out).unwrap();
}
out
}
fn render_template_node(node: &TemplateNode, out: &mut String) -> std::fmt::Result {
match node {
TemplateNode::Element {
tag,
attrs,
children,
..
} => {
write!(out, "<{tag}")?;
for attr in *attrs {
if let TemplateAttribute::Static { name, value, .. } = attr {
write!(out, "{name}=\"{value}\"")?;
}
}
for child in *children {
render_template_node(child, out)?;
}
write!(out, "</{tag}>")?;
}
TemplateNode::Text { text: t } => write!(out, "{t}")?,
TemplateNode::Dynamic { id: _ } => write!(out, "<!--placeholder-->")?,
};
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/file_data.rs | packages/html/src/file_data.rs | use bytes::Bytes;
use futures_util::Stream;
use std::{path::PathBuf, pin::Pin, prelude::rust_2024::Future};
#[derive(Clone)]
pub struct FileData {
inner: std::sync::Arc<dyn NativeFileData>,
}
impl FileData {
pub fn new(inner: impl NativeFileData + 'static) -> Self {
Self {
inner: std::sync::Arc::new(inner),
}
}
pub fn content_type(&self) -> Option<String> {
self.inner.content_type()
}
pub fn name(&self) -> String {
self.inner.name()
}
pub fn size(&self) -> u64 {
self.inner.size()
}
pub fn last_modified(&self) -> u64 {
self.inner.last_modified()
}
pub async fn read_bytes(&self) -> Result<Bytes, dioxus_core::CapturedError> {
self.inner.read_bytes().await
}
pub async fn read_string(&self) -> Result<String, dioxus_core::CapturedError> {
self.inner.read_string().await
}
pub fn byte_stream(
&self,
) -> Pin<Box<dyn Stream<Item = Result<Bytes, dioxus_core::CapturedError>> + Send + 'static>>
{
self.inner.byte_stream()
}
pub fn inner(&self) -> &dyn std::any::Any {
self.inner.inner()
}
pub fn path(&self) -> PathBuf {
self.inner.path()
}
}
impl PartialEq for FileData {
fn eq(&self, other: &Self) -> bool {
self.name() == other.name()
&& self.size() == other.size()
&& self.last_modified() == other.last_modified()
&& self.path() == other.path()
}
}
pub trait NativeFileData: Send + Sync {
fn name(&self) -> String;
fn size(&self) -> u64;
fn last_modified(&self) -> u64;
fn path(&self) -> PathBuf;
fn content_type(&self) -> Option<String>;
fn read_bytes(
&self,
) -> Pin<Box<dyn Future<Output = Result<Bytes, dioxus_core::CapturedError>> + 'static>>;
fn byte_stream(
&self,
) -> Pin<
Box<
dyn futures_util::Stream<Item = Result<Bytes, dioxus_core::CapturedError>>
+ 'static
+ Send,
>,
>;
fn read_string(
&self,
) -> Pin<Box<dyn Future<Output = Result<String, dioxus_core::CapturedError>> + 'static>>;
fn inner(&self) -> &dyn std::any::Any;
}
impl std::fmt::Debug for FileData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FileData")
.field("name", &self.inner.name())
.field("size", &self.inner.size())
.field("last_modified", &self.inner.last_modified())
.finish()
}
}
pub trait HasFileData: std::any::Any {
fn files(&self) -> Vec<FileData>;
}
#[cfg(feature = "serialize")]
pub use serialize::*;
#[cfg(feature = "serialize")]
mod serialize {
use super::*;
/// A serializable representation of file data
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedFileData {
pub path: PathBuf,
pub size: u64,
pub last_modified: u64,
pub content_type: Option<String>,
pub contents: Option<bytes::Bytes>,
}
impl SerializedFileData {
/// Create a new empty serialized file data object
pub fn empty() -> Self {
Self {
path: PathBuf::new(),
size: 0,
last_modified: 0,
content_type: None,
contents: None,
}
}
}
impl NativeFileData for SerializedFileData {
fn name(&self) -> String {
self.path()
.file_name()
.unwrap()
.to_string_lossy()
.into_owned()
}
fn size(&self) -> u64 {
self.size
}
fn last_modified(&self) -> u64 {
self.last_modified
}
fn read_bytes(
&self,
) -> Pin<Box<dyn Future<Output = Result<Bytes, dioxus_core::CapturedError>> + 'static>>
{
let contents = self.contents.clone();
let path = self.path.clone();
Box::pin(async move {
if let Some(contents) = contents {
return Ok(contents);
}
#[cfg(not(target_arch = "wasm32"))]
if path.exists() {
return Ok(std::fs::read(path).map(Bytes::from)?);
}
Err(dioxus_core::CapturedError::msg(
"File contents not available",
))
})
}
fn read_string(
&self,
) -> Pin<Box<dyn Future<Output = Result<String, dioxus_core::CapturedError>> + 'static>>
{
let contents = self.contents.clone();
let path = self.path.clone();
Box::pin(async move {
if let Some(contents) = contents {
return Ok(String::from_utf8(contents.to_vec())?);
}
#[cfg(not(target_arch = "wasm32"))]
if path.exists() {
return Ok(std::fs::read_to_string(path)?);
}
Err(dioxus_core::CapturedError::msg(
"File contents not available",
))
})
}
fn byte_stream(
&self,
) -> Pin<
Box<
dyn futures_util::Stream<Item = Result<Bytes, dioxus_core::CapturedError>>
+ 'static
+ Send,
>,
> {
let contents = self.contents.clone();
let path = self.path.clone();
Box::pin(futures_util::stream::once(async move {
if let Some(contents) = contents {
return Ok(contents);
}
#[cfg(not(target_arch = "wasm32"))]
if path.exists() {
return Ok(std::fs::read(path).map(Bytes::from)?);
}
Err(dioxus_core::CapturedError::msg(
"File contents not available",
))
}))
}
fn inner(&self) -> &dyn std::any::Any {
self
}
fn path(&self) -> PathBuf {
self.path.clone()
}
fn content_type(&self) -> Option<String> {
self.content_type.clone()
}
}
impl<'de> serde::Deserialize<'de> for FileData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let sfd = SerializedFileData::deserialize(deserializer)?;
Ok(FileData::new(sfd))
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/elements.rs | packages/html/src/elements.rs | #![allow(non_upper_case_globals)]
use dioxus_core::HasAttributes;
use dioxus_core::IntoAttributeValue;
#[cfg(feature = "hot-reload-context")]
use dioxus_core_types::HotReloadingContext;
use dioxus_html_internal_macro::impl_extension_attributes;
#[cfg(feature = "hot-reload-context")]
use crate::{map_global_attributes, map_svg_attributes};
pub type AttributeDescription = (&'static str, Option<&'static str>, bool);
macro_rules! impl_attribute {
(
$element:ident {
$(#[$attr_method:meta])*
$fil:ident: $vil:ident (DEFAULT),
}
) => {
$(#[$attr_method])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
#[doc = concat!("let ", stringify!($fil), " = \"value\";")]
///
/// rsx! {
/// // Attributes need to be under the element they modify
#[doc = concat!(" ", stringify!($element), " {")]
/// // Attributes are followed by a colon and then the value of the attribute
#[doc = concat!(" ", stringify!($fil), ": \"value\"")]
/// }
#[doc = concat!(" ", stringify!($element), " {")]
/// // Or you can use the shorthand syntax if you have a variable in scope that has the same name as the attribute
#[doc = concat!(" ", stringify!($fil), ",")]
/// }
/// };
/// ```
pub const $fil: AttributeDescription = (stringify!($fil), None, false);
};
(
$element:ident {
$(#[$attr_method:meta])*
$fil:ident: $vil:ident ($name:literal),
}
) => {
$(#[$attr_method])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
#[doc = concat!("let ", stringify!($fil), " = \"value\";")]
///
/// rsx! {
/// // Attributes need to be under the element they modify
#[doc = concat!(" ", stringify!($element), " {")]
/// // Attributes are followed by a colon and then the value of the attribute
#[doc = concat!(" ", stringify!($fil), ": \"value\"")]
/// }
#[doc = concat!(" ", stringify!($element), " {")]
/// // Or you can use the shorthand syntax if you have a variable in scope that has the same name as the attribute
#[doc = concat!(" ", stringify!($fil), ",")]
/// }
/// };
/// ```
pub const $fil: AttributeDescription = ($name, None, false);
};
(
$element:ident {
$(#[$attr_method:meta])*
$fil:ident: $vil:ident (volatile),
}
) => {
$(#[$attr_method])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
#[doc = concat!("let ", stringify!($fil), " = \"value\";")]
///
/// rsx! {
/// // Attributes need to be under the element they modify
#[doc = concat!(" ", stringify!($element), " {")]
/// // Attributes are followed by a colon and then the value of the attribute
#[doc = concat!(" ", stringify!($fil), ": \"value\"")]
/// }
#[doc = concat!(" ", stringify!($element), " {")]
/// // Or you can use the shorthand syntax if you have a variable in scope that has the same name as the attribute
#[doc = concat!(" ", stringify!($fil), ",")]
/// }
/// };
/// ```
pub const $fil: AttributeDescription = (stringify!($fil), None, true);
};
(
$element:ident {
$(#[$attr_method:meta])*
$fil:ident: $vil:ident (in $ns:literal),
}
) => {
$(#[$attr_method])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
#[doc = concat!("let ", stringify!($fil), " = \"value\";")]
///
/// rsx! {
/// // Attributes need to be under the element they modify
#[doc = concat!(" ", stringify!($element), " {")]
/// // Attributes are followed by a colon and then the value of the attribute
#[doc = concat!(" ", stringify!($fil), ": \"value\"")]
/// }
#[doc = concat!(" ", stringify!($element), " {")]
/// // Or you can use the shorthand syntax if you have a variable in scope that has the same name as the attribute
#[doc = concat!(" ", stringify!($fil), ",")]
/// }
/// };
/// ```
pub const $fil: AttributeDescription = (stringify!($fil), Some($ns), false)
};
(
$element:ident {
$(#[$attr_method:meta])*
$fil:ident: $vil:ident (in $ns:literal : volatile),
}
) => {
$(#[$attr_method])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
#[doc = concat!("let ", stringify!($fil), " = \"value\";")]
///
/// rsx! {
/// // Attributes need to be under the element they modify
#[doc = concat!(" ", stringify!($element), " {")]
/// // Attributes are followed by a colon and then the value of the attribute
#[doc = concat!(" ", stringify!($fil), ": \"value\"")]
/// }
#[doc = concat!(" ", stringify!($element), " {")]
/// // Or you can use the shorthand syntax if you have a variable in scope that has the same name as the attribute
#[doc = concat!(" ", stringify!($fil), ",")]
/// }
/// };
/// ```
pub const $fil: AttributeDescription = (stringify!($fil), Some($ns), true)
};
}
#[cfg(feature = "hot-reload-context")]
macro_rules! impl_attribute_match {
(
$attr:ident $fil:ident: $vil:ident (DEFAULT),
) => {
if $attr == stringify!($fil) {
return Some((stringify!($fil), None));
}
};
(
$attr:ident $fil:ident: $vil:ident (volatile),
) => {
if $attr == stringify!($fil) {
return Some((stringify!($fil), None));
}
};
(
$attr:ident $fil:ident: $vil:ident ($name:literal),
) => {
if $attr == stringify!($fil) {
return Some(($name, None));
}
};
(
$attr:ident $fil:ident: $vil:ident (in $ns:literal),
) => {
if $attr == stringify!($fil) {
return Some((stringify!($fil), Some($ns)));
}
};
}
#[cfg(feature = "html-to-rsx")]
macro_rules! impl_html_to_rsx_attribute_match {
(
$attr:ident $fil:ident $name:literal
) => {
if $attr == $name {
return Some(stringify!($fil));
}
};
(
$attr:ident $fil:ident $_:tt
) => {
if $attr == stringify!($fil) {
return Some(stringify!($fil));
}
};
}
macro_rules! impl_element {
(
$(#[$attr:meta])*
$name:ident None {
$(
$(#[$attr_method:meta])*
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
#[allow(non_camel_case_types)]
$(#[$attr])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # let attributes = vec![];
/// # fn ChildComponent() -> Element { unimplemented!() }
/// # let raw_expression: Element = rsx! {};
/// rsx! {
/// // Elements are followed by braces that surround any attributes and children for that element
#[doc = concat!(" ", stringify!($name), " {")]
/// // Add any attributes first
/// class: "my-class",
/// "custom-attribute-name": "value",
/// // Then add any attributes you are spreading into this element
/// ..attributes,
/// // Then add any children elements, components, text nodes, or raw expressions
/// div {}
/// ChildComponent {}
/// "child text"
/// {raw_expression}
/// }
/// };
/// ```
pub mod $name {
#[allow(unused)]
use super::*;
pub use crate::attribute_groups::global_attributes::*;
pub const TAG_NAME: &'static str = stringify!($name);
pub const NAME_SPACE: Option<&'static str> = None;
$(
impl_attribute!(
$name {
$(#[$attr_method])*
$fil: $vil ($extra),
}
);
)*
}
};
(
$(#[$attr:meta])*
$name:ident $namespace:literal {
$(
$(#[$attr_method:meta])*
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
$(#[$attr])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # let attributes = vec![];
/// # fn ChildComponent() -> Element { unimplemented!() }
/// # let raw_expression: Element = rsx! {};
/// rsx! {
/// // Elements are followed by braces that surround any attributes and children for that element
#[doc = concat!(" ", stringify!($name), " {")]
/// // Add any attributes first
/// color: "red",
/// "custom-attribute-name": "value",
/// // Then add any attributes you are spreading into this element
/// ..attributes,
/// // Then add any children elements, components, text nodes, or raw expressions
/// circle { cx: "10", cy: "10", r: "2", fill: "red" }
/// ChildComponent {}
/// "child text"
/// {raw_expression}
/// }
/// };
/// ```
pub mod $name {
#[allow(unused)]
use super::*;
pub use crate::attribute_groups::svg_attributes::*;
pub const TAG_NAME: &'static str = stringify!($name);
pub const NAME_SPACE: Option<&'static str> = Some($namespace);
$(
impl_attribute!(
$name {
$(#[$attr_method])*
$fil: $vil ($extra),
}
);
)*
}
};
(
$(#[$attr:meta])*
$element:ident [$name:literal, $namespace:tt] {
$(
$(#[$attr_method:meta])*
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
#[allow(non_camel_case_types)]
$(#[$attr])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # let attributes = vec![];
/// # fn ChildComponent() -> Element { unimplemented!() }
/// # let raw_expression: Element = rsx! {};
/// rsx! {
/// // Elements are followed by braces that surround any attributes and children for that element
#[doc = concat!(" ", stringify!($element), " {")]
/// // Add any attributes first
/// color: "red",
/// "custom-attribute-name": "value",
/// // Then add any attributes you are spreading into this element
/// ..attributes,
/// // Then add any children elements, components, text nodes, or raw expressions
/// circle { cx: "10", cy: "10", r: "2", fill: "red" }
/// ChildComponent {}
/// "child text"
/// {raw_expression}
/// }
/// };
/// ```
pub mod $element {
#[allow(unused)]
use super::*;
pub use crate::attribute_groups::svg_attributes::*;
pub const TAG_NAME: &'static str = $name;
pub const NAME_SPACE: Option<&'static str> = Some($namespace);
$(
impl_attribute!(
$element {
$(#[$attr_method])*
$fil: $vil ($extra),
}
);
)*
}
}
}
#[cfg(feature = "hot-reload-context")]
macro_rules! impl_element_match {
(
$el:ident $name:ident None {
$(
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
if $el == stringify!($name) {
return Some((stringify!($name), None));
}
};
(
$el:ident $name:ident $namespace:literal {
$(
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
if $el == stringify!($name) {
return Some((stringify!($name), Some($namespace)));
}
};
(
$el:ident $name:ident [$_:literal, $namespace:tt] {
$(
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
if $el == stringify!($name) {
return Some((stringify!($name), Some($namespace)));
}
};
}
#[cfg(feature = "hot-reload-context")]
macro_rules! impl_element_match_attributes {
(
$el:ident $attr:ident $name:ident None {
$(
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
if $el == stringify!($name) {
$(
impl_attribute_match!(
$attr $fil: $vil ($extra),
);
)*
return impl_map_global_attributes!($el $attr $name None);
}
};
(
$el:ident $attr:ident $name:ident $namespace:tt {
$(
$fil:ident: $vil:ident $extra:tt,
)*
}
) => {
if $el == stringify!($name) {
$(
impl_attribute_match!(
$attr $fil: $vil ($extra),
);
)*
return impl_map_global_attributes!($el $attr $name $namespace);
}
}
}
#[cfg(feature = "hot-reload-context")]
macro_rules! impl_map_global_attributes {
(
$el:ident $attr:ident $element:ident None
) => {
map_global_attributes($attr)
};
(
$el:ident $attr:ident $element:ident $namespace:literal
) => {
if $namespace == "http://www.w3.org/2000/svg" {
map_svg_attributes($attr)
} else {
map_global_attributes($attr)
}
};
(
$el:ident $attr:ident $element:ident [$name:literal, $namespace:tt]
) => {
if $namespace == "http://www.w3.org/2000/svg" {
map_svg_attributes($attr)
} else {
map_global_attributes($attr)
}
};
}
macro_rules! builder_constructors {
(
$(
$(#[$attr:meta])*
$name:ident $namespace:tt {
$(
$(#[$attr_method:meta])*
$fil:ident: $vil:ident $extra:tt,
)*
};
)*
) => {
#[cfg(feature = "hot-reload-context")]
pub struct HtmlCtx;
#[cfg(feature = "hot-reload-context")]
impl HotReloadingContext for HtmlCtx {
fn map_attribute(element: &str, attribute: &str) -> Option<(&'static str, Option<&'static str>)> {
$(
impl_element_match_attributes!(
element attribute $name $namespace {
$(
$fil: $vil $extra,
)*
}
);
)*
None
}
fn map_element(element: &str) -> Option<(&'static str, Option<&'static str>)> {
$(
impl_element_match!(
element $name $namespace {
$(
$fil: $vil $extra,
)*
}
);
)*
None
}
}
#[cfg(feature = "html-to-rsx")]
pub fn map_html_attribute_to_rsx(html: &str) -> Option<&'static str> {
$(
$(
impl_html_to_rsx_attribute_match!(
html $fil $extra
);
)*
)*
if let Some(name) = crate::map_html_global_attributes_to_rsx(html) {
return Some(name);
}
if let Some(name) = crate::map_html_svg_attributes_to_rsx(html) {
return Some(name);
}
None
}
#[cfg(feature = "html-to-rsx")]
pub fn map_html_element_to_rsx(html: &str) -> Option<&'static str> {
$(
if html == stringify!($name) {
return Some(stringify!($name));
}
)*
None
}
$(
impl_element!(
$(#[$attr])*
$name $namespace {
$(
$(#[$attr_method])*
$fil: $vil $extra,
)*
}
);
)*
/// This module contains helpers for rust analyzer autocompletion
#[doc(hidden)]
pub mod completions {
/// This helper tells rust analyzer that it should autocomplete the element name with braces.
#[allow(non_camel_case_types)]
pub enum CompleteWithBraces {
$(
$(#[$attr])*
///
/// ## Usage in rsx
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # let attributes = vec![];
/// # fn ChildComponent() -> Element { unimplemented!() }
/// # let raw_expression: Element = rsx! {};
/// rsx! {
/// // Elements are followed by braces that surround any attributes and children for that element
#[doc = concat!(" ", stringify!($name), " {")]
/// // Add any attributes first
/// class: "my-class",
/// "custom-attribute-name": "value",
/// // Then add any attributes you are spreading into this element
/// ..attributes,
/// // Then add any children elements, components, text nodes, or raw expressions
/// div {}
/// ChildComponent {}
/// "child text"
/// {raw_expression}
/// }
/// };
/// ```
$name {}
),*
}
}
pub(crate) mod extensions {
use super::*;
$(
impl_extension_attributes![$name { $($fil,)* }];
)*
}
};
}
// Organized in the same order as
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element
//
// Does not include obsolete elements.
//
// This namespace represents a collection of modern HTML-5 compatible elements.
//
// This list does not include obsolete, deprecated, experimental, or poorly supported elements.
builder_constructors! {
// Document metadata
/// Build a
/// [`<base>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base)
/// element.
///
base None {
href: Uri DEFAULT,
target: Target DEFAULT,
};
/// Build a
/// [`<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)
/// element.
head None {};
/// Build a
/// [`<link>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link)
/// element.
link None {
// as: Mime,
crossorigin: CrossOrigin DEFAULT,
href: Uri DEFAULT,
hreflang: LanguageTag DEFAULT,
media: String DEFAULT, // FIXME media query
rel: LinkType DEFAULT,
sizes: String DEFAULT, // FIXME
title: String DEFAULT, // FIXME
r#type: Mime "type",
integrity: String DEFAULT,
disabled: Bool DEFAULT,
referrerpolicy: ReferrerPolicy DEFAULT,
fetchpriority: FetchPriority DEFAULT,
blocking: Blocking DEFAULT,
r#as: As "as",
};
/// Build a
/// [`<meta>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta)
/// element.
meta None {
charset: String DEFAULT, // FIXME IANA standard names
content: String DEFAULT,
http_equiv: String "http-equiv",
name: Metadata DEFAULT,
property: Metadata DEFAULT,
};
/// Build a
/// [`<style>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style)
/// element.
style None {
r#type: Mime "type",
media: String DEFAULT, // FIXME media query
nonce: Nonce DEFAULT,
title: String DEFAULT, // FIXME
};
/// Build a
/// [`<title>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title)
/// element.
title None { };
// Sectioning root
/// Build a
/// [`<body>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)
/// element.
body None {};
// ------------------
// Content sectioning
// ------------------
/// Build a
/// [`<address>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/address)
/// element.
address None {};
/// Build a
/// [`<article>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article)
/// element.
article None {};
/// Build a
/// [`<aside>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside)
/// element.
aside None {};
/// Build a
/// [`<footer>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer)
/// element.
footer None {};
/// Build a
/// [`<header>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header)
/// element.
header None {};
/// Build a
/// [`<hgroup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hgroup)
/// element.
hgroup None {};
/// Build a
/// [`<h1>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h1)
/// element.
///
/// # About
/// - The HTML `<h1>` element is found within the `<body>` tag.
/// - Headings can range from `<h1>` to `<h6>`.
/// - The most important heading is `<h1>` and the least important heading is `<h6>`.
/// - The `<h1>` heading is the first heading in the document.
/// - The `<h1>` heading is usually a large bolded font.
h1 None {};
/// Build a
/// [`<h2>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h2)
/// element.
///
/// # About
/// - The HTML `<h2>` element is found within the `<body>` tag.
/// - Headings can range from `<h1>` to `<h6>`.
/// - The most important heading is `<h1>` and the least important heading is `<h6>`.
/// - The `<h2>` heading is the second heading in the document.
/// - The `<h2>` heading is usually a large bolded font.
h2 None {};
/// Build a
/// [`<h3>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h3)
/// element.
///
/// # About
/// - The HTML `<h1>` element is found within the `<body>` tag.
/// - Headings can range from `<h1>` to `<h6>`.
/// - The most important heading is `<h1>` and the least important heading is `<h6>`.
/// - The `<h1>` heading is the first heading in the document.
/// - The `<h1>` heading is usually a large bolded font.
h3 None {};
/// Build a
/// [`<h4>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h4)
/// element.
h4 None {};
/// Build a
/// [`<h5>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h5)
/// element.
h5 None {};
/// Build a
/// [`<h6>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h6)
/// element.
h6 None {};
/// Build a
/// [`<main>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main)
/// element.
main None {};
/// Build a
/// [`<nav>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav)
/// element.
nav None {};
/// Build a
/// [`<section>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section)
/// element.
section None {};
// Text content
/// Build a
/// [`<blockquote>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote)
/// element.
blockquote None {
cite: Uri DEFAULT,
};
/// Build a
/// [`<dd>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd)
/// element.
dd None {};
/// Build a
/// [`<div>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div)
/// element.
///
/// Part of the HTML namespace. Only works in HTML-compatible renderers
///
/// ## Definition and Usage
/// - The `<div>` tag defines a division or a section in an HTML document.
/// - The `<div>` tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript.
/// - The `<div>` tag is easily styled by using the class or id attribute.
/// - Any sort of content can be put inside the `<div>` tag!
///
/// Note: By default, browsers always place a line break before and after the `<div>` element.
///
/// ## References:
/// - <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div>
/// - <https://www.w3schools.com/tags/tag_div.asp>
div None {};
/// Build a
/// [`<dl>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl)
/// element.
dl None {};
/// Build a
/// [`<dt>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt)
/// element.
dt None {};
/// Build a
/// [`<figcaption>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption)
/// element.
figcaption None {};
/// Build a
/// [`<figure>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure)
/// element.
figure None {};
/// Build a
/// [`<hr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr)
/// element.
hr None {};
/// Build a
/// [`<li>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li)
/// element.
li None {
value: isize DEFAULT,
};
/// Build a
/// [`<ol>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol)
/// element.
ol None {
reversed: Bool DEFAULT,
start: isize DEFAULT,
r#type: OrderedListType "type",
};
/// Build a
/// [`<p>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p)
/// element.
p None {};
/// Build a
/// [`<pre>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre)
/// element.
pre None {};
/// Build a
/// [`<ul>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul)
/// element.
ul None {};
// Inline text semantics
/// Build a
/// [`<a>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)
/// element.
a None {
download: String DEFAULT,
href: Uri DEFAULT,
hreflang: LanguageTag DEFAULT,
target: Target DEFAULT,
r#type: Mime "type",
// ping: SpacedList<Uri>,
// rel: SpacedList<LinkType>,
ping: SpacedList DEFAULT,
rel: SpacedList DEFAULT,
};
/// Build a
/// [`<abbr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/abbr)
/// element.
abbr None {};
/// Build a
/// [`<b>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b)
/// element.
b None {};
/// Build a
/// [`<bdi>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/bdi)
/// element.
bdi None {};
/// Build a
/// [`<bdo>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/bdo)
/// element.
bdo None {};
/// Build a
/// [`<br>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br)
/// element.
br None {};
/// Build a
/// [`<cite>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite)
/// element.
cite None {};
/// Build a
/// [`<code>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code)
/// element.
code None {
language: String DEFAULT,
};
/// Build a
/// [`<data>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data)
/// element.
data None {
value: String DEFAULT,
};
/// Build a
/// [`<dfn>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dfn)
/// element.
dfn None {};
/// Build a
/// [`<em>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em)
/// element.
em None {};
/// Build a
/// [`<i>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i)
/// element.
i None {};
/// Build a
/// [`<kbd>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd)
/// element.
kbd None {};
/// Build a
/// [`<mark>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark)
/// element.
mark None {};
/// Build a
/// [`<menu>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu)
/// element.
menu None {};
/// Build a
/// [`<q>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q)
/// element.
q None {
cite: Uri DEFAULT,
};
/// Build a
/// [`<rp>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rp)
/// element.
rp None {};
/// Build a
/// [`<rt>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rt)
/// element.
rt None {};
/// Build a
/// [`<ruby>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ruby)
/// element.
ruby None {};
/// Build a
/// [`<s>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s)
/// element.
s None {};
/// Build a
/// [`<samp>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/samp)
/// element.
samp None {};
/// Build a
/// [`<small>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small)
/// element.
small None {};
/// Build a
/// [`<span>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span)
/// element.
span None {};
/// Build a
/// [`<strong>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong)
/// element.
strong None {};
/// Build a
/// [`<sub>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub)
/// element.
sub None {};
/// Build a
/// [`<sup>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup)
/// element.
sup None {};
/// Build a
/// [`<time>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time)
/// element.
time None {
datetime: Datetime DEFAULT,
};
/// Build a
/// [`<u>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u)
/// element.
u None {};
/// Build a
/// [`<var>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/var)
/// element.
var None {};
/// Build a
/// [`<wbr>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr)
/// element.
wbr None {};
// Image and multimedia
/// Build a
/// [`<area>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area)
/// element.
area None {
alt: String DEFAULT,
coords: String DEFAULT, // TODO could perhaps be validated
download: Bool DEFAULT,
href: Uri DEFAULT,
hreflang: LanguageTag DEFAULT,
shape: AreaShape DEFAULT,
target: Target DEFAULT,
// ping: SpacedList<Uri>,
// rel: SpacedSet<LinkType>,
};
/// Build a
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | true |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/data_transfer.rs | packages/html/src/data_transfer.rs | pub struct DataTransfer {
inner: Box<dyn NativeDataTransfer>,
}
impl DataTransfer {
pub fn new(inner: impl NativeDataTransfer + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
#[cfg(feature = "serialize")]
pub fn store(&self, item: impl Serialize) -> Result<(), String> {
let serialized = serde_json::to_string(&item).map_err(|e| e.to_string())?;
self.set_data("application/json", &serialized)
}
#[cfg(feature = "serialize")]
pub fn retrieve<T: for<'de> serde::Deserialize<'de>>(&self) -> Result<Option<T>, String> {
if let Some(data) = self.get_data("application/json") {
let deserialized = serde_json::from_str(&data).map_err(|e| e.to_string())?;
Ok(Some(deserialized))
} else {
Ok(None)
}
}
pub fn get_data(&self, format: &str) -> Option<String> {
self.inner.get_data(format)
}
pub fn get_as_text(&self) -> Option<String> {
self.get_data("text/plain")
}
pub fn set_data(&self, format: &str, data: &str) -> Result<(), String> {
self.inner.set_data(format, data)
}
pub fn clear_data(&self, format: Option<&str>) -> Result<(), String> {
self.inner.clear_data(format)
}
pub fn effect_allowed(&self) -> String {
self.inner.effect_allowed()
}
pub fn set_effect_allowed(&self, effect: &str) {
self.inner.set_effect_allowed(effect)
}
pub fn drop_effect(&self) -> String {
self.inner.drop_effect()
}
pub fn set_drop_effect(&self, effect: &str) {
self.inner.set_drop_effect(effect)
}
pub fn files(&self) -> Vec<crate::file_data::FileData> {
self.inner.files()
}
}
pub trait NativeDataTransfer: Send + Sync {
fn get_data(&self, format: &str) -> Option<String>;
fn set_data(&self, format: &str, data: &str) -> Result<(), String>;
fn clear_data(&self, format: Option<&str>) -> Result<(), String>;
fn effect_allowed(&self) -> String;
fn set_effect_allowed(&self, effect: &str);
fn drop_effect(&self) -> String;
fn set_drop_effect(&self, effect: &str);
fn files(&self) -> Vec<crate::file_data::FileData>;
}
pub trait HasDataTransferData {
fn data_transfer(&self) -> DataTransfer;
}
#[cfg(feature = "serialize")]
pub use ser::*;
#[cfg(feature = "serialize")]
use serde::Serialize;
#[cfg(feature = "serialize")]
mod ser {
use crate::DragData;
use super::*;
use serde::{Deserialize, Serialize};
/// A serialized version of DataTransfer
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedDataTransfer {
pub items: Vec<SerializedDataTransferItem>,
pub files: Vec<crate::file_data::SerializedFileData>,
pub effect_allowed: String,
pub drop_effect: String,
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedDataTransferItem {
pub kind: String,
pub type_: String,
pub data: String,
}
impl NativeDataTransfer for SerializedDataTransfer {
fn get_data(&self, format: &str) -> Option<String> {
self.items
.iter()
.find(|item| item.type_ == format)
.map(|item| item.data.clone())
}
fn set_data(&self, _format: &str, _data: &str) -> Result<(), String> {
// todo!()
// Err("Cannot set data on serialized DataTransfer".into())
Ok(())
}
fn clear_data(&self, _format: Option<&str>) -> Result<(), String> {
// todo!()
// Err("Cannot clear data on serialized DataTransfer".into())
Ok(())
}
fn effect_allowed(&self) -> String {
self.effect_allowed.clone()
}
fn set_effect_allowed(&self, _effect: &str) {
// No-op
}
fn drop_effect(&self) -> String {
self.drop_effect.clone()
}
fn set_drop_effect(&self, _effect: &str) {
// No-op
}
fn files(&self) -> Vec<crate::file_data::FileData> {
self.files
.iter()
.map(|f| crate::file_data::FileData::new(f.clone()))
.collect()
}
}
impl From<&DragData> for SerializedDataTransfer {
fn from(_drag: &DragData) -> Self {
// todo!()
Self {
items: vec![],
files: vec![],
effect_allowed: "all".into(),
drop_effect: "none".into(),
}
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/focus.rs | packages/html/src/events/focus.rs | use dioxus_core::Event;
pub type FocusEvent = Event<FocusData>;
pub struct FocusData {
inner: Box<dyn HasFocusData>,
}
impl<E: HasFocusData> From<E> for FocusData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for FocusData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FocusData").finish()
}
}
impl PartialEq for FocusData {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl FocusData {
/// Create a new FocusData
pub fn new(inner: impl HasFocusData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event data to a specific type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of FocusData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone, Default)]
pub struct SerializedFocusData {}
#[cfg(feature = "serialize")]
impl From<&FocusData> for SerializedFocusData {
fn from(_: &FocusData) -> Self {
Self {}
}
}
#[cfg(feature = "serialize")]
impl HasFocusData for SerializedFocusData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for FocusData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedFocusData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for FocusData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedFocusData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasFocusData: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! [
FocusData;
/// onfocus
onfocus
// onfocusout
onfocusout
// onfocusin
onfocusin
/// onblur
onblur
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/scroll.rs | packages/html/src/events/scroll.rs | use dioxus_core::Event;
pub type ScrollEvent = Event<ScrollData>;
pub struct ScrollData {
inner: Box<dyn HasScrollData>,
}
impl<E: HasScrollData> From<E> for ScrollData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl ScrollData {
/// Create a new ScrollData
pub fn new(inner: impl HasScrollData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
pub fn scroll_top(&self) -> f64 {
self.inner.scroll_top()
}
pub fn scroll_left(&self) -> f64 {
self.inner.scroll_left()
}
pub fn scroll_width(&self) -> i32 {
self.inner.scroll_width()
}
pub fn scroll_height(&self) -> i32 {
self.inner.scroll_height()
}
pub fn client_width(&self) -> i32 {
self.inner.client_width()
}
pub fn client_height(&self) -> i32 {
self.inner.client_height()
}
}
impl std::fmt::Debug for ScrollData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScrollData")
.field("scroll_top", &self.scroll_top())
.field("scroll_left", &self.scroll_left())
.field("scroll_width", &self.scroll_width())
.field("scroll_height", &self.scroll_height())
.field("client_width", &self.client_width())
.field("client_height", &self.client_height())
.finish()
}
}
impl PartialEq for ScrollData {
fn eq(&self, other: &Self) -> bool {
self.scroll_top() == other.scroll_top()
&& self.scroll_left() == other.scroll_left()
&& self.scroll_width() == other.scroll_width()
&& self.scroll_height() == other.scroll_height()
&& self.client_width() == other.client_width()
&& self.client_height() == other.client_height()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of ScrollData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedScrollData {
pub scroll_top: f64,
pub scroll_left: f64,
pub scroll_width: i32,
pub scroll_height: i32,
pub client_width: i32,
pub client_height: i32,
}
#[cfg(feature = "serialize")]
impl From<&ScrollData> for SerializedScrollData {
fn from(data: &ScrollData) -> Self {
Self {
scroll_top: data.inner.scroll_top(),
scroll_left: data.inner.scroll_left(),
scroll_width: data.inner.scroll_width(),
scroll_height: data.inner.scroll_height(),
client_width: data.inner.client_width(),
client_height: data.inner.client_height(),
}
}
}
#[cfg(feature = "serialize")]
impl HasScrollData for SerializedScrollData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn scroll_top(&self) -> f64 {
self.scroll_top
}
fn scroll_left(&self) -> f64 {
self.scroll_left
}
fn scroll_width(&self) -> i32 {
self.scroll_width
}
fn scroll_height(&self) -> i32 {
self.scroll_height
}
fn client_width(&self) -> i32 {
self.client_width
}
fn client_height(&self) -> i32 {
self.client_height
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for ScrollData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedScrollData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for ScrollData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedScrollData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasScrollData: std::any::Any {
/// Return self as Any
fn as_any(&self) -> &dyn std::any::Any;
/// Get the vertical scroll position
fn scroll_top(&self) -> f64;
/// Get the horizontal scroll position
fn scroll_left(&self) -> f64;
/// Get the total scrollable width
fn scroll_width(&self) -> i32;
/// Get the total scrollable height
fn scroll_height(&self) -> i32;
/// Get the viewport width
fn client_width(&self) -> i32;
/// Get the viewport height
fn client_height(&self) -> i32;
}
impl_event! {
ScrollData;
/// onscroll
onscroll
/// onscrollend
onscrollend
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/image.rs | packages/html/src/events/image.rs | use dioxus_core::Event;
pub type ImageEvent = Event<ImageData>;
pub struct ImageData {
inner: Box<dyn HasImageData>,
}
impl<E: HasImageData> From<E> for ImageData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for ImageData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ImageData")
.field("load_error", &self.load_error())
.finish()
}
}
impl PartialEq for ImageData {
fn eq(&self, other: &Self) -> bool {
self.load_error() == other.load_error()
}
}
impl ImageData {
/// Create a new ImageData
pub fn new(e: impl HasImageData) -> Self {
Self { inner: Box::new(e) }
}
/// If the renderer encountered an error while loading the image
pub fn load_error(&self) -> bool {
self.inner.load_error()
}
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of ImageData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedImageData {
#[cfg_attr(feature = "serialize", serde(default))]
load_error: bool,
}
#[cfg(feature = "serialize")]
impl From<&ImageData> for SerializedImageData {
fn from(data: &ImageData) -> Self {
Self {
load_error: data.load_error(),
}
}
}
#[cfg(feature = "serialize")]
impl HasImageData for SerializedImageData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn load_error(&self) -> bool {
self.load_error
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for ImageData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedImageData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for ImageData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedImageData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
/// A trait for any object that has the data for an image event
pub trait HasImageData: std::any::Any {
/// If the renderer encountered an error while loading the image
fn load_error(&self) -> bool;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! [
ImageData;
/// onerror
onerror
/// onload
onload
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/mouse.rs | packages/html/src/events/mouse.rs | use crate::geometry::{ClientPoint, Coordinates, ElementPoint, PagePoint, ScreenPoint};
use crate::input_data::{MouseButton, MouseButtonSet};
use crate::*;
use dioxus_core::Event;
use keyboard_types::Modifiers;
pub type MouseEvent = Event<MouseData>;
/// A synthetic event that wraps a web-style [`MouseEvent`](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent)
/// Data associated with a mouse event
pub struct MouseData {
inner: Box<dyn HasMouseData>,
}
impl<E: HasMouseData + 'static> From<E> for MouseData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for MouseData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MouseData")
.field("coordinates", &self.coordinates())
.field("modifiers", &self.modifiers())
.field("held_buttons", &self.held_buttons())
.field("trigger_button", &self.trigger_button())
.finish()
}
}
impl<E: HasMouseData> PartialEq<E> for MouseData {
fn eq(&self, other: &E) -> bool {
self.coordinates() == other.coordinates()
&& self.modifiers() == other.modifiers()
&& self.held_buttons() == other.held_buttons()
&& self.trigger_button() == other.trigger_button()
}
}
/// A trait for any object that has the data for a mouse event
pub trait HasMouseData: PointerInteraction {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! {
MouseData;
/// Execute a callback when a button is clicked.
///
/// ## Description
///
/// An element receives a click event when a pointing device button (such as a mouse's primary mouse button)
/// is both pressed and released while the pointer is located inside the element.
///
/// - Bubbles: Yes
/// - Cancelable: Yes
/// - Interface(InteData): [`MouseEvent`]
///
/// If the button is pressed on one element and the pointer is moved outside the element before the button
/// is released, the event is fired on the most specific ancestor element that contained both elements.
/// `click` fires after both the `mousedown` and `mouseup` events have fired, in that order.
///
/// ## Example
/// ```rust, ignore
/// rsx!( button { onclick: move |_| tracing::info!("Clicked!"), "click me" } )
/// ```
///
/// ## Reference
/// - <https://www.w3schools.com/tags/ev_onclick.asp>
/// - <https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event>
onclick
/// oncontextmenu
oncontextmenu
#[deprecated(since = "0.5.0", note = "use ondoubleclick instead")]
ondblclick
ondoubleclick: "ondblclick"
/// onmousedown
onmousedown
/// onmouseenter
onmouseenter
/// onmouseleave
onmouseleave
/// onmousemove
onmousemove
/// onmouseout
onmouseout
/// onmouseover
///
/// Triggered when the users's mouse hovers over an element.
onmouseover
/// onmouseup
onmouseup
}
impl MouseData {
/// Create a new instance of MouseData
pub fn new(inner: impl HasMouseData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl InteractionLocation for MouseData {
fn client_coordinates(&self) -> ClientPoint {
self.inner.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.inner.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.inner.screen_coordinates()
}
}
impl InteractionElementOffset for MouseData {
fn element_coordinates(&self) -> ElementPoint {
self.inner.element_coordinates()
}
fn coordinates(&self) -> Coordinates {
self.inner.coordinates()
}
}
impl ModifiersInteraction for MouseData {
/// The set of modifier keys which were pressed when the event occurred
fn modifiers(&self) -> Modifiers {
self.inner.modifiers()
}
}
impl PointerInteraction for MouseData {
/// The set of mouse buttons which were held when the event occurred.
fn held_buttons(&self) -> MouseButtonSet {
self.inner.held_buttons()
}
/// The mouse button that triggered the event
///
// todo the following is kind of bad; should we just return None when the trigger_button is unreliable (and frankly irrelevant)? i guess we would need the event_type here
/// This is only guaranteed to indicate which button was pressed during events caused by pressing or releasing a button. As such, it is not reliable for events such as mouseenter, mouseleave, mouseover, mouseout, or mousemove. For example, a value of MouseButton::Primary may also indicate that no button was pressed.
fn trigger_button(&self) -> Option<MouseButton> {
self.inner.trigger_button()
}
}
impl PartialEq for MouseData {
fn eq(&self, other: &Self) -> bool {
self.coordinates() == other.coordinates()
&& self.modifiers() == other.modifiers()
&& self.held_buttons() == other.held_buttons()
&& self.trigger_button() == other.trigger_button()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of [`MouseData`]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone, Default)]
pub struct SerializedMouseData {
/// Common data for all pointer/mouse events
#[serde(flatten)]
point_data: crate::point_interaction::SerializedPointInteraction,
}
#[cfg(feature = "serialize")]
impl SerializedMouseData {
/// Create a new instance of SerializedMouseData
pub fn new(
trigger_button: Option<MouseButton>,
held_buttons: MouseButtonSet,
coordinates: Coordinates,
modifiers: Modifiers,
) -> Self {
Self {
point_data: crate::point_interaction::SerializedPointInteraction::new(
trigger_button,
held_buttons,
coordinates,
modifiers,
),
}
}
}
#[cfg(feature = "serialize")]
impl From<&MouseData> for SerializedMouseData {
fn from(e: &MouseData) -> Self {
Self {
point_data: crate::point_interaction::SerializedPointInteraction::from(e),
}
}
}
#[cfg(feature = "serialize")]
impl HasMouseData for SerializedMouseData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl InteractionLocation for SerializedMouseData {
fn client_coordinates(&self) -> ClientPoint {
self.point_data.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.point_data.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.point_data.screen_coordinates()
}
}
#[cfg(feature = "serialize")]
impl InteractionElementOffset for SerializedMouseData {
fn element_coordinates(&self) -> ElementPoint {
self.point_data.element_coordinates()
}
}
#[cfg(feature = "serialize")]
impl ModifiersInteraction for SerializedMouseData {
fn modifiers(&self) -> Modifiers {
self.point_data.modifiers()
}
}
#[cfg(feature = "serialize")]
impl PointerInteraction for SerializedMouseData {
fn held_buttons(&self) -> MouseButtonSet {
self.point_data.held_buttons()
}
fn trigger_button(&self) -> Option<MouseButton> {
self.point_data.trigger_button()
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for MouseData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedMouseData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for MouseData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedMouseData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/clipboard.rs | packages/html/src/events/clipboard.rs | use dioxus_core::Event;
pub type ClipboardEvent = Event<ClipboardData>;
pub struct ClipboardData {
inner: Box<dyn HasClipboardData>,
}
impl<E: HasClipboardData> From<E> for ClipboardData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for ClipboardData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClipboardData").finish()
}
}
impl PartialEq for ClipboardData {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl ClipboardData {
/// Create a new ClipboardData
pub fn new(inner: impl HasClipboardData) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_ref().as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of ClipboardData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedClipboardData {}
#[cfg(feature = "serialize")]
impl From<&ClipboardData> for SerializedClipboardData {
fn from(_: &ClipboardData) -> Self {
Self {}
}
}
#[cfg(feature = "serialize")]
impl HasClipboardData for SerializedClipboardData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for ClipboardData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedClipboardData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for ClipboardData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedClipboardData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasClipboardData: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event![
ClipboardData;
/// oncopy
oncopy
/// oncut
oncut
/// onpaste
onpaste
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/composition.rs | packages/html/src/events/composition.rs | use dioxus_core::Event;
pub type CompositionEvent = Event<CompositionData>;
pub struct CompositionData {
inner: Box<dyn HasCompositionData>,
}
impl std::fmt::Debug for CompositionData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CompositionData")
.field("data", &self.data())
.finish()
}
}
impl<E: HasCompositionData> From<E> for CompositionData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl PartialEq for CompositionData {
fn eq(&self, other: &Self) -> bool {
self.data() == other.data()
}
}
impl CompositionData {
/// Create a new CompositionData
pub fn new(inner: impl HasCompositionData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// The characters generated by the input method that raised the event
pub fn data(&self) -> String {
self.inner.data()
}
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of CompositionData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedCompositionData {
data: String,
}
#[cfg(feature = "serialize")]
impl From<&CompositionData> for SerializedCompositionData {
fn from(data: &CompositionData) -> Self {
Self { data: data.data() }
}
}
#[cfg(feature = "serialize")]
impl HasCompositionData for SerializedCompositionData {
fn data(&self) -> String {
self.data.clone()
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for CompositionData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedCompositionData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for CompositionData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedCompositionData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
/// A trait for any object that has the data for a composition event
pub trait HasCompositionData: std::any::Any {
/// The characters generated by the input method that raised the event
fn data(&self) -> String;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! [
CompositionData;
/// oncompositionstart
oncompositionstart
/// oncompositionend
oncompositionend
/// oncompositionupdate
oncompositionupdate
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/animation.rs | packages/html/src/events/animation.rs | use dioxus_core::Event;
pub type AnimationEvent = Event<AnimationData>;
pub struct AnimationData {
inner: Box<dyn HasAnimationData>,
}
impl AnimationData {
/// Create a new AnimationData
pub fn new(inner: impl HasAnimationData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// The name of the animation
pub fn animation_name(&self) -> String {
self.inner.animation_name()
}
/// The name of the pseudo-element the animation runs on
pub fn pseudo_element(&self) -> String {
self.inner.pseudo_element()
}
/// The amount of time the animation has been running
pub fn elapsed_time(&self) -> f32 {
self.inner.elapsed_time()
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_ref().as_any().downcast_ref::<T>()
}
}
impl<E: HasAnimationData> From<E> for AnimationData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for AnimationData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnimationData")
.field("animation_name", &self.animation_name())
.field("pseudo_element", &self.pseudo_element())
.field("elapsed_time", &self.elapsed_time())
.finish()
}
}
impl PartialEq for AnimationData {
fn eq(&self, other: &Self) -> bool {
self.animation_name() == other.animation_name()
&& self.pseudo_element() == other.pseudo_element()
&& self.elapsed_time() == other.elapsed_time()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of AnimationData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedAnimationData {
animation_name: String,
pseudo_element: String,
elapsed_time: f32,
}
#[cfg(feature = "serialize")]
impl From<&AnimationData> for SerializedAnimationData {
fn from(data: &AnimationData) -> Self {
Self {
animation_name: data.animation_name(),
pseudo_element: data.pseudo_element(),
elapsed_time: data.elapsed_time(),
}
}
}
#[cfg(feature = "serialize")]
impl HasAnimationData for SerializedAnimationData {
fn animation_name(&self) -> String {
self.animation_name.clone()
}
fn pseudo_element(&self) -> String {
self.pseudo_element.clone()
}
fn elapsed_time(&self) -> f32 {
self.elapsed_time
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for AnimationData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedAnimationData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for AnimationData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedAnimationData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
/// A trait for any object that has the data for an animation event
pub trait HasAnimationData: std::any::Any {
/// The name of the animation
fn animation_name(&self) -> String;
/// The name of the pseudo-element the animation runs on
fn pseudo_element(&self) -> String;
/// The amount of time the animation has been running
fn elapsed_time(&self) -> f32;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! [
AnimationData;
/// onanimationstart
onanimationstart
/// onanimationend
onanimationend
/// onanimationiteration
onanimationiteration
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/form.rs | packages/html/src/events/form.rs | use crate::file_data::HasFileData;
use crate::FileData;
use std::fmt::Debug;
use dioxus_core::Event;
pub type FormEvent = Event<FormData>;
/* DOMEvent: Send + SyncTarget relatedTarget */
pub struct FormData {
inner: Box<dyn HasFormData>,
}
impl FormData {
/// Create a new form event
pub fn new(event: impl HasFormData + 'static) -> Self {
Self {
inner: Box::new(event),
}
}
/// Get the value of the form event
pub fn value(&self) -> String {
self.inner.value()
}
/// Get the value of the form event as a parsed type
pub fn parsed<T>(&self) -> Result<T, T::Err>
where
T: std::str::FromStr,
{
self.value().parse()
}
/// Try to parse the value as a boolean
///
/// Returns false if the value is not a boolean, or if it is false!
/// Does not verify anything about the event itself, use with caution
pub fn checked(&self) -> bool {
self.value().parse().unwrap_or(false)
}
/// Collect all the named form values from the containing form.
///
/// Every input must be named!
pub fn values(&self) -> Vec<(String, FormValue)> {
self.inner.values()
}
/// Get the first value with the given name
pub fn get_first(&self, name: &str) -> Option<FormValue> {
self.values()
.into_iter()
.find_map(|(k, v)| if k == name { Some(v) } else { None })
}
/// Get all values with the given name
pub fn get(&self, name: &str) -> Vec<FormValue> {
self.values()
.into_iter()
.filter_map(|(k, v)| if k == name { Some(v) } else { None })
.collect()
}
/// Get the files of the form event
pub fn files(&self) -> Vec<FileData> {
self.inner.files()
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
/// Did this form pass its own validation?
pub fn valid(&self) -> bool {
!self.inner.value().is_empty()
}
}
impl FormData {
/// Parse the values into a struct with one field per value
#[cfg(feature = "serialize")]
pub fn parsed_values<T>(&self) -> Result<T, serde_json::Error>
where
T: serde::de::DeserializeOwned,
{
use crate::SerializedFileData;
let values = &self.values();
let mut map = serde_json::Map::new();
for (key, value) in values {
let entry = map
.entry(key.clone())
.or_insert_with(|| serde_json::Value::Array(Vec::new()));
match value {
FormValue::Text(text) => {
entry
.as_array_mut()
.expect("entry should be an array")
.push(serde_json::Value::String(text.clone()));
}
// we create the serialized variant with no bytes
// SerializedFileData, if given a real path, will read the bytes from disk (synchronously)
FormValue::File(Some(file_data)) => {
let serialized = SerializedFileData {
path: file_data.path().to_owned(),
size: file_data.size(),
last_modified: file_data.last_modified(),
content_type: file_data.content_type(),
contents: None,
};
entry
.as_array_mut()
.expect("entry should be an array")
.push(serde_json::to_value(&serialized).unwrap_or(serde_json::Value::Null));
}
FormValue::File(None) => {
entry
.as_array_mut()
.expect("entry should be an array")
.push(
serde_json::to_value(SerializedFileData::empty())
.unwrap_or(serde_json::Value::Null),
);
}
}
}
// Go through the map and convert single-element arrays to just the element
let map = map
.into_iter()
.map(|(k, v)| match v {
serde_json::Value::Array(arr) if arr.len() == 1 => {
(k, arr.into_iter().next().unwrap())
}
_ => (k, v),
})
.collect::<serde_json::Map<String, serde_json::Value>>();
serde_json::from_value(serde_json::Value::Object(map))
}
}
impl HasFileData for FormData {
fn files(&self) -> Vec<FileData> {
self.inner.files()
}
}
impl<E: HasFormData> From<E> for FormData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl PartialEq for FormData {
fn eq(&self, other: &Self) -> bool {
self.value() == other.value() && self.values() == other.values()
}
}
impl Debug for FormData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FormEvent")
.field("value", &self.value())
.field("values", &self.values())
.field("valid", &self.valid())
.finish()
}
}
/// A value in a form, either text or a file
#[derive(Debug, Clone, PartialEq)]
pub enum FormValue {
Text(String),
File(Option<FileData>),
}
impl PartialEq<str> for FormValue {
fn eq(&self, other: &str) -> bool {
match self {
FormValue::Text(s) => s == other,
FormValue::File(_f) => false,
}
}
}
impl PartialEq<&str> for FormValue {
fn eq(&self, other: &&str) -> bool {
match self {
FormValue::Text(s) => s == other,
FormValue::File(_f) => false,
}
}
}
/// An object that has all the data for a form event
pub trait HasFormData: HasFileData + std::any::Any {
fn value(&self) -> String;
fn valid(&self) -> bool;
fn values(&self) -> Vec<(String, FormValue)>;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
#[cfg(feature = "serialize")]
pub use serialize::*;
#[cfg(feature = "serialize")]
mod serialize {
use crate::SerializedFileData;
use super::*;
/// A serialized form data object
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedFormData {
#[serde(default)]
pub value: String,
#[serde(default)]
pub values: Vec<SerializedFormObject>,
#[serde(default)]
pub valid: bool,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedFormObject {
pub key: String,
pub text: Option<String>,
pub file: Option<SerializedFileData>,
}
#[cfg(feature = "serialize")]
impl SerializedFormData {
/// Create a new serialized form data object
pub fn new(value: String, values: Vec<SerializedFormObject>) -> Self {
Self {
value,
values,
valid: true,
}
}
/// Create a serialized form data object from a form data object
fn from_form_lossy(data: &FormData) -> Self {
if let Some(data) = data.downcast::<SerializedFormData>() {
return data.clone();
}
let values = data
.values()
.iter()
.map(|(key, value)| match value {
FormValue::Text(s) => SerializedFormObject {
key: key.clone(),
text: Some(s.to_string()),
file: None,
},
FormValue::File(f) => SerializedFormObject {
key: key.clone(),
text: None,
file: if let Some(f) = f {
Some(SerializedFileData {
path: f.path(),
size: f.size(),
last_modified: f.last_modified(),
content_type: f.content_type(),
contents: None,
})
} else {
Some(SerializedFileData::empty())
},
},
})
.collect();
Self {
values,
value: data.value(),
valid: data.valid(),
}
}
}
impl HasFormData for SerializedFormData {
fn value(&self) -> String {
self.value.clone()
}
fn values(&self) -> Vec<(String, FormValue)> {
self.values
.iter()
.map(|v| {
let value = if let Some(text) = &v.text {
FormValue::Text(text.clone())
} else if let Some(_file) = &v.file {
// todo: we lose the file contents here
FormValue::File(None)
} else {
FormValue::File(None)
};
(v.key.clone(), value)
})
.collect()
}
fn valid(&self) -> bool {
self.valid
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl HasFileData for SerializedFormData {
fn files(&self) -> Vec<FileData> {
self.values
.iter()
.filter_map(|v| v.file.as_ref().map(|f| FileData::new(f.clone())))
.collect()
}
}
impl serde::Serialize for FormData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedFormData::from_form_lossy(self).serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for FormData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedFormData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
}
impl_event! {
FormData;
/// onchange
onchange
/// The `oninput` event is fired when the value of a `<input>`, `<select>`, or `<textarea>` element is changed.
///
/// There are two main approaches to updating your input element:
/// 1) Controlled inputs directly update the value of the input element as the user interacts with the element
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn App() -> Element {
/// let mut value = use_signal(|| "hello world".to_string());
///
/// rsx! {
/// input {
/// // We directly set the value of the input element to our value signal
/// value: "{value}",
/// // The `oninput` event handler will run every time the user changes the value of the input element
/// // We can set the `value` signal to the new value of the input element
/// oninput: move |event| value.set(event.value())
/// }
/// // Since this is a controlled input, we can also update the value of the input element directly
/// button {
/// onclick: move |_| value.write().clear(),
/// "Clear"
/// }
/// }
/// }
/// ```
///
/// 2) Uncontrolled inputs just read the value of the input element as it changes
///
/// ```rust
/// use dioxus::prelude::*;
///
/// fn App() -> Element {
/// rsx! {
/// input {
/// // In uncontrolled inputs, we don't set the value of the input element directly
/// // But you can still read the value of the input element
/// oninput: move |event| println!("{}", event.value()),
/// }
/// // Since we don't directly control the value of the input element, we can't easily modify it
/// }
/// }
/// ```
oninput
/// oninvalid
oninvalid
/// onreset
onreset
/// onsubmit
onsubmit
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/drag.rs | packages/html/src/events/drag.rs | use crate::input_data::{MouseButton, MouseButtonSet};
use crate::*;
use crate::{
data_transfer::DataTransfer,
geometry::{ClientPoint, Coordinates, ElementPoint, PagePoint, ScreenPoint},
};
use dioxus_core::Event;
use keyboard_types::Modifiers;
use crate::HasMouseData;
pub type DragEvent = Event<DragData>;
/// The DragEvent interface is a DOM event that represents a drag and drop interaction. The user initiates a drag by
/// placing a pointer device (such as a mouse) on the touch surface and then dragging the pointer to a new location
/// (such as another DOM element). Applications are free to interpret a drag and drop interaction in an
/// application-specific way.
pub struct DragData {
inner: Box<dyn HasDragData>,
}
impl<E: HasDragData + 'static> From<E> for DragData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for DragData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DragData")
.field("coordinates", &self.coordinates())
.field("modifiers", &self.modifiers())
.field("held_buttons", &self.held_buttons())
.field("trigger_button", &self.trigger_button())
.finish()
}
}
impl PartialEq for DragData {
fn eq(&self, other: &Self) -> bool {
self.coordinates() == other.coordinates()
&& self.modifiers() == other.modifiers()
&& self.held_buttons() == other.held_buttons()
&& self.trigger_button() == other.trigger_button()
}
}
impl DragData {
/// Create a new DragData
pub fn new(inner: impl HasDragData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation.
pub fn data_transfer(&self) -> DataTransfer {
self.inner.data_transfer()
}
/// Downcast this event data to a specific type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
HasDragData::as_any(&*self.inner).downcast_ref::<T>()
}
}
impl crate::HasFileData for DragData {
fn files(&self) -> Vec<FileData> {
self.inner.files()
}
}
impl InteractionLocation for DragData {
fn client_coordinates(&self) -> ClientPoint {
self.inner.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.inner.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.inner.screen_coordinates()
}
}
impl InteractionElementOffset for DragData {
fn element_coordinates(&self) -> ElementPoint {
self.inner.element_coordinates()
}
fn coordinates(&self) -> Coordinates {
self.inner.coordinates()
}
}
impl ModifiersInteraction for DragData {
fn modifiers(&self) -> Modifiers {
self.inner.modifiers()
}
}
impl PointerInteraction for DragData {
fn held_buttons(&self) -> MouseButtonSet {
self.inner.held_buttons()
}
// todo the following is kind of bad; should we just return None when the trigger_button is unreliable (and frankly irrelevant)? i guess we would need the event_type here
fn trigger_button(&self) -> Option<MouseButton> {
self.inner.trigger_button()
}
}
#[cfg(feature = "serialize")]
pub use ser::*;
#[cfg(feature = "serialize")]
mod ser {
use super::*;
/// A serialized version of DragData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedDragData {
pub mouse: crate::point_interaction::SerializedPointInteraction,
pub data_transfer: crate::data_transfer::SerializedDataTransfer,
}
impl SerializedDragData {
fn new(drag: &DragData) -> Self {
Self {
mouse: crate::point_interaction::SerializedPointInteraction::from(drag),
data_transfer: crate::data_transfer::SerializedDataTransfer::from(drag),
}
}
}
impl HasDataTransferData for SerializedDragData {
fn data_transfer(&self) -> crate::data_transfer::DataTransfer {
crate::data_transfer::DataTransfer::new(self.data_transfer.clone())
}
}
impl HasDragData for SerializedDragData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl crate::file_data::HasFileData for SerializedDragData {
fn files(&self) -> Vec<FileData> {
self.data_transfer
.files
.iter()
.map(|f| FileData::new(f.clone()))
.collect()
}
}
impl HasMouseData for SerializedDragData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl InteractionLocation for SerializedDragData {
fn client_coordinates(&self) -> ClientPoint {
self.mouse.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.mouse.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.mouse.screen_coordinates()
}
}
impl InteractionElementOffset for SerializedDragData {
fn element_coordinates(&self) -> ElementPoint {
self.mouse.element_coordinates()
}
fn coordinates(&self) -> Coordinates {
self.mouse.coordinates()
}
}
impl ModifiersInteraction for SerializedDragData {
fn modifiers(&self) -> Modifiers {
self.mouse.modifiers()
}
}
impl PointerInteraction for SerializedDragData {
fn held_buttons(&self) -> MouseButtonSet {
self.mouse.held_buttons()
}
fn trigger_button(&self) -> Option<MouseButton> {
self.mouse.trigger_button()
}
}
impl serde::Serialize for DragData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedDragData::new(self).serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for DragData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedDragData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
}
/// A trait for any object that has the data for a drag event
pub trait HasDragData: HasMouseData + crate::HasFileData + crate::HasDataTransferData {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! {
DragData;
/// ondrag
ondrag
/// ondragend
ondragend
/// ondragenter
ondragenter
/// ondragexit
ondragexit
/// ondragleave
ondragleave
/// ondragover
ondragover
/// ondragstart
ondragstart
/// ondrop
ondrop
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/media.rs | packages/html/src/events/media.rs | use dioxus_core::Event;
pub type MediaEvent = Event<MediaData>;
pub struct MediaData {
inner: Box<dyn HasMediaData>,
}
impl<E: HasMediaData> From<E> for MediaData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for MediaData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MediaData").finish()
}
}
impl PartialEq for MediaData {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl MediaData {
/// Create a new MediaData
pub fn new(inner: impl HasMediaData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of MediaData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedMediaData {}
#[cfg(feature = "serialize")]
impl From<&MediaData> for SerializedMediaData {
fn from(_: &MediaData) -> Self {
Self {}
}
}
#[cfg(feature = "serialize")]
impl HasMediaData for SerializedMediaData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for MediaData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedMediaData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for MediaData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedMediaData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasMediaData: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! [
MediaData;
///abort
onabort
///canplay
oncanplay
///canplaythrough
oncanplaythrough
///durationchange
ondurationchange
///emptied
onemptied
///encrypted
onencrypted
///ended
onended
// todo: this conflicts with Media events
// neither have data, so it's okay
// ///error
// onerror
///loadeddata
onloadeddata
///loadedmetadata
onloadedmetadata
///loadstart
onloadstart
///pause
onpause
///play
onplay
///playing
onplaying
///progress
onprogress
///ratechange
onratechange
///seeked
onseeked
///seeking
onseeking
///stalled
onstalled
///suspend
onsuspend
///timeupdate
ontimeupdate
///volumechange
onvolumechange
///waiting
onwaiting
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/toggle.rs | packages/html/src/events/toggle.rs | use dioxus_core::Event;
pub type ToggleEvent = Event<ToggleData>;
pub struct ToggleData {
inner: Box<dyn HasToggleData>,
}
impl<E: HasToggleData> From<E> for ToggleData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for ToggleData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ToggleData").finish()
}
}
impl PartialEq for ToggleData {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl ToggleData {
/// Create a new ToggleData
pub fn new(inner: impl HasToggleData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of ToggleData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedToggleData {}
#[cfg(feature = "serialize")]
impl From<&ToggleData> for SerializedToggleData {
fn from(_: &ToggleData) -> Self {
Self {}
}
}
#[cfg(feature = "serialize")]
impl HasToggleData for SerializedToggleData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for ToggleData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedToggleData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for ToggleData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedToggleData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasToggleData: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! {
ToggleData;
/// ontoggle
ontoggle
/// onbeforetoggle
onbeforetoggle
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/cancel.rs | packages/html/src/events/cancel.rs | use dioxus_core::Event;
pub type CancelEvent = Event<CancelData>;
pub struct CancelData {
inner: Box<dyn HasCancelData>,
}
impl<E: HasCancelData> From<E> for CancelData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for CancelData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CancelData").finish()
}
}
impl PartialEq for CancelData {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl CancelData {
/// Create a new CancelData
pub fn new(inner: impl HasCancelData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of CancelData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedCancelData {}
#[cfg(feature = "serialize")]
impl From<&CancelData> for SerializedCancelData {
fn from(_: &CancelData) -> Self {
Self {}
}
}
#[cfg(feature = "serialize")]
impl HasCancelData for SerializedCancelData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for CancelData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedCancelData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for CancelData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedCancelData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasCancelData: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! {
CancelData;
/// oncancel
oncancel
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/transition.rs | packages/html/src/events/transition.rs | use dioxus_core::Event;
pub type TransitionEvent = Event<TransitionData>;
pub struct TransitionData {
inner: Box<dyn HasTransitionData>,
}
impl<E: HasTransitionData> From<E> for TransitionData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for TransitionData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TransitionData")
.field("property_name", &self.inner.property_name())
.field("pseudo_element", &self.inner.pseudo_element())
.field("elapsed_time", &self.inner.elapsed_time())
.finish()
}
}
impl PartialEq for TransitionData {
fn eq(&self, other: &Self) -> bool {
self.inner.property_name() == other.inner.property_name()
&& self.inner.pseudo_element() == other.inner.pseudo_element()
&& self.inner.elapsed_time() == other.inner.elapsed_time()
}
}
impl TransitionData {
/// Create a new TransitionData
pub fn new(inner: impl HasTransitionData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of TransitionData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedTransitionData {
property_name: String,
pseudo_element: String,
elapsed_time: f32,
}
#[cfg(feature = "serialize")]
impl From<&TransitionData> for SerializedTransitionData {
fn from(data: &TransitionData) -> Self {
Self {
property_name: data.inner.property_name(),
pseudo_element: data.inner.pseudo_element(),
elapsed_time: data.inner.elapsed_time(),
}
}
}
#[cfg(feature = "serialize")]
impl HasTransitionData for SerializedTransitionData {
fn property_name(&self) -> String {
self.property_name.clone()
}
fn pseudo_element(&self) -> String {
self.pseudo_element.clone()
}
fn elapsed_time(&self) -> f32 {
self.elapsed_time
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for TransitionData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedTransitionData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for TransitionData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedTransitionData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasTransitionData: std::any::Any {
fn property_name(&self) -> String;
fn pseudo_element(&self) -> String;
fn elapsed_time(&self) -> f32;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! {
TransitionData;
/// transitionend
ontransitionend
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/wheel.rs | packages/html/src/events/wheel.rs | use dioxus_core::Event;
use keyboard_types::Modifiers;
use std::fmt::Formatter;
use crate::{geometry::*, InteractionLocation, ModifiersInteraction, PointerInteraction};
use crate::{
input_data::{MouseButton, MouseButtonSet},
InteractionElementOffset,
};
use super::HasMouseData;
/// A synthetic event that wraps a web-style
/// [`WheelEvent`](https://developer.mozilla.org/en-US/docs/Web/API/WheelEvent)
pub type WheelEvent = Event<WheelData>;
/// Data associated with a [WheelEvent]
pub struct WheelData {
inner: Box<dyn HasWheelData>,
}
impl<E: HasWheelData> From<E> for WheelData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for WheelData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WheelData")
.field("delta", &self.delta())
.field("coordinates", &self.coordinates())
.field("modifiers", &self.modifiers())
.field("held_buttons", &self.held_buttons())
.field("trigger_button", &self.trigger_button())
.finish()
}
}
impl PartialEq for WheelData {
fn eq(&self, other: &Self) -> bool {
self.inner.delta() == other.inner.delta()
}
}
impl WheelData {
pub fn new(inner: impl HasWheelData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// The amount of wheel movement
#[allow(deprecated)]
pub fn delta(&self) -> WheelDelta {
self.inner.delta()
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
HasWheelData::as_any(&*self.inner).downcast_ref::<T>()
}
}
impl InteractionLocation for WheelData {
fn client_coordinates(&self) -> ClientPoint {
self.inner.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.inner.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.inner.screen_coordinates()
}
}
impl InteractionElementOffset for WheelData {
fn element_coordinates(&self) -> ElementPoint {
self.inner.element_coordinates()
}
fn coordinates(&self) -> Coordinates {
self.inner.coordinates()
}
}
impl ModifiersInteraction for WheelData {
fn modifiers(&self) -> Modifiers {
self.inner.modifiers()
}
}
impl PointerInteraction for WheelData {
fn held_buttons(&self) -> MouseButtonSet {
self.inner.held_buttons()
}
// todo the following is kind of bad; should we just return None when the trigger_button is unreliable (and frankly irrelevant)? i guess we would need the event_type here
fn trigger_button(&self) -> Option<MouseButton> {
self.inner.trigger_button()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of WheelData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedWheelData {
#[serde(flatten)]
pub mouse: crate::point_interaction::SerializedPointInteraction,
pub delta_mode: u32,
pub delta_x: f64,
pub delta_y: f64,
pub delta_z: f64,
}
#[cfg(feature = "serialize")]
impl SerializedWheelData {
/// Create a new SerializedWheelData
pub fn new(wheel: &WheelData) -> Self {
let delta_mode = match wheel.delta() {
WheelDelta::Pixels(_) => 0,
WheelDelta::Lines(_) => 1,
WheelDelta::Pages(_) => 2,
};
let delta_raw = wheel.delta().strip_units();
Self {
mouse: crate::point_interaction::SerializedPointInteraction::from(wheel),
delta_mode,
delta_x: delta_raw.x,
delta_y: delta_raw.y,
delta_z: delta_raw.z,
}
}
}
#[cfg(feature = "serialize")]
impl From<&WheelData> for SerializedWheelData {
fn from(data: &WheelData) -> Self {
Self::new(data)
}
}
#[cfg(feature = "serialize")]
impl HasWheelData for SerializedWheelData {
fn delta(&self) -> WheelDelta {
WheelDelta::from_web_attributes(self.delta_mode, self.delta_x, self.delta_y, self.delta_z)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl HasMouseData for SerializedWheelData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl InteractionLocation for SerializedWheelData {
fn client_coordinates(&self) -> ClientPoint {
self.mouse.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.mouse.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.mouse.screen_coordinates()
}
}
#[cfg(feature = "serialize")]
impl InteractionElementOffset for SerializedWheelData {
fn element_coordinates(&self) -> ElementPoint {
self.mouse.element_coordinates()
}
fn coordinates(&self) -> Coordinates {
self.mouse.coordinates()
}
}
#[cfg(feature = "serialize")]
impl ModifiersInteraction for SerializedWheelData {
fn modifiers(&self) -> Modifiers {
self.mouse.modifiers()
}
}
#[cfg(feature = "serialize")]
impl PointerInteraction for SerializedWheelData {
fn held_buttons(&self) -> MouseButtonSet {
self.mouse.held_buttons()
}
fn trigger_button(&self) -> Option<MouseButton> {
self.mouse.trigger_button()
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for WheelData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedWheelData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for WheelData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedWheelData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
impl_event![
WheelData;
/// Called when the mouse wheel is rotated over an element.
onwheel
];
pub trait HasWheelData: HasMouseData + std::any::Any {
/// The amount of wheel movement
fn delta(&self) -> WheelDelta;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/mod.rs | packages/html/src/events/mod.rs | #![doc = include_str!("../../docs/event_handlers.md")]
use std::any::Any;
use std::sync::RwLock;
macro_rules! impl_event {
(
$data:ty;
$(
$( #[$attr:meta] )*
$name:ident $(: $js_name:literal)?
)*
) => {
$(
$( #[$attr] )*
/// <details open>
/// <summary>General Event Handler Information</summary>
///
#[doc = include_str!("../../docs/event_handlers.md")]
///
/// </details>
///
#[doc = include_str!("../../docs/common_event_handler_errors.md")]
$(
#[doc(alias = $js_name)]
)?
#[inline]
pub fn $name<__Marker>(mut _f: impl ::dioxus_core::SuperInto<::dioxus_core::ListenerCallback<$data>, __Marker>) -> ::dioxus_core::Attribute {
let event_handler = _f.super_into();
::dioxus_core::Attribute::new(
impl_event!(@name $name $($js_name)?),
::dioxus_core::AttributeValue::listener(move |e: ::dioxus_core::Event<crate::PlatformEventData>| {
let event: ::dioxus_core::Event<$data> = e.map(|data| {
data.into()
});
event_handler.call(event.into_any());
}),
None,
false,
).into()
}
#[doc(hidden)]
$( #[$attr] )*
pub mod $name {
use super::*;
// When expanding the macro, we use this version of the function if we see an inline closure to give better type inference
$( #[$attr] )*
pub fn call_with_explicit_closure<
__Marker,
Return: ::dioxus_core::SpawnIfAsync<__Marker> + 'static,
>(
event_handler: impl FnMut(::dioxus_core::Event<$data>) -> Return + 'static,
) -> ::dioxus_core::Attribute {
#[allow(deprecated)]
super::$name(event_handler)
}
}
)*
};
(@name $name:ident $js_name:literal) => {
$js_name
};
(@name $name:ident) => {
stringify!($name)
};
}
static EVENT_CONVERTER: RwLock<Option<Box<dyn HtmlEventConverter>>> = RwLock::new(None);
#[inline]
pub fn set_event_converter(converter: Box<dyn HtmlEventConverter>) {
*EVENT_CONVERTER.write().unwrap() = Some(converter);
}
#[inline]
pub(crate) fn with_event_converter<F, R>(f: F) -> R
where
F: FnOnce(&dyn HtmlEventConverter) -> R,
{
let converter = EVENT_CONVERTER.read().unwrap();
f(converter.as_ref().unwrap().as_ref())
}
/// A platform specific event.
pub struct PlatformEventData {
event: Box<dyn Any>,
}
impl PlatformEventData {
pub fn new(event: Box<dyn Any>) -> Self {
Self { event }
}
pub fn inner(&self) -> &Box<dyn Any> {
&self.event
}
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.event.downcast_ref::<T>()
}
pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
self.event.downcast_mut::<T>()
}
pub fn into_inner<T: 'static>(self) -> Option<T> {
self.event.downcast::<T>().ok().map(|e| *e)
}
}
/// A converter between a platform specific event and a general event. All code in a renderer that has a large binary size should be placed in this trait. Each of these functions should be snipped in high levels of optimization.
pub trait HtmlEventConverter: Send + Sync {
/// Convert a general event to an animation data event
fn convert_animation_data(&self, event: &PlatformEventData) -> AnimationData;
/// Convert a general event to a cancel data event
fn convert_cancel_data(&self, event: &PlatformEventData) -> CancelData;
/// Convert a general event to a clipboard data event
fn convert_clipboard_data(&self, event: &PlatformEventData) -> ClipboardData;
/// Convert a general event to a composition data event
fn convert_composition_data(&self, event: &PlatformEventData) -> CompositionData;
/// Convert a general event to a drag data event
fn convert_drag_data(&self, event: &PlatformEventData) -> DragData;
/// Convert a general event to a focus data event
fn convert_focus_data(&self, event: &PlatformEventData) -> FocusData;
/// Convert a general event to a form data event
fn convert_form_data(&self, event: &PlatformEventData) -> FormData;
/// Convert a general event to an image data event
fn convert_image_data(&self, event: &PlatformEventData) -> ImageData;
/// Convert a general event to a keyboard data event
fn convert_keyboard_data(&self, event: &PlatformEventData) -> KeyboardData;
/// Convert a general event to a media data event
fn convert_media_data(&self, event: &PlatformEventData) -> MediaData;
/// Convert a general event to a mounted data event
fn convert_mounted_data(&self, event: &PlatformEventData) -> MountedData;
/// Convert a general event to a mouse data event
fn convert_mouse_data(&self, event: &PlatformEventData) -> MouseData;
/// Convert a general event to a pointer data event
fn convert_pointer_data(&self, event: &PlatformEventData) -> PointerData;
/// Convert a general event to a resize data event
fn convert_resize_data(&self, event: &PlatformEventData) -> ResizeData;
/// Convert a general event to a scroll data event
fn convert_scroll_data(&self, event: &PlatformEventData) -> ScrollData;
/// Convert a general event to a selection data event
fn convert_selection_data(&self, event: &PlatformEventData) -> SelectionData;
/// Convert a general event to a toggle data event
fn convert_toggle_data(&self, event: &PlatformEventData) -> ToggleData;
/// Convert a general event to a touch data event
fn convert_touch_data(&self, event: &PlatformEventData) -> TouchData;
/// Convert a general event to a transition data event
fn convert_transition_data(&self, event: &PlatformEventData) -> TransitionData;
/// Convert a general event to a visible data event
fn convert_visible_data(&self, event: &PlatformEventData) -> VisibleData;
/// Convert a general event to a wheel data event
fn convert_wheel_data(&self, event: &PlatformEventData) -> WheelData;
}
impl From<&PlatformEventData> for AnimationData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_animation_data(val))
}
}
impl From<&PlatformEventData> for CancelData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_cancel_data(val))
}
}
impl From<&PlatformEventData> for ClipboardData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_clipboard_data(val))
}
}
impl From<&PlatformEventData> for CompositionData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_composition_data(val))
}
}
impl From<&PlatformEventData> for DragData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_drag_data(val))
}
}
impl From<&PlatformEventData> for FocusData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_focus_data(val))
}
}
impl From<&PlatformEventData> for FormData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_form_data(val))
}
}
impl From<&PlatformEventData> for ImageData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_image_data(val))
}
}
impl From<&PlatformEventData> for KeyboardData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_keyboard_data(val))
}
}
impl From<&PlatformEventData> for MediaData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_media_data(val))
}
}
impl From<&PlatformEventData> for MountedData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_mounted_data(val))
}
}
impl From<&PlatformEventData> for MouseData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_mouse_data(val))
}
}
impl From<&PlatformEventData> for PointerData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_pointer_data(val))
}
}
impl From<&PlatformEventData> for ResizeData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_resize_data(val))
}
}
impl From<&PlatformEventData> for ScrollData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_scroll_data(val))
}
}
impl From<&PlatformEventData> for SelectionData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_selection_data(val))
}
}
impl From<&PlatformEventData> for ToggleData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_toggle_data(val))
}
}
impl From<&PlatformEventData> for TouchData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_touch_data(val))
}
}
impl From<&PlatformEventData> for TransitionData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_transition_data(val))
}
}
impl From<&PlatformEventData> for VisibleData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_visible_data(val))
}
}
impl From<&PlatformEventData> for WheelData {
fn from(val: &PlatformEventData) -> Self {
with_event_converter(|c| c.convert_wheel_data(val))
}
}
mod animation;
mod cancel;
mod clipboard;
mod composition;
mod drag;
mod focus;
mod form;
mod image;
mod keyboard;
mod media;
mod mounted;
mod mouse;
mod pointer;
mod resize;
mod scroll;
mod selection;
mod toggle;
mod touch;
mod transition;
mod visible;
mod wheel;
pub use animation::*;
pub use cancel::*;
pub use clipboard::*;
pub use composition::*;
pub use drag::*;
pub use focus::*;
pub use form::*;
pub use image::*;
pub use keyboard::*;
pub use media::*;
pub use mounted::*;
pub use mouse::*;
pub use pointer::*;
pub use resize::*;
pub use scroll::*;
pub use selection::*;
pub use toggle::*;
pub use touch::*;
pub use transition::*;
pub use visible::*;
pub use wheel::*;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/selection.rs | packages/html/src/events/selection.rs | use dioxus_core::Event;
pub type SelectionEvent = Event<SelectionData>;
pub struct SelectionData {
inner: Box<dyn HasSelectionData>,
}
impl SelectionData {
/// Create a new SelectionData
pub fn new(inner: impl HasSelectionData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl<E: HasSelectionData> From<E> for SelectionData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for SelectionData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SelectionData").finish()
}
}
impl PartialEq for SelectionData {
fn eq(&self, _other: &Self) -> bool {
true
}
}
#[cfg(feature = "serialize")]
/// A serialized version of SelectionData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedSelectionData {}
#[cfg(feature = "serialize")]
impl From<&SelectionData> for SerializedSelectionData {
fn from(_: &SelectionData) -> Self {
Self {}
}
}
#[cfg(feature = "serialize")]
impl HasSelectionData for SerializedSelectionData {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for SelectionData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedSelectionData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for SelectionData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedSelectionData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasSelectionData: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event! [
SelectionData;
/// select
onselect
/// selectstart
onselectstart
/// selectionchange
onselectionchange
];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/mounted.rs | packages/html/src/events/mounted.rs | //! Handles querying data from the renderer
use std::{
fmt::{Debug, Display, Formatter},
future::Future,
pin::Pin,
};
/// An Element that has been rendered and allows reading and modifying information about it.
///
/// Different platforms will have different implementations and different levels of support for this trait. Renderers that do not support specific features will return `None` for those queries.
// we can not use async_trait here because it does not create a trait that is object safe
pub trait RenderedElementBacking: std::any::Any {
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
/// Get the number of pixels that an element's content is scrolled
fn get_scroll_offset(&self) -> Pin<Box<dyn Future<Output = MountedResult<PixelsVector2D>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}
/// Get the size of an element's content, including content not visible on the screen due to overflow
#[allow(clippy::type_complexity)]
fn get_scroll_size(&self) -> Pin<Box<dyn Future<Output = MountedResult<PixelsSize>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}
/// Get the bounding rectangle of the element relative to the viewport (this does not include the scroll position)
#[allow(clippy::type_complexity)]
fn get_client_rect(&self) -> Pin<Box<dyn Future<Output = MountedResult<PixelsRect>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}
/// Scroll to make the element visible
fn scroll_to(
&self,
_options: ScrollToOptions,
) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}
/// Scroll to the given element offsets
fn scroll(
&self,
_coordinates: PixelsVector2D,
_behavior: ScrollBehavior,
) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}
/// Set the focus on the element
fn set_focus(&self, _focus: bool) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
Box::pin(async { Err(MountedError::NotSupported) })
}
}
impl RenderedElementBacking for () {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
/// The way that scrolling should be performed
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(alias = "ScrollIntoViewOptions")]
pub enum ScrollBehavior {
/// Scroll to the element immediately
#[cfg_attr(feature = "serialize", serde(rename = "instant"))]
Instant,
/// Scroll to the element smoothly
#[default]
#[cfg_attr(feature = "serialize", serde(rename = "smooth"))]
Smooth,
}
/// The desired final position within the scrollable ancestor container for a given axis.
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(alias = "ScrollIntoViewOptions")]
pub enum ScrollLogicalPosition {
/// Aligns the element's start edge (top or left) with the start of the scrollable container,
/// making the element appear at the start of the visible area.
#[cfg_attr(feature = "serialize", serde(rename = "start"))]
Start,
/// Aligns the element at the center of the scrollable container,
/// positioning it in the middle of the visible area.
#[cfg_attr(feature = "serialize", serde(rename = "center"))]
Center,
/// Aligns the element's end edge (bottom or right) with the end of the scrollable container,
/// making the element appear at the end of the visible area
#[cfg_attr(feature = "serialize", serde(rename = "end"))]
End,
/// Scrolls the element to the nearest edge in the given axis.
/// This minimizes the scrolling distance.
#[cfg_attr(feature = "serialize", serde(rename = "nearest"))]
Nearest,
}
/// The way that scrolling should be performed
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[doc(alias = "ScrollIntoViewOptions")]
pub struct ScrollToOptions {
pub behavior: ScrollBehavior,
pub vertical: ScrollLogicalPosition,
pub horizontal: ScrollLogicalPosition,
}
impl Default for ScrollToOptions {
fn default() -> Self {
Self {
behavior: ScrollBehavior::Smooth,
vertical: ScrollLogicalPosition::Start,
horizontal: ScrollLogicalPosition::Center,
}
}
}
/// An Element that has been rendered and allows reading and modifying information about it.
///
/// Different platforms will have different implementations and different levels of support for this trait. Renderers that do not support specific features will return `None` for those queries.
pub struct MountedData {
inner: Box<dyn RenderedElementBacking>,
}
impl Debug for MountedData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MountedData").finish()
}
}
impl<E: RenderedElementBacking> From<E> for MountedData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl MountedData {
/// Create a new MountedData
pub fn new(registry: impl RenderedElementBacking + 'static) -> Self {
Self {
inner: Box::new(registry),
}
}
/// Get the number of pixels that an element's content is scrolled
#[doc(alias = "scrollTop")]
#[doc(alias = "scrollLeft")]
pub async fn get_scroll_offset(&self) -> MountedResult<PixelsVector2D> {
self.inner.get_scroll_offset().await
}
/// Get the size of an element's content, including content not visible on the screen due to overflow
#[doc(alias = "scrollWidth")]
#[doc(alias = "scrollHeight")]
pub async fn get_scroll_size(&self) -> MountedResult<PixelsSize> {
self.inner.get_scroll_size().await
}
/// Get the bounding rectangle of the element relative to the viewport (this does not include the scroll position)
#[doc(alias = "getBoundingClientRect")]
pub async fn get_client_rect(&self) -> MountedResult<PixelsRect> {
self.inner.get_client_rect().await
}
/// Scroll to make the element visible
#[doc(alias = "scrollIntoView")]
pub fn scroll_to(
&self,
behavior: ScrollBehavior,
) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
self.inner.scroll_to(ScrollToOptions {
behavior,
..ScrollToOptions::default()
})
}
/// Scroll to make the element visible
#[doc(alias = "scrollIntoView")]
pub fn scroll_to_with_options(
&self,
options: ScrollToOptions,
) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
self.inner.scroll_to(options)
}
/// Scroll to the given element offsets
#[doc(alias = "scrollTo")]
pub fn scroll(
&self,
coordinates: PixelsVector2D,
behavior: ScrollBehavior,
) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
self.inner.scroll(coordinates, behavior)
}
/// Set the focus on the element
#[doc(alias = "focus")]
#[doc(alias = "blur")]
pub fn set_focus(&self, focus: bool) -> Pin<Box<dyn Future<Output = MountedResult<()>>>> {
self.inner.set_focus(focus)
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
use dioxus_core::Event;
use crate::geometry::{PixelsRect, PixelsSize, PixelsVector2D};
pub type MountedEvent = Event<MountedData>;
impl_event! [
MountedData;
#[doc(alias = "ref")]
#[doc(alias = "createRef")]
#[doc(alias = "useRef")]
/// The onmounted event is fired when the element is first added to the DOM. This event gives you a [`MountedData`] object and lets you interact with the raw DOM element.
///
/// This event is fired once per element. If you need to access the element multiple times, you can store the [`MountedData`] object in a [`use_signal`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_signal.html) hook and use it as needed.
///
/// # Examples
///
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// fn App() -> Element {
/// let mut header_element = use_signal(|| None);
///
/// rsx! {
/// div {
/// h1 {
/// // The onmounted event will run the first time the h1 element is mounted
/// onmounted: move |element| header_element.set(Some(element.data())),
/// "Scroll to top example"
/// }
///
/// for i in 0..100 {
/// div { "Item {i}" }
/// }
///
/// button {
/// // When you click the button, if the header element has been mounted, we scroll to that element
/// onclick: move |_| async move {
/// if let Some(header) = header_element.cloned() {
/// let _ = header.scroll_to(ScrollBehavior::Smooth).await;
/// }
/// },
/// "Scroll to top"
/// }
/// }
/// }
/// }
/// ```
///
/// The `MountedData` struct contains cross platform APIs that work on the desktop, mobile, liveview and web platforms. For the web platform, you can also downcast the `MountedData` event to the `web-sys::Element` type for more web specific APIs:
///
/// ```rust, ignore
/// use dioxus::prelude::*;
/// use dioxus_web::WebEventExt; // provides [`as_web_event()`] method
///
/// fn App() -> Element {
/// rsx! {
/// div {
/// id: "some-id",
/// onmounted: move |element| {
/// // You can use the web_event trait to downcast the element to a web specific event. For the mounted event, this will be a web_sys::Element
/// let web_sys_element = element.as_web_event();
/// assert_eq!(web_sys_element.id(), "some-id");
/// }
/// }
/// }
/// }
/// ```
onmounted
];
pub use onmounted as onmount;
/// The MountedResult type for the MountedData
pub type MountedResult<T> = Result<T, MountedError>;
#[derive(Debug)]
/// The error type for the MountedData
#[non_exhaustive]
pub enum MountedError {
/// The renderer does not support the requested operation
NotSupported,
/// The element was not found
OperationFailed(Box<dyn std::error::Error>),
}
impl Display for MountedError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
MountedError::NotSupported => {
write!(f, "The renderer does not support the requested operation")
}
MountedError::OperationFailed(e) => {
write!(f, "The operation failed: {}", e)
}
}
}
}
impl std::error::Error for MountedError {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/keyboard.rs | packages/html/src/events/keyboard.rs | use dioxus_core::Event;
use keyboard_types::{Code, Key, Location, Modifiers};
use std::fmt::Debug;
use crate::ModifiersInteraction;
#[cfg(feature = "serialize")]
fn resilient_deserialize_code<'de, D>(deserializer: D) -> Result<Code, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
// If we fail to deserialize the code for any reason, just return Unidentified instead of failing.
Ok(Code::deserialize(deserializer).unwrap_or(Code::Unidentified))
}
pub type KeyboardEvent = Event<KeyboardData>;
pub struct KeyboardData {
inner: Box<dyn HasKeyboardData>,
}
impl<E: HasKeyboardData> From<E> for KeyboardData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for KeyboardData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("KeyboardData")
.field("key", &self.key())
.field("code", &self.code())
.field("modifiers", &self.modifiers())
.field("location", &self.location())
.field("is_auto_repeating", &self.is_auto_repeating())
.field("is_composing", &self.is_composing())
.finish()
}
}
impl PartialEq for KeyboardData {
fn eq(&self, other: &Self) -> bool {
self.key() == other.key()
&& self.code() == other.code()
&& self.modifiers() == other.modifiers()
&& self.location() == other.location()
&& self.is_auto_repeating() == other.is_auto_repeating()
&& self.is_composing() == other.is_composing()
}
}
impl KeyboardData {
/// Create a new KeyboardData
pub fn new(inner: impl HasKeyboardData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// The value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout.
pub fn key(&self) -> Key {
self.inner.key()
}
/// A physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value that isn't altered by keyboard layout or the state of the modifier keys.
pub fn code(&self) -> Code {
self.inner.code()
}
/// The location of the key on the keyboard or other input device.
pub fn location(&self) -> Location {
self.inner.location()
}
/// `true` iff the key is being held down such that it is automatically repeating.
pub fn is_auto_repeating(&self) -> bool {
self.inner.is_auto_repeating()
}
/// Indicates whether the key is fired within a composition session.
pub fn is_composing(&self) -> bool {
self.inner.is_composing()
}
/// Downcast this KeyboardData to a concrete type.
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl ModifiersInteraction for KeyboardData {
fn modifiers(&self) -> Modifiers {
self.inner.modifiers()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of KeyboardData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedKeyboardData {
char_code: u32,
is_composing: bool,
key: String,
key_code: KeyCode,
#[serde(deserialize_with = "resilient_deserialize_code")]
code: Code,
alt_key: bool,
ctrl_key: bool,
meta_key: bool,
shift_key: bool,
location: usize,
repeat: bool,
which: usize,
}
#[cfg(feature = "serialize")]
impl SerializedKeyboardData {
/// Create a new SerializedKeyboardData
pub fn new(
key: Key,
code: Code,
location: Location,
is_auto_repeating: bool,
modifiers: Modifiers,
is_composing: bool,
) -> Self {
Self {
char_code: key.legacy_charcode(),
is_composing,
key: key.to_string(),
key_code: KeyCode::from_raw_code(
std::convert::TryInto::try_into(key.legacy_keycode())
.expect("could not convert keycode to u8"),
),
code,
alt_key: modifiers.contains(Modifiers::ALT),
ctrl_key: modifiers.contains(Modifiers::CONTROL),
meta_key: modifiers.contains(Modifiers::META),
shift_key: modifiers.contains(Modifiers::SHIFT),
location: crate::input_data::encode_key_location(location),
repeat: is_auto_repeating,
which: std::convert::TryInto::try_into(key.legacy_charcode())
.expect("could not convert charcode to usize"),
}
}
}
#[cfg(feature = "serialize")]
impl From<&KeyboardData> for SerializedKeyboardData {
fn from(data: &KeyboardData) -> Self {
Self::new(
data.key(),
data.code(),
data.location(),
data.is_auto_repeating(),
data.modifiers(),
data.is_composing(),
)
}
}
#[cfg(feature = "serialize")]
impl HasKeyboardData for SerializedKeyboardData {
fn key(&self) -> Key {
std::str::FromStr::from_str(&self.key).unwrap_or(Key::Unidentified)
}
fn code(&self) -> Code {
self.code
}
fn location(&self) -> Location {
crate::input_data::decode_key_location(self.location)
}
fn is_auto_repeating(&self) -> bool {
self.repeat
}
fn is_composing(&self) -> bool {
self.is_composing
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl ModifiersInteraction for SerializedKeyboardData {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
if self.alt_key {
modifiers.insert(Modifiers::ALT);
}
if self.ctrl_key {
modifiers.insert(Modifiers::CONTROL);
}
if self.meta_key {
modifiers.insert(Modifiers::META);
}
if self.shift_key {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for KeyboardData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedKeyboardData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for KeyboardData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedKeyboardData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
impl_event! {
KeyboardData;
/// onkeydown
onkeydown
/// onkeypress
onkeypress
/// onkeyup
onkeyup
}
pub trait HasKeyboardData: ModifiersInteraction + std::any::Any {
/// The value of the key pressed by the user, taking into consideration the state of modifier keys such as Shift as well as the keyboard locale and layout.
fn key(&self) -> Key;
/// A physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value that isn't altered by keyboard layout or the state of the modifier keys.
fn code(&self) -> Code;
/// The location of the key on the keyboard or other input device.
fn location(&self) -> Location;
/// `true` iff the key is being held down such that it is automatically repeating.
fn is_auto_repeating(&self) -> bool;
/// Indicates whether the key is fired within a composition session.
fn is_composing(&self) -> bool;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for KeyCode {
fn deserialize<D>(deserializer: D) -> Result<KeyCode, D::Error>
where
D: serde::Deserializer<'de>,
{
// We could be deserializing a unicode character, so we need to use u64 even if the output only takes u8
let value = u64::deserialize(deserializer)?;
if let Ok(smaller_uint) = value.try_into() {
Ok(KeyCode::from_raw_code(smaller_uint))
} else {
Ok(KeyCode::Unknown)
}
}
}
#[cfg_attr(feature = "serialize", derive(serde_repr::Serialize_repr))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum KeyCode {
// That key has no keycode, = 0
// break, = 3
// backspace / delete, = 8
// tab, = 9
// clear, = 12
// enter, = 13
// shift, = 16
// ctrl, = 17
// alt, = 18
// pause/break, = 19
// caps lock, = 20
// hangul, = 21
// hanja, = 25
// escape, = 27
// conversion, = 28
// non-conversion, = 29
// spacebar, = 32
// page up, = 33
// page down, = 34
// end, = 35
// home, = 36
// left arrow, = 37
// up arrow, = 38
// right arrow, = 39
// down arrow, = 40
// select, = 41
// print, = 42
// execute, = 43
// Print Screen, = 44
// insert, = 45
// delete, = 46
// help, = 47
// 0, = 48
// 1, = 49
// 2, = 50
// 3, = 51
// 4, = 52
// 5, = 53
// 6, = 54
// 7, = 55
// 8, = 56
// 9, = 57
// :, = 58
// semicolon (firefox), equals, = 59
// <, = 60
// equals (firefox), = 61
// ß, = 63
// @ (firefox), = 64
// a, = 65
// b, = 66
// c, = 67
// d, = 68
// e, = 69
// f, = 70
// g, = 71
// h, = 72
// i, = 73
// j, = 74
// k, = 75
// l, = 76
// m, = 77
// n, = 78
// o, = 79
// p, = 80
// q, = 81
// r, = 82
// s, = 83
// t, = 84
// u, = 85
// v, = 86
// w, = 87
// x, = 88
// y, = 89
// z, = 90
// Windows Key / Left ⌘ / Chromebook Search key, = 91
// right window key, = 92
// Windows Menu / Right ⌘, = 93
// sleep, = 95
// numpad 0, = 96
// numpad 1, = 97
// numpad 2, = 98
// numpad 3, = 99
// numpad 4, = 100
// numpad 5, = 101
// numpad 6, = 102
// numpad 7, = 103
// numpad 8, = 104
// numpad 9, = 105
// multiply, = 106
// add, = 107
// numpad period (firefox), = 108
// subtract, = 109
// decimal point, = 110
// divide, = 111
// f1, = 112
// f2, = 113
// f3, = 114
// f4, = 115
// f5, = 116
// f6, = 117
// f7, = 118
// f8, = 119
// f9, = 120
// f10, = 121
// f11, = 122
// f12, = 123
// f13, = 124
// f14, = 125
// f15, = 126
// f16, = 127
// f17, = 128
// f18, = 129
// f19, = 130
// f20, = 131
// f21, = 132
// f22, = 133
// f23, = 134
// f24, = 135
// f25, = 136
// f26, = 137
// f27, = 138
// f28, = 139
// f29, = 140
// f30, = 141
// f31, = 142
// f32, = 143
// num lock, = 144
// scroll lock, = 145
// airplane mode, = 151
// ^, = 160
// !, = 161
// ؛ (arabic semicolon), = 162
// #, = 163
// $, = 164
// ù, = 165
// page backward, = 166
// page forward, = 167
// refresh, = 168
// closing paren (AZERTY), = 169
// *, = 170
// ~ + * key, = 171
// home key, = 172
// minus (firefox), mute/unmute, = 173
// decrease volume level, = 174
// increase volume level, = 175
// next, = 176
// previous, = 177
// stop, = 178
// play/pause, = 179
// e-mail, = 180
// mute/unmute (firefox), = 181
// decrease volume level (firefox), = 182
// increase volume level (firefox), = 183
// semi-colon / ñ, = 186
// equal sign, = 187
// comma, = 188
// dash, = 189
// period, = 190
// forward slash / ç, = 191
// grave accent / ñ / æ / ö, = 192
// ?, / or °, = 193
// numpad period (chrome), = 194
// open bracket, = 219
// back slash, = 220
// close bracket / å, = 221
// single quote / ø / ä, = 222
// `, = 223
// left or right ⌘ key (firefox), = 224
// altgr, = 225
// < /git >, left back slash, = 226
// GNOME Compose Key, = 230
// ç, = 231
// XF86Forward, = 233
// XF86Back, = 234
// non-conversion, = 235
// alphanumeric, = 240
// hiragana/katakana, = 242
// half-width/full-width, = 243
// kanji, = 244
// unlock trackpad (Chrome/Edge), = 251
// toggle touchpad, = 255
NA = 0,
Break = 3,
Backspace = 8,
Tab = 9,
Clear = 12,
Enter = 13,
Shift = 16,
Ctrl = 17,
Alt = 18,
Pause = 19,
CapsLock = 20,
// hangul, = 21
// hanja, = 25
Escape = 27,
// conversion, = 28
// non-conversion, = 29
Space = 32,
PageUp = 33,
PageDown = 34,
End = 35,
Home = 36,
LeftArrow = 37,
UpArrow = 38,
RightArrow = 39,
DownArrow = 40,
// select, = 41
// print, = 42
// execute, = 43
// Print Screen, = 44
Insert = 45,
Delete = 46,
// help, = 47
Num0 = 48,
Num1 = 49,
Num2 = 50,
Num3 = 51,
Num4 = 52,
Num5 = 53,
Num6 = 54,
Num7 = 55,
Num8 = 56,
Num9 = 57,
// :, = 58
// semicolon (firefox), equals, = 59
// <, = 60
// equals (firefox), = 61
// ß, = 63
// @ (firefox), = 64
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftWindow = 91,
RightWindow = 92,
SelectKey = 93,
Numpad0 = 96,
Numpad1 = 97,
Numpad2 = 98,
Numpad3 = 99,
Numpad4 = 100,
Numpad5 = 101,
Numpad6 = 102,
Numpad7 = 103,
Numpad8 = 104,
Numpad9 = 105,
Multiply = 106,
Add = 107,
Subtract = 109,
DecimalPoint = 110,
Divide = 111,
F1 = 112,
F2 = 113,
F3 = 114,
F4 = 115,
F5 = 116,
F6 = 117,
F7 = 118,
F8 = 119,
F9 = 120,
F10 = 121,
F11 = 122,
F12 = 123,
// f13, = 124
// f14, = 125
// f15, = 126
// f16, = 127
// f17, = 128
// f18, = 129
// f19, = 130
// f20, = 131
// f21, = 132
// f22, = 133
// f23, = 134
// f24, = 135
// f25, = 136
// f26, = 137
// f27, = 138
// f28, = 139
// f29, = 140
// f30, = 141
// f31, = 142
// f32, = 143
NumLock = 144,
ScrollLock = 145,
// airplane mode, = 151
// ^, = 160
// !, = 161
// ؛ (arabic semicolon), = 162
// #, = 163
// $, = 164
// ù, = 165
// page backward, = 166
// page forward, = 167
// refresh, = 168
// closing paren (AZERTY), = 169
// *, = 170
// ~ + * key, = 171
// home key, = 172
// minus (firefox), mute/unmute, = 173
// decrease volume level, = 174
// increase volume level, = 175
// next, = 176
// previous, = 177
// stop, = 178
// play/pause, = 179
// e-mail, = 180
// mute/unmute (firefox), = 181
// decrease volume level (firefox), = 182
// increase volume level (firefox), = 183
Semicolon = 186,
EqualSign = 187,
Comma = 188,
Dash = 189,
Period = 190,
ForwardSlash = 191,
GraveAccent = 192,
// ?, / or °, = 193
// numpad period (chrome), = 194
OpenBracket = 219,
BackSlash = 220,
CloseBracket = 221,
SingleQuote = 222,
// `, = 223
// left or right ⌘ key (firefox), = 224
// altgr, = 225
// < /git >, left back slash, = 226
// GNOME Compose Key, = 230
// ç, = 231
// XF86Forward, = 233
// XF86Back, = 234
// non-conversion, = 235
// alphanumeric, = 240
// hiragana/katakana, = 242
// half-width/full-width, = 243
// kanji, = 244
// unlock trackpad (Chrome/Edge), = 251
// toggle touchpad, = 255
Unknown,
}
impl KeyCode {
pub fn from_raw_code(i: u8) -> Self {
use KeyCode::*;
match i {
8 => Backspace,
9 => Tab,
13 => Enter,
16 => Shift,
17 => Ctrl,
18 => Alt,
19 => Pause,
20 => CapsLock,
27 => Escape,
33 => PageUp,
34 => PageDown,
35 => End,
36 => Home,
37 => LeftArrow,
38 => UpArrow,
39 => RightArrow,
40 => DownArrow,
45 => Insert,
46 => Delete,
48 => Num0,
49 => Num1,
50 => Num2,
51 => Num3,
52 => Num4,
53 => Num5,
54 => Num6,
55 => Num7,
56 => Num8,
57 => Num9,
65 => A,
66 => B,
67 => C,
68 => D,
69 => E,
70 => F,
71 => G,
72 => H,
73 => I,
74 => J,
75 => K,
76 => L,
77 => M,
78 => N,
79 => O,
80 => P,
81 => Q,
82 => R,
83 => S,
84 => T,
85 => U,
86 => V,
87 => W,
88 => X,
89 => Y,
90 => Z,
91 => LeftWindow,
92 => RightWindow,
93 => SelectKey,
96 => Numpad0,
97 => Numpad1,
98 => Numpad2,
99 => Numpad3,
100 => Numpad4,
101 => Numpad5,
102 => Numpad6,
103 => Numpad7,
104 => Numpad8,
105 => Numpad9,
106 => Multiply,
107 => Add,
109 => Subtract,
110 => DecimalPoint,
111 => Divide,
112 => F1,
113 => F2,
114 => F3,
115 => F4,
116 => F5,
117 => F6,
118 => F7,
119 => F8,
120 => F9,
121 => F10,
122 => F11,
123 => F12,
144 => NumLock,
145 => ScrollLock,
186 => Semicolon,
187 => EqualSign,
188 => Comma,
189 => Dash,
190 => Period,
191 => ForwardSlash,
192 => GraveAccent,
219 => OpenBracket,
220 => BackSlash,
221 => CloseBracket,
222 => SingleQuote,
_ => Unknown,
}
}
// get the raw code
pub fn raw_code(&self) -> u32 {
*self as u32
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/pointer.rs | packages/html/src/events/pointer.rs | use dioxus_core::Event;
use keyboard_types::Modifiers;
use crate::{geometry::*, input_data::*, *};
/// A synthetic event that wraps a web-style [`PointerEvent`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent)
pub type PointerEvent = Event<PointerData>;
pub struct PointerData {
inner: Box<dyn HasPointerData>,
}
impl PointerData {
/// Create a new PointerData
pub fn new(data: impl HasPointerData + 'static) -> Self {
Self::from(data)
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl<E: HasPointerData + 'static> From<E> for PointerData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for PointerData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PointerData")
.field("pointer_id", &self.pointer_id())
.field("width", &self.width())
.field("height", &self.height())
.field("pressure", &self.pressure())
.field("tangential_pressure", &self.tangential_pressure())
.field("tilt_x", &self.tilt_x())
.field("tilt_y", &self.tilt_y())
.field("twist", &self.twist())
.field("pointer_type", &self.pointer_type())
.field("is_primary", &self.is_primary())
.field("coordinates", &self.coordinates())
.field("modifiers", &self.modifiers())
.field("held_buttons", &self.held_buttons())
.field("trigger_button", &self.trigger_button())
.finish()
}
}
impl PartialEq for PointerData {
fn eq(&self, other: &Self) -> bool {
self.pointer_id() == other.pointer_id()
&& self.width() == other.width()
&& self.height() == other.height()
&& self.pressure() == other.pressure()
&& self.tangential_pressure() == other.tangential_pressure()
&& self.tilt_x() == other.tilt_x()
&& self.tilt_y() == other.tilt_y()
&& self.twist() == other.twist()
&& self.pointer_type() == other.pointer_type()
&& self.is_primary() == other.is_primary()
&& self.coordinates() == other.coordinates()
&& self.modifiers() == other.modifiers()
&& self.held_buttons() == other.held_buttons()
&& self.trigger_button() == other.trigger_button()
}
}
/// A trait for any object that has the data for a pointer event
pub trait HasPointerData: PointerInteraction {
/// Gets the unique identifier of the pointer causing the event.
fn pointer_id(&self) -> i32;
/// Gets the width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.
fn width(&self) -> f64;
/// Gets the height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.
fn height(&self) -> f64;
/// Gets the normalized pressure of the pointer input in the range of 0 to 1,
fn pressure(&self) -> f32;
/// Gets the normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range -1 to 1,
fn tangential_pressure(&self) -> f32;
/// Gets the plane angle (in degrees, in the range of -90 to 90) between the Y-Z plane and the plane containing both the transducer (e.g. pen stylus) axis and the Y axis.
fn tilt_x(&self) -> i32;
/// Gets the plane angle (in degrees, in the range of -90 to 90) between the X-Z plane and the plane containing both the transducer (e.g. pen stylus) axis and the X axis.
fn tilt_y(&self) -> i32;
/// Gets the clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359.The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359.
fn twist(&self) -> i32;
/// Gets the device type that caused the event (mouse, pen, touch, etc.).
fn pointer_type(&self) -> String;
/// Gets if the pointer represents the primary pointer of this pointer type.
fn is_primary(&self) -> bool;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
impl_event![
PointerData;
/// pointerdown
onpointerdown
/// pointermove
onpointermove
/// pointerup
onpointerup
/// pointercancel
onpointercancel
/// gotpointercapture
ongotpointercapture
/// lostpointercapture
onlostpointercapture
/// pointerenter
onpointerenter
/// pointerleave
onpointerleave
/// pointerover
onpointerover
/// pointerout
onpointerout
/// auxclick
onauxclick
];
impl PointerData {
/// Gets the unique identifier of the pointer causing the event.
pub fn pointer_id(&self) -> i32 {
self.inner.pointer_id()
}
/// Gets the width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.
pub fn width(&self) -> f64 {
self.inner.width()
}
/// Gets the height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.
pub fn height(&self) -> f64 {
self.inner.height()
}
/// Gets the normalized pressure of the pointer input in the range of 0 to 1,
pub fn pressure(&self) -> f32 {
self.inner.pressure()
}
/// Gets the normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range -1 to 1,
pub fn tangential_pressure(&self) -> f32 {
self.inner.tangential_pressure()
}
/// Gets the plane angle (in degrees, in the range of -90 to 90) between the Y-Z plane and the plane containing both the transducer (e.g. pen stylus) axis and the Y axis.
pub fn tilt_x(&self) -> i32 {
self.inner.tilt_x()
}
/// Gets the plane angle (in degrees, in the range of -90 to 90) between the X-Z plane and the plane containing both the transducer (e.g. pen stylus) axis and the X axis.
pub fn tilt_y(&self) -> i32 {
self.inner.tilt_y()
}
/// Gets the clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359.The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359.
pub fn twist(&self) -> i32 {
self.inner.twist()
}
/// Gets the device type that caused the event (mouse, pen, touch, etc.).
pub fn pointer_type(&self) -> String {
self.inner.pointer_type()
}
/// Gets if the pointer represents the primary pointer of this pointer type.
pub fn is_primary(&self) -> bool {
self.inner.is_primary()
}
}
impl InteractionLocation for PointerData {
fn client_coordinates(&self) -> ClientPoint {
self.inner.client_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.inner.screen_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.inner.page_coordinates()
}
}
impl InteractionElementOffset for PointerData {
fn element_coordinates(&self) -> ElementPoint {
self.inner.element_coordinates()
}
}
impl ModifiersInteraction for PointerData {
fn modifiers(&self) -> Modifiers {
self.inner.modifiers()
}
}
impl PointerInteraction for PointerData {
fn held_buttons(&self) -> MouseButtonSet {
self.inner.held_buttons()
}
fn trigger_button(&self) -> Option<MouseButton> {
self.inner.trigger_button()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of PointerData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedPointerData {
/// Common data for all pointer/mouse events
#[serde(flatten)]
point_data: crate::point_interaction::SerializedPointInteraction,
/// The unique identifier of the pointer causing the event.
pointer_id: i32,
/// The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer.
width: f64,
/// The height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer.
height: f64,
/// The normalized pressure of the pointer input in the range of 0 to 1,
pressure: f32,
/// The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range -1 to 1,
tangential_pressure: f32,
/// The plane angle (in degrees, in the range of -90 to 90) between the Y-Z plane and the plane containing both the transducer (e.g. pen stylus) axis and the Y axis.
tilt_x: i32,
/// The plane angle (in degrees, in the range of -90 to 90) between the X-Z plane and the plane containing both the transducer (e.g. pen stylus) axis and the X axis.
tilt_y: i32,
/// The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359.The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range 0 to 359.
twist: i32,
/// Indicates the device type that caused the event (mouse, pen, touch, etc.).
pointer_type: String,
/// Indicates if the pointer represents the primary pointer of this pointer type.
is_primary: bool,
}
#[cfg(feature = "serialize")]
impl HasPointerData for SerializedPointerData {
fn pointer_id(&self) -> i32 {
self.pointer_id
}
fn width(&self) -> f64 {
self.width
}
fn height(&self) -> f64 {
self.height
}
fn pressure(&self) -> f32 {
self.pressure
}
fn tangential_pressure(&self) -> f32 {
self.tangential_pressure
}
fn tilt_x(&self) -> i32 {
self.tilt_x
}
fn tilt_y(&self) -> i32 {
self.tilt_y
}
fn twist(&self) -> i32 {
self.twist
}
fn pointer_type(&self) -> String {
self.pointer_type.clone()
}
fn is_primary(&self) -> bool {
self.is_primary
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl InteractionLocation for SerializedPointerData {
fn client_coordinates(&self) -> ClientPoint {
self.point_data.client_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.point_data.screen_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.point_data.page_coordinates()
}
}
#[cfg(feature = "serialize")]
impl InteractionElementOffset for SerializedPointerData {
fn element_coordinates(&self) -> ElementPoint {
self.point_data.element_coordinates()
}
}
#[cfg(feature = "serialize")]
impl ModifiersInteraction for SerializedPointerData {
fn modifiers(&self) -> Modifiers {
self.point_data.modifiers()
}
}
#[cfg(feature = "serialize")]
impl PointerInteraction for SerializedPointerData {
fn held_buttons(&self) -> MouseButtonSet {
self.point_data.held_buttons()
}
fn trigger_button(&self) -> Option<MouseButton> {
self.point_data.trigger_button()
}
}
#[cfg(feature = "serialize")]
impl From<&PointerData> for SerializedPointerData {
fn from(data: &PointerData) -> Self {
Self {
point_data: data.into(),
pointer_id: data.pointer_id(),
width: data.width(),
height: data.height(),
pressure: data.pressure(),
tangential_pressure: data.tangential_pressure(),
tilt_x: data.tilt_x(),
tilt_y: data.tilt_y(),
twist: data.twist(),
pointer_type: data.pointer_type().to_string(),
is_primary: data.is_primary(),
}
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for PointerData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedPointerData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for PointerData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedPointerData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/visible.rs | packages/html/src/events/visible.rs | use std::{
fmt::{Display, Formatter},
time::SystemTime,
};
pub struct VisibleData {
inner: Box<dyn HasVisibleData>,
}
impl<E: HasVisibleData> From<E> for VisibleData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl VisibleData {
/// Create a new VisibleData
pub fn new(inner: impl HasVisibleData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Get the bounds rectangle of the target element
pub fn get_bounding_client_rect(&self) -> VisibleResult<PixelsRect> {
self.inner.get_bounding_client_rect()
}
/// Get the ratio of the intersectionRect to the boundingClientRect
pub fn get_intersection_ratio(&self) -> VisibleResult<f64> {
self.inner.get_intersection_ratio()
}
/// Get the rect representing the target's visible area
pub fn get_intersection_rect(&self) -> VisibleResult<PixelsRect> {
self.inner.get_intersection_rect()
}
/// Get if the target element intersects with the intersection observer's root
pub fn is_intersecting(&self) -> VisibleResult<bool> {
self.inner.is_intersecting()
}
/// Get the rect for the intersection observer's root
pub fn get_root_bounds(&self) -> VisibleResult<PixelsRect> {
self.inner.get_root_bounds()
}
/// Get a timestamp indicating the time at which the intersection was recorded
pub fn get_time(&self) -> VisibleResult<SystemTime> {
self.inner.get_time()
}
/// Downcast this event to a concrete event type
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl std::fmt::Debug for VisibleData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VisibleData")
.field(
"bounding_client_rect",
&self.inner.get_bounding_client_rect(),
)
.field("intersection_ratio", &self.inner.get_intersection_ratio())
.field("intersection_rect", &self.inner.get_intersection_rect())
.field("is_intersecting", &self.inner.is_intersecting())
.field("root_bounds", &self.inner.get_root_bounds())
.field("time", &self.inner.get_time())
.finish()
}
}
impl PartialEq for VisibleData {
fn eq(&self, _: &Self) -> bool {
true
}
}
#[cfg(feature = "serialize")]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct DOMRect {
bottom: f64, // The bottom coordinate value of the DOMRect (usually the same as y + height)
height: f64, // The height of the DOMRect
left: f64, // The left coordinate value of the DOMRect (usually the same as x)
right: f64, // The right coordinate value of the DOMRect (usually the same as x + width)
top: f64, // The top coordinate value of the DOMRect (usually the same as y)
width: f64, // The width of the DOMRect
x: f64, // The x coordinate of the DOMRect's origin
y: f64, // The y coordinate of the DOMRect's origin
}
#[cfg(feature = "serialize")]
impl From<PixelsRect> for DOMRect {
fn from(rect: PixelsRect) -> Self {
let x = rect.origin.x;
let y = rect.origin.y;
let height = rect.height();
let width = rect.width();
Self {
bottom: y + height,
height,
left: x,
right: x + width,
top: y,
width,
x,
y,
}
}
}
#[cfg(feature = "serialize")]
impl From<&DOMRect> for PixelsRect {
fn from(rect: &DOMRect) -> Self {
PixelsRect::new(
euclid::Point2D::new(rect.x, rect.y),
euclid::Size2D::new(rect.width, rect.height),
)
}
}
#[cfg(feature = "serialize")]
/// A serialized version of VisibleData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedVisibleData {
pub bounding_client_rect: DOMRect,
pub intersection_ratio: f64,
pub intersection_rect: DOMRect,
pub is_intersecting: bool,
pub root_bounds: DOMRect,
pub time_ms: u128,
}
#[cfg(feature = "serialize")]
impl SerializedVisibleData {
/// Create a new SerializedVisibleData
pub fn new(
bounding_client_rect: DOMRect,
intersection_ratio: f64,
intersection_rect: DOMRect,
is_intersecting: bool,
root_bounds: DOMRect,
time_ms: u128,
) -> Self {
Self {
bounding_client_rect,
intersection_ratio,
intersection_rect,
is_intersecting,
root_bounds,
time_ms,
}
}
}
#[cfg(feature = "serialize")]
impl From<&VisibleData> for SerializedVisibleData {
fn from(data: &VisibleData) -> Self {
Self::new(
data.get_bounding_client_rect().unwrap().into(),
data.get_intersection_ratio().unwrap(),
data.get_intersection_rect().unwrap().into(),
data.is_intersecting().unwrap(),
data.get_root_bounds().unwrap().into(),
data.get_time().unwrap().elapsed().unwrap().as_millis(),
)
}
}
#[cfg(feature = "serialize")]
impl HasVisibleData for SerializedVisibleData {
/// Get the bounds rectangle of the target element
fn get_bounding_client_rect(&self) -> VisibleResult<PixelsRect> {
Ok((&self.bounding_client_rect).into())
}
/// Get the ratio of the intersectionRect to the boundingClientRect
fn get_intersection_ratio(&self) -> VisibleResult<f64> {
Ok(self.intersection_ratio)
}
/// Get the rect representing the target's visible area
fn get_intersection_rect(&self) -> VisibleResult<PixelsRect> {
Ok((&self.intersection_rect).into())
}
/// Get if the target element intersects with the intersection observer's root
fn is_intersecting(&self) -> VisibleResult<bool> {
Ok(self.is_intersecting)
}
/// Get the rect for the intersection observer's root
fn get_root_bounds(&self) -> VisibleResult<PixelsRect> {
Ok((&self.root_bounds).into())
}
/// Get a timestamp indicating the time at which the intersection was recorded
fn get_time(&self) -> VisibleResult<SystemTime> {
Ok(SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(self.time_ms as u64))
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for VisibleData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedVisibleData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for VisibleData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedVisibleData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasVisibleData: std::any::Any {
/// Get the bounds rectangle of the target element
fn get_bounding_client_rect(&self) -> VisibleResult<PixelsRect> {
Err(VisibleError::NotSupported)
}
/// Get the ratio of the intersectionRect to the boundingClientRect
fn get_intersection_ratio(&self) -> VisibleResult<f64> {
Err(VisibleError::NotSupported)
}
/// Get the rect representing the target's visible area
fn get_intersection_rect(&self) -> VisibleResult<PixelsRect> {
Err(VisibleError::NotSupported)
}
/// Get if the target element intersects with the intersection observer's root
fn is_intersecting(&self) -> VisibleResult<bool> {
Err(VisibleError::NotSupported)
}
/// Get the rect for the intersection observer's root
fn get_root_bounds(&self) -> VisibleResult<PixelsRect> {
Err(VisibleError::NotSupported)
}
/// Get a timestamp indicating the time at which the intersection was recorded
fn get_time(&self) -> VisibleResult<SystemTime> {
Err(VisibleError::NotSupported)
}
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
use dioxus_core::Event;
use crate::geometry::PixelsRect;
pub type VisibleEvent = Event<VisibleData>;
impl_event! {
VisibleData;
/// onvisible
onvisible
}
/// The VisibleResult type for the VisibleData
pub type VisibleResult<T> = Result<T, VisibleError>;
#[derive(Debug)]
/// The error type for the VisibleData
#[non_exhaustive]
pub enum VisibleError {
/// The renderer does not support the requested operation
NotSupported,
/// The element was not found
OperationFailed(Box<dyn std::error::Error>),
/// The target element had no associated ElementId
NoElementId,
}
impl Display for VisibleError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
VisibleError::NotSupported => {
write!(f, "The renderer does not support the requested operation")
}
VisibleError::OperationFailed(e) => {
write!(f, "The operation failed: {}", e)
}
VisibleError::NoElementId => {
write!(f, "The target had no associated ElementId")
}
}
}
}
impl std::error::Error for VisibleError {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/resize.rs | packages/html/src/events/resize.rs | use std::fmt::{Display, Formatter};
pub struct ResizeData {
inner: Box<dyn HasResizeData>,
}
impl<E: HasResizeData> From<E> for ResizeData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl ResizeData {
/// Create a new ResizeData
pub fn new(inner: impl HasResizeData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Get the border box size of the observed element
pub fn get_border_box_size(&self) -> ResizeResult<PixelsSize> {
self.inner.get_border_box_size()
}
/// Get the content box size of the observed element
pub fn get_content_box_size(&self) -> ResizeResult<PixelsSize> {
self.inner.get_content_box_size()
}
/// Downcast this event to a concrete event type
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl std::fmt::Debug for ResizeData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResizeData")
.field("border_box_size", &self.inner.get_border_box_size())
.field("content_box_size", &self.inner.get_content_box_size())
.finish()
}
}
impl PartialEq for ResizeData {
fn eq(&self, _: &Self) -> bool {
true
}
}
#[cfg(feature = "serialize")]
/// A serialized version of ResizeData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedResizeData {
pub border_box_size: PixelsSize,
pub content_box_size: PixelsSize,
}
#[cfg(feature = "serialize")]
impl SerializedResizeData {
/// Create a new SerializedResizeData
pub fn new(border_box_size: PixelsSize, content_box_size: PixelsSize) -> Self {
Self {
border_box_size,
content_box_size,
}
}
}
#[cfg(feature = "serialize")]
impl From<&ResizeData> for SerializedResizeData {
fn from(data: &ResizeData) -> Self {
Self::new(
data.get_border_box_size().unwrap(),
data.get_content_box_size().unwrap(),
)
}
}
#[cfg(feature = "serialize")]
impl HasResizeData for SerializedResizeData {
/// Get the border box size of the observed element
fn get_border_box_size(&self) -> ResizeResult<PixelsSize> {
Ok(self.border_box_size)
}
/// Get the content box size of the observed element
fn get_content_box_size(&self) -> ResizeResult<PixelsSize> {
Ok(self.content_box_size)
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for ResizeData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedResizeData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for ResizeData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedResizeData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasResizeData: std::any::Any {
/// Get the border box size of the observed element
fn get_border_box_size(&self) -> ResizeResult<PixelsSize> {
Err(ResizeError::NotSupported)
}
/// Get the content box size of the observed element
fn get_content_box_size(&self) -> ResizeResult<PixelsSize> {
Err(ResizeError::NotSupported)
}
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
use dioxus_core::Event;
use crate::geometry::PixelsSize;
pub type ResizeEvent = Event<ResizeData>;
impl_event! {
ResizeData;
/// onresize
onresize
}
/// The ResizeResult type for the ResizeData
pub type ResizeResult<T> = Result<T, ResizeError>;
#[derive(Debug)]
/// The error type for the MountedData
#[non_exhaustive]
pub enum ResizeError {
/// The renderer does not support the requested operation
NotSupported,
/// The element was not found
OperationFailed(Box<dyn std::error::Error>),
}
impl Display for ResizeError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ResizeError::NotSupported => {
write!(f, "The renderer does not support the requested operation")
}
ResizeError::OperationFailed(e) => {
write!(f, "The operation failed: {}", e)
}
}
}
}
impl std::error::Error for ResizeError {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/html/src/events/touch.rs | packages/html/src/events/touch.rs | use dioxus_core::Event;
use keyboard_types::Modifiers;
use crate::geometry::*;
use crate::{InteractionLocation, ModifiersInteraction};
pub type TouchEvent = Event<TouchData>;
pub struct TouchData {
inner: Box<dyn HasTouchData>,
}
impl<E: HasTouchData> From<E> for TouchData {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl std::fmt::Debug for TouchData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TouchData")
.field("modifiers", &self.modifiers())
.field("touches", &self.touches())
.field("touches_changed", &self.touches_changed())
.field("target_touches", &self.target_touches())
.finish()
}
}
impl PartialEq for TouchData {
fn eq(&self, other: &Self) -> bool {
self.modifiers() == other.modifiers()
}
}
impl TouchData {
/// Create a new TouchData
pub fn new(inner: impl HasTouchData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// Get the pointers that are currently down
pub fn touches(&self) -> Vec<TouchPoint> {
self.inner.touches()
}
/// Get the touches that have changed since the last event
pub fn touches_changed(&self) -> Vec<TouchPoint> {
self.inner.touches_changed()
}
/// Get the touches that started and stayed on the element that triggered this event
pub fn target_touches(&self) -> Vec<TouchPoint> {
self.inner.target_touches()
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl ModifiersInteraction for TouchData {
fn modifiers(&self) -> Modifiers {
self.inner.modifiers()
}
}
#[cfg(feature = "serialize")]
/// A serialized version of TouchData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedTouchData {
alt_key: bool,
ctrl_key: bool,
meta_key: bool,
shift_key: bool,
touches: Vec<SerializedTouchPoint>,
changed_touches: Vec<SerializedTouchPoint>,
target_touches: Vec<SerializedTouchPoint>,
}
#[cfg(feature = "serialize")]
impl From<&TouchData> for SerializedTouchData {
fn from(data: &TouchData) -> Self {
let modifiers = data.modifiers();
Self {
alt_key: modifiers.contains(Modifiers::ALT),
ctrl_key: modifiers.contains(Modifiers::CONTROL),
meta_key: modifiers.contains(Modifiers::META),
shift_key: modifiers.contains(Modifiers::SHIFT),
touches: data.touches().iter().map(|t| t.into()).collect(),
changed_touches: data.touches_changed().iter().map(|t| t.into()).collect(),
target_touches: data.target_touches().iter().map(|t| t.into()).collect(),
}
}
}
#[cfg(feature = "serialize")]
impl ModifiersInteraction for SerializedTouchData {
fn modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::default();
if self.alt_key {
modifiers.insert(Modifiers::ALT);
}
if self.ctrl_key {
modifiers.insert(Modifiers::CONTROL);
}
if self.meta_key {
modifiers.insert(Modifiers::META);
}
if self.shift_key {
modifiers.insert(Modifiers::SHIFT);
}
modifiers
}
}
#[cfg(feature = "serialize")]
impl HasTouchData for SerializedTouchData {
fn touches(&self) -> Vec<TouchPoint> {
self.touches.clone().into_iter().map(Into::into).collect()
}
fn touches_changed(&self) -> Vec<TouchPoint> {
self.changed_touches
.clone()
.into_iter()
.map(Into::into)
.collect()
}
fn target_touches(&self) -> Vec<TouchPoint> {
self.target_touches
.clone()
.into_iter()
.map(Into::into)
.collect()
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for TouchData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SerializedTouchData::from(self).serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for TouchData {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let data = SerializedTouchData::deserialize(deserializer)?;
Ok(Self {
inner: Box::new(data),
})
}
}
pub trait HasTouchData: ModifiersInteraction + std::any::Any {
/// Get the touches that are currently down
fn touches(&self) -> Vec<TouchPoint>;
/// Get the touches that have changed since the last event
fn touches_changed(&self) -> Vec<TouchPoint>;
/// Get the touches that started and stayed on the element that triggered this event
fn target_touches(&self) -> Vec<TouchPoint>;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
pub struct TouchPoint {
inner: Box<dyn HasTouchPointData>,
}
impl<E: HasTouchPointData> From<E> for TouchPoint {
fn from(e: E) -> Self {
Self { inner: Box::new(e) }
}
}
impl TouchPoint {
/// Create a new TouchPoint
pub fn new(inner: impl HasTouchPointData + 'static) -> Self {
Self {
inner: Box::new(inner),
}
}
/// A unique identifier for this touch point that will be the same for the duration of the touch
fn identifier(&self) -> i32 {
self.inner.identifier()
}
/// the pressure of the touch
fn force(&self) -> f64 {
self.inner.force()
}
/// the radius of the touch
fn radius(&self) -> ScreenPoint {
self.inner.radius()
}
/// the rotation of the touch in degrees between 0 and 90
fn rotation(&self) -> f64 {
self.inner.rotation()
}
/// Downcast this event to a concrete event type
#[inline(always)]
pub fn downcast<T: 'static>(&self) -> Option<&T> {
self.inner.as_any().downcast_ref::<T>()
}
}
impl std::fmt::Debug for TouchPoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TouchPoint")
.field("client_coordinates", &self.client_coordinates())
.field("page_coordinates", &self.page_coordinates())
.field("screen_coordinates", &self.screen_coordinates())
.field("identifier", &self.identifier())
.field("force", &self.force())
.field("radius", &self.radius())
.field("rotation", &self.rotation())
.finish()
}
}
impl InteractionLocation for TouchPoint {
fn client_coordinates(&self) -> ClientPoint {
self.inner.client_coordinates()
}
fn page_coordinates(&self) -> PagePoint {
self.inner.page_coordinates()
}
fn screen_coordinates(&self) -> ScreenPoint {
self.inner.screen_coordinates()
}
}
/// A trait for touch point data
pub trait HasTouchPointData: InteractionLocation + std::any::Any {
/// A unique identifier for this touch point that will be the same for the duration of the touch
fn identifier(&self) -> i32;
/// the pressure of the touch
fn force(&self) -> f64;
/// the radius of the touch
fn radius(&self) -> ScreenPoint;
/// the rotation of the touch in degrees between 0 and 90
fn rotation(&self) -> f64;
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any;
}
#[cfg(feature = "serialize")]
/// A serialized version of TouchPoint
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
struct SerializedTouchPoint {
identifier: i32,
client_x: f64,
client_y: f64,
page_x: f64,
page_y: f64,
screen_x: f64,
screen_y: f64,
force: f64,
radius_x: f64,
radius_y: f64,
rotation_angle: f64,
}
#[cfg(feature = "serialize")]
impl From<&TouchPoint> for SerializedTouchPoint {
fn from(point: &TouchPoint) -> Self {
let client_coordinates = point.client_coordinates();
let page_coordinates = point.page_coordinates();
let screen_coordinates = point.screen_coordinates();
Self {
identifier: point.identifier(),
client_x: client_coordinates.x,
client_y: client_coordinates.y,
page_x: page_coordinates.x,
page_y: page_coordinates.y,
screen_x: screen_coordinates.x,
screen_y: screen_coordinates.y,
force: point.force(),
radius_x: point.radius().x,
radius_y: point.radius().y,
rotation_angle: point.rotation(),
}
}
}
#[cfg(feature = "serialize")]
impl HasTouchPointData for SerializedTouchPoint {
/// A unique identifier for this touch point that will be the same for the duration of the touch
fn identifier(&self) -> i32 {
self.identifier
}
/// the pressure of the touch
fn force(&self) -> f64 {
self.force
}
/// the radius of the touch
fn radius(&self) -> ScreenPoint {
ScreenPoint::new(self.radius_x, self.radius_y)
}
/// the rotation of the touch in degrees between 0 and 90
fn rotation(&self) -> f64 {
self.rotation_angle
}
/// return self as Any
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
#[cfg(feature = "serialize")]
impl InteractionLocation for SerializedTouchPoint {
/// Gets the coordinates of the event relative to the browser viewport.
fn client_coordinates(&self) -> ClientPoint {
ClientPoint::new(self.client_x, self.client_y)
}
/// Gets the coordinates of the event relative to the screen.
fn screen_coordinates(&self) -> ScreenPoint {
ScreenPoint::new(self.screen_x, self.screen_y)
}
/// Gets the coordinates of the event relative to the page.
fn page_coordinates(&self) -> PagePoint {
PagePoint::new(self.page_x, self.page_y)
}
}
impl_event! {
TouchData;
/// touchstart
ontouchstart
/// touchmove
ontouchmove
/// touchend
ontouchend
/// touchcancel
ontouchcancel
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/check/src/issues.rs | packages/check/src/issues.rs | use owo_colors::{
colors::{css::LightBlue, BrightRed},
OwoColorize, Stream,
};
use std::{
fmt::Display,
path::{Path, PathBuf},
};
use crate::metadata::{
AnyLoopInfo, AsyncInfo, ClosureInfo, ConditionalInfo, ForInfo, HookInfo, IfInfo, MatchInfo,
WhileInfo,
};
/// The result of checking a Dioxus file for issues.
pub struct IssueReport {
pub path: PathBuf,
pub crate_root: PathBuf,
pub file_content: String,
pub issues: Vec<Issue>,
}
impl IssueReport {
pub fn new<S: ToString>(
path: PathBuf,
crate_root: PathBuf,
file_content: S,
issues: Vec<Issue>,
) -> Self {
Self {
path,
crate_root,
file_content: file_content.to_string(),
issues,
}
}
}
fn lightblue(text: &str) -> String {
text.if_supports_color(Stream::Stderr, |text| text.fg::<LightBlue>())
.to_string()
}
fn brightred(text: &str) -> String {
text.if_supports_color(Stream::Stderr, |text| text.fg::<BrightRed>())
.to_string()
}
fn bold(text: &str) -> String {
text.if_supports_color(Stream::Stderr, |text| text.bold())
.to_string()
}
impl Display for IssueReport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let relative_file = Path::new(&self.path)
.strip_prefix(&self.crate_root)
.unwrap_or(Path::new(&self.path))
.display();
let pipe_char = lightblue("|");
for (i, issue) in self.issues.iter().enumerate() {
let hook_info = issue.hook_info();
let hook_span = hook_info.span;
let hook_name_span = hook_info.name_span;
let error_line = format!("{}: {}", brightred("error"), issue);
writeln!(f, "{}", bold(&error_line))?;
writeln!(
f,
" {} {}:{}:{}",
lightblue("-->"),
relative_file,
hook_span.start.line,
hook_span.start.column + 1
)?;
let max_line_num_len = hook_span.end.line.to_string().len();
writeln!(f, "{:>max_line_num_len$} {}", "", pipe_char)?;
for (i, line) in self.file_content.lines().enumerate() {
let line_num = i + 1;
if line_num >= hook_span.start.line && line_num <= hook_span.end.line {
writeln!(
f,
"{:>max_line_num_len$} {} {}",
lightblue(&line_num.to_string()),
pipe_char,
line,
)?;
if line_num == hook_span.start.line {
let mut caret = String::new();
for _ in 0..hook_name_span.start.column {
caret.push(' ');
}
for _ in hook_name_span.start.column..hook_name_span.end.column {
caret.push('^');
}
writeln!(
f,
"{:>max_line_num_len$} {} {}",
"",
pipe_char,
brightred(&caret),
)?;
}
}
}
let note_text_prefix = format!(
"{:>max_line_num_len$} {}\n{:>max_line_num_len$} {} note:",
"",
pipe_char,
"",
lightblue("=")
);
match issue {
Issue::HookInsideConditional(
_,
ConditionalInfo::If(IfInfo { span: _, head_span }),
)
| Issue::HookInsideConditional(
_,
ConditionalInfo::Match(MatchInfo { span: _, head_span }),
) => {
if let Some(source_text) = &head_span.source_text {
writeln!(
f,
"{} `{} {{ … }}` is the conditional",
note_text_prefix, source_text,
)?;
}
}
Issue::HookInsideLoop(_, AnyLoopInfo::For(ForInfo { span: _, head_span }))
| Issue::HookInsideLoop(_, AnyLoopInfo::While(WhileInfo { span: _, head_span })) => {
if let Some(source_text) = &head_span.source_text {
writeln!(
f,
"{} `{} {{ … }}` is the loop",
note_text_prefix, source_text,
)?;
}
}
Issue::HookInsideLoop(_, AnyLoopInfo::Loop(_)) => {
writeln!(f, "{} `loop {{ … }}` is the loop", note_text_prefix,)?;
}
Issue::HookOutsideComponent(_)
| Issue::HookInsideClosure(_, _)
| Issue::HookInsideAsync(_, _) => {}
}
if i < self.issues.len() - 1 {
writeln!(f)?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
#[allow(clippy::enum_variant_names)] // we'll add non-hook ones in the future
/// Issues that might be found via static analysis of a Dioxus file.
pub enum Issue {
/// <https://dioxuslabs.com/learn/0.7/reference/hooks#no-hooks-in-conditionals>
HookInsideConditional(HookInfo, ConditionalInfo),
/// <https://dioxuslabs.com/learn/0.7/reference/hooks#no-hooks-in-loops>
HookInsideLoop(HookInfo, AnyLoopInfo),
/// <https://dioxuslabs.com/learn/0.7/reference/hooks#no-hooks-in-closures>
HookInsideClosure(HookInfo, ClosureInfo),
HookInsideAsync(HookInfo, AsyncInfo),
HookOutsideComponent(HookInfo),
}
impl Issue {
pub fn hook_info(&self) -> HookInfo {
match self {
Issue::HookInsideConditional(hook_info, _)
| Issue::HookInsideLoop(hook_info, _)
| Issue::HookInsideClosure(hook_info, _)
| Issue::HookInsideAsync(hook_info, _)
| Issue::HookOutsideComponent(hook_info) => hook_info.clone(),
}
}
}
impl std::fmt::Display for Issue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Issue::HookInsideConditional(hook_info, conditional_info) => {
write!(
f,
"hook called conditionally: `{}` (inside `{}`)",
hook_info.name,
match conditional_info {
ConditionalInfo::If(_) => "if",
ConditionalInfo::Match(_) => "match",
}
)
}
Issue::HookInsideLoop(hook_info, loop_info) => {
write!(
f,
"hook called in a loop: `{}` (inside {})",
hook_info.name,
match loop_info {
AnyLoopInfo::For(_) => "`for` loop",
AnyLoopInfo::While(_) => "`while` loop",
AnyLoopInfo::Loop(_) => "`loop`",
}
)
}
Issue::HookInsideClosure(hook_info, _) => {
write!(f, "hook called in a closure: `{}`", hook_info.name)
}
Issue::HookInsideAsync(hook_info, _) => {
write!(f, "hook called in an async block: `{}`", hook_info.name)
}
Issue::HookOutsideComponent(hook_info) => {
write!(
f,
"hook called outside component or hook: `{}`",
hook_info.name
)
}
}
}
}
#[cfg(test)]
mod tests {
use crate::check_file;
use indoc::indoc;
use pretty_assertions::assert_eq;
#[test]
fn test_issue_report_display_conditional_if() {
owo_colors::set_override(false);
let issue_report = check_file(
"src/main.rs".into(),
indoc! {r#"
fn App() -> Element {
if you_are_happy && you_know_it {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
}
"#},
);
let expected = indoc! {r#"
error: hook called conditionally: `use_signal` (inside `if`)
--> src/main.rs:3:25
|
3 | let something = use_signal(|| "hands");
| ^^^^^^^^^^
|
= note: `if you_are_happy && you_know_it { … }` is the conditional
"#};
assert_eq!(expected, issue_report.to_string());
}
#[test]
fn test_issue_report_display_conditional_match() {
owo_colors::set_override(false);
let issue_report = check_file(
"src/main.rs".into(),
indoc! {r#"
fn App() -> Element {
match you_are_happy && you_know_it {
true => {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
_ => {}
}
}
"#},
);
let expected = indoc! {r#"
error: hook called conditionally: `use_signal` (inside `match`)
--> src/main.rs:4:29
|
4 | let something = use_signal(|| "hands");
| ^^^^^^^^^^
|
= note: `match you_are_happy && you_know_it { … }` is the conditional
"#};
assert_eq!(expected, issue_report.to_string());
}
#[test]
fn test_issue_report_display_for_loop() {
owo_colors::set_override(false);
let issue_report = check_file(
"src/main.rs".into(),
indoc! {r#"
fn App() -> Element {
for i in 0..10 {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
}
"#},
);
let expected = indoc! {r#"
error: hook called in a loop: `use_signal` (inside `for` loop)
--> src/main.rs:3:25
|
3 | let something = use_signal(|| "hands");
| ^^^^^^^^^^
|
= note: `for i in 0..10 { … }` is the loop
"#};
assert_eq!(expected, issue_report.to_string());
}
#[test]
fn test_issue_report_display_while_loop() {
owo_colors::set_override(false);
let issue_report = check_file(
"src/main.rs".into(),
indoc! {r#"
fn App() -> Element {
while check_thing() {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
}
"#},
);
let expected = indoc! {r#"
error: hook called in a loop: `use_signal` (inside `while` loop)
--> src/main.rs:3:25
|
3 | let something = use_signal(|| "hands");
| ^^^^^^^^^^
|
= note: `while check_thing() { … }` is the loop
"#};
assert_eq!(expected, issue_report.to_string());
}
#[test]
fn test_issue_report_display_loop() {
owo_colors::set_override(false);
let issue_report = check_file(
"src/main.rs".into(),
indoc! {r#"
fn App() -> Element {
loop {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
}
"#},
);
let expected = indoc! {r#"
error: hook called in a loop: `use_signal` (inside `loop`)
--> src/main.rs:3:25
|
3 | let something = use_signal(|| "hands");
| ^^^^^^^^^^
|
= note: `loop { … }` is the loop
"#};
assert_eq!(expected, issue_report.to_string());
}
#[test]
fn test_issue_report_display_closure() {
owo_colors::set_override(false);
let issue_report = check_file(
"src/main.rs".into(),
indoc! {r#"
fn App() -> Element {
let something = || {
let something = use_signal(|| "hands");
println!("clap your {something}")
};
}
"#},
);
let expected = indoc! {r#"
error: hook called in a closure: `use_signal`
--> src/main.rs:3:25
|
3 | let something = use_signal(|| "hands");
| ^^^^^^^^^^
"#};
assert_eq!(expected, issue_report.to_string());
}
#[test]
fn test_issue_report_display_multiline_hook() {
owo_colors::set_override(false);
let issue_report = check_file(
"src/main.rs".into(),
indoc! {r#"
fn App() -> Element {
if you_are_happy && you_know_it {
let something = use_signal(|| {
"hands"
});
println!("clap your {something}")
}
}
"#},
);
let expected = indoc! {r#"
error: hook called conditionally: `use_signal` (inside `if`)
--> src/main.rs:3:25
|
3 | let something = use_signal(|| {
| ^^^^^^^^^^
4 | "hands"
5 | });
|
= note: `if you_are_happy && you_know_it { … }` is the conditional
"#};
assert_eq!(expected, issue_report.to_string());
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/check/src/lib.rs | packages/check/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")]
mod check;
mod issues;
mod metadata;
pub use check::check_file;
pub use issues::{Issue, IssueReport};
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/check/src/check.rs | packages/check/src/check.rs | use std::path::PathBuf;
use syn::{spanned::Spanned, visit::Visit, Pat};
use crate::{
issues::{Issue, IssueReport},
metadata::{
AnyLoopInfo, AsyncInfo, ClosureInfo, ComponentInfo, ConditionalInfo, FnInfo, ForInfo,
HookInfo, IfInfo, LoopInfo, MatchInfo, Span, WhileInfo,
},
};
struct VisitHooks {
issues: Vec<Issue>,
context: Vec<Node>,
}
impl VisitHooks {
const fn new() -> Self {
Self {
issues: vec![],
context: vec![],
}
}
}
/// Checks a Dioxus file for issues.
pub fn check_file(path: PathBuf, file_content: &str) -> IssueReport {
let file = syn::parse_file(file_content).unwrap();
let mut visit_hooks = VisitHooks::new();
visit_hooks.visit_file(&file);
IssueReport::new(
path,
std::env::current_dir().unwrap_or_default(),
file_content.to_string(),
visit_hooks.issues,
)
}
#[allow(unused)]
#[derive(Debug, Clone)]
enum Node {
If(IfInfo),
Match(MatchInfo),
For(ForInfo),
While(WhileInfo),
Loop(LoopInfo),
Closure(ClosureInfo),
Async(AsyncInfo),
ComponentFn(ComponentInfo),
HookFn(HookInfo),
OtherFn(FnInfo),
}
fn returns_element(ty: &syn::ReturnType) -> bool {
match ty {
syn::ReturnType::Default => false,
syn::ReturnType::Type(_, ref ty) => {
if let syn::Type::Path(ref path) = **ty {
if let Some(segment) = path.path.segments.last() {
if segment.ident == "Element" {
return true;
}
}
}
false
}
}
}
fn is_hook_ident(ident: &syn::Ident) -> bool {
ident.to_string().starts_with("use_")
}
fn is_component_fn(item_fn: &syn::ItemFn) -> bool {
returns_element(&item_fn.sig.output)
}
fn get_closure_hook_body(local: &syn::Local) -> Option<&syn::Expr> {
if let Pat::Ident(ident) = &local.pat {
if is_hook_ident(&ident.ident) {
if let Some(init) = &local.init {
if let syn::Expr::Closure(closure) = init.expr.as_ref() {
return Some(&closure.body);
}
}
}
}
None
}
fn fn_name_and_name_span(item_fn: &syn::ItemFn) -> (String, Span) {
let name = item_fn.sig.ident.to_string();
let name_span = item_fn.sig.ident.span().into();
(name, name_span)
}
impl<'ast> syn::visit::Visit<'ast> for VisitHooks {
fn visit_expr_call(&mut self, i: &'ast syn::ExprCall) {
if let syn::Expr::Path(ref path) = *i.func {
if let Some(segment) = path.path.segments.last() {
if is_hook_ident(&segment.ident) {
let hook_info = HookInfo::new(
i.span().into(),
segment.ident.span().into(),
segment.ident.to_string(),
);
let mut container_fn: Option<Node> = None;
for node in self.context.iter().rev() {
match &node {
Node::If(if_info) => {
let issue = Issue::HookInsideConditional(
hook_info.clone(),
ConditionalInfo::If(if_info.clone()),
);
self.issues.push(issue);
}
Node::Match(match_info) => {
let issue = Issue::HookInsideConditional(
hook_info.clone(),
ConditionalInfo::Match(match_info.clone()),
);
self.issues.push(issue);
}
Node::For(for_info) => {
let issue = Issue::HookInsideLoop(
hook_info.clone(),
AnyLoopInfo::For(for_info.clone()),
);
self.issues.push(issue);
}
Node::While(while_info) => {
let issue = Issue::HookInsideLoop(
hook_info.clone(),
AnyLoopInfo::While(while_info.clone()),
);
self.issues.push(issue);
}
Node::Loop(loop_info) => {
let issue = Issue::HookInsideLoop(
hook_info.clone(),
AnyLoopInfo::Loop(loop_info.clone()),
);
self.issues.push(issue);
}
Node::Closure(closure_info) => {
let issue = Issue::HookInsideClosure(
hook_info.clone(),
closure_info.clone(),
);
self.issues.push(issue);
}
Node::Async(async_info) => {
let issue =
Issue::HookInsideAsync(hook_info.clone(), async_info.clone());
self.issues.push(issue);
}
Node::ComponentFn(_) | Node::HookFn(_) | Node::OtherFn(_) => {
container_fn = Some(node.clone());
break;
}
}
}
if let Some(Node::OtherFn(_)) = container_fn {
let issue = Issue::HookOutsideComponent(hook_info);
self.issues.push(issue);
}
}
}
}
syn::visit::visit_expr_call(self, i);
}
fn visit_item_fn(&mut self, i: &'ast syn::ItemFn) {
let (name, name_span) = fn_name_and_name_span(i);
if is_component_fn(i) {
self.context.push(Node::ComponentFn(ComponentInfo::new(
i.span().into(),
name,
name_span,
)));
} else if is_hook_ident(&i.sig.ident) {
self.context.push(Node::HookFn(HookInfo::new(
i.span().into(),
i.sig.ident.span().into(),
name,
)));
} else {
self.context
.push(Node::OtherFn(FnInfo::new(i.span().into(), name, name_span)));
}
syn::visit::visit_item_fn(self, i);
self.context.pop();
}
fn visit_local(&mut self, i: &'ast syn::Local) {
if let Some(body) = get_closure_hook_body(i) {
// if the closure is a hook, we only visit the body of the closure.
// this prevents adding a ClosureInfo node to the context
syn::visit::visit_expr(self, body);
} else {
// otherwise visit the whole local
syn::visit::visit_local(self, i);
}
}
fn visit_expr_if(&mut self, i: &'ast syn::ExprIf) {
self.context.push(Node::If(IfInfo::new(
i.span().into(),
i.if_token
.span()
.join(i.cond.span())
.unwrap_or_else(|| i.span())
.into(),
)));
// only visit the body and else branch, calling hooks inside the expression is not conditional
self.visit_block(&i.then_branch);
if let Some(it) = &i.else_branch {
self.visit_expr(&(it).1);
}
self.context.pop();
}
fn visit_expr_match(&mut self, i: &'ast syn::ExprMatch) {
self.context.push(Node::Match(MatchInfo::new(
i.span().into(),
i.match_token
.span()
.join(i.expr.span())
.unwrap_or_else(|| i.span())
.into(),
)));
// only visit the arms, calling hooks inside the expression is not conditional
for it in &i.arms {
self.visit_arm(it);
}
self.context.pop();
}
fn visit_expr_for_loop(&mut self, i: &'ast syn::ExprForLoop) {
self.context.push(Node::For(ForInfo::new(
i.span().into(),
i.for_token
.span()
.join(i.expr.span())
.unwrap_or_else(|| i.span())
.into(),
)));
syn::visit::visit_expr_for_loop(self, i);
self.context.pop();
}
fn visit_expr_while(&mut self, i: &'ast syn::ExprWhile) {
self.context.push(Node::While(WhileInfo::new(
i.span().into(),
i.while_token
.span()
.join(i.cond.span())
.unwrap_or_else(|| i.span())
.into(),
)));
syn::visit::visit_expr_while(self, i);
self.context.pop();
}
fn visit_expr_loop(&mut self, i: &'ast syn::ExprLoop) {
self.context
.push(Node::Loop(LoopInfo::new(i.span().into())));
syn::visit::visit_expr_loop(self, i);
self.context.pop();
}
fn visit_expr_closure(&mut self, i: &'ast syn::ExprClosure) {
self.context
.push(Node::Closure(ClosureInfo::new(i.span().into())));
syn::visit::visit_expr_closure(self, i);
self.context.pop();
}
fn visit_expr_async(&mut self, i: &'ast syn::ExprAsync) {
self.context
.push(Node::Async(AsyncInfo::new(i.span().into())));
syn::visit::visit_expr_async(self, i);
self.context.pop();
}
}
#[cfg(test)]
mod tests {
use crate::metadata::{
AnyLoopInfo, ClosureInfo, ConditionalInfo, ForInfo, HookInfo, IfInfo, LineColumn, LoopInfo,
MatchInfo, Span, WhileInfo,
};
use indoc::indoc;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn test_no_hooks() {
let contents = indoc! {r#"
fn App() -> Element {
rsx! {
p { "Hello World" }
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_hook_correctly_used_inside_component() {
let contents = indoc! {r#"
fn App() -> Element {
let count = use_signal(|| 0);
rsx! {
p { "Hello World: {count}" }
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_hook_correctly_used_inside_hook_fn() {
let contents = indoc! {r#"
fn use_thing() -> UseState<i32> {
use_signal(|| 0)
}
"#};
let report = check_file("use_thing.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_hook_correctly_used_inside_hook_closure() {
let contents = indoc! {r#"
fn App() -> Element {
let use_thing = || {
use_signal(|| 0)
};
let count = use_thing();
rsx! {
p { "Hello World: {count}" }
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_conditional_hook_if() {
let contents = indoc! {r#"
fn App() -> Element {
if you_are_happy && you_know_it {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideConditional(
HookInfo::new(
Span::new_from_str(
r#"use_signal(|| "hands")"#,
LineColumn { line: 3, column: 24 },
),
Span::new_from_str(
r#"use_signal"#,
LineColumn { line: 3, column: 24 },
),
"use_signal".to_string()
),
ConditionalInfo::If(IfInfo::new(
Span::new_from_str(
"if you_are_happy && you_know_it {\n let something = use_signal(|| \"hands\");\n println!(\"clap your {something}\")\n }",
LineColumn { line: 2, column: 4 },
),
Span::new_from_str(
"if you_are_happy && you_know_it",
LineColumn { line: 2, column: 4 }
)
))
)],
);
}
#[test]
fn test_conditional_hook_match() {
let contents = indoc! {r#"
fn App() -> Element {
match you_are_happy && you_know_it {
true => {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
false => {}
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideConditional(
HookInfo::new(
Span::new_from_str(r#"use_signal(|| "hands")"#, LineColumn { line: 4, column: 28 }),
Span::new_from_str(r#"use_signal"#, LineColumn { line: 4, column: 28 }),
"use_signal".to_string()
),
ConditionalInfo::Match(MatchInfo::new(
Span::new_from_str(
"match you_are_happy && you_know_it {\n true => {\n let something = use_signal(|| \"hands\");\n println!(\"clap your {something}\")\n }\n false => {}\n }",
LineColumn { line: 2, column: 4 },
),
Span::new_from_str("match you_are_happy && you_know_it", LineColumn { line: 2, column: 4 })
))
)]
);
}
#[test]
fn test_use_in_match_expr() {
let contents = indoc! {r#"
fn use_thing() {
match use_resource(|| async {}) {
Ok(_) => {}
Err(_) => {}
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_for_loop_hook() {
let contents = indoc! {r#"
fn App() -> Element {
for _name in &names {
let is_selected = use_signal(|| false);
println!("selected: {is_selected}");
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideLoop(
HookInfo::new(
Span::new_from_str(
"use_signal(|| false)",
LineColumn { line: 3, column: 26 },
),
Span::new_from_str(
"use_signal",
LineColumn { line: 3, column: 26 },
),
"use_signal".to_string()
),
AnyLoopInfo::For(ForInfo::new(
Span::new_from_str(
"for _name in &names {\n let is_selected = use_signal(|| false);\n println!(\"selected: {is_selected}\");\n }",
LineColumn { line: 2, column: 4 },
),
Span::new_from_str(
"for _name in &names",
LineColumn { line: 2, column: 4 },
)
))
)]
);
}
#[test]
fn test_while_loop_hook() {
let contents = indoc! {r#"
fn App() -> Element {
while true {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideLoop(
HookInfo::new(
Span::new_from_str(
r#"use_signal(|| "hands")"#,
LineColumn { line: 3, column: 24 },
),
Span::new_from_str(
"use_signal",
LineColumn { line: 3, column: 24 },
),
"use_signal".to_string()
),
AnyLoopInfo::While(WhileInfo::new(
Span::new_from_str(
"while true {\n let something = use_signal(|| \"hands\");\n println!(\"clap your {something}\")\n }",
LineColumn { line: 2, column: 4 },
),
Span::new_from_str(
"while true",
LineColumn { line: 2, column: 4 },
)
))
)],
);
}
#[test]
fn test_loop_hook() {
let contents = indoc! {r#"
fn App() -> Element {
loop {
let something = use_signal(|| "hands");
println!("clap your {something}")
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideLoop(
HookInfo::new(
Span::new_from_str(
r#"use_signal(|| "hands")"#,
LineColumn { line: 3, column: 24 },
),
Span::new_from_str(
"use_signal",
LineColumn { line: 3, column: 24 },
),
"use_signal".to_string()
),
AnyLoopInfo::Loop(LoopInfo::new(Span::new_from_str(
"loop {\n let something = use_signal(|| \"hands\");\n println!(\"clap your {something}\")\n }",
LineColumn { line: 2, column: 4 },
)))
)],
);
}
#[test]
fn test_conditional_okay() {
let contents = indoc! {r#"
fn App() -> Element {
let something = use_signal(|| "hands");
if you_are_happy && you_know_it {
println!("clap your {something}")
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_conditional_expr_okay() {
let contents = indoc! {r#"
fn App() -> Element {
if use_signal(|| true) {
println!("clap your {something}")
}
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_closure_hook() {
let contents = indoc! {r#"
fn App() -> Element {
let _a = || {
let b = use_signal(|| 0);
b.get()
};
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideClosure(
HookInfo::new(
Span::new_from_str(
"use_signal(|| 0)",
LineColumn {
line: 3,
column: 16
},
),
Span::new_from_str(
"use_signal",
LineColumn {
line: 3,
column: 16
},
),
"use_signal".to_string()
),
ClosureInfo::new(Span::new_from_str(
"|| {\n let b = use_signal(|| 0);\n b.get()\n }",
LineColumn {
line: 2,
column: 13
},
))
)]
);
}
#[test]
fn test_hook_outside_component() {
let contents = indoc! {r#"
fn not_component_or_hook() {
let _a = use_signal(|| 0);
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookOutsideComponent(HookInfo::new(
Span::new_from_str(
"use_signal(|| 0)",
LineColumn {
line: 2,
column: 13
}
),
Span::new_from_str(
"use_signal",
LineColumn {
line: 2,
column: 13
},
),
"use_signal".to_string()
))]
);
}
#[test]
fn test_hook_inside_hook() {
let contents = indoc! {r#"
fn use_thing() {
let _a = use_signal(|| 0);
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(report.issues, vec![]);
}
#[test]
fn test_hook_inside_hook_initialization() {
let contents = indoc! {r#"
fn use_thing() {
let _a = use_signal(|| use_signal(|| 0));
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideClosure(
HookInfo::new(
Span::new_from_str(
"use_signal(|| 0)",
LineColumn {
line: 2,
column: 27,
},
),
Span::new_from_str(
"use_signal",
LineColumn {
line: 2,
column: 27,
},
),
"use_signal".to_string()
),
ClosureInfo::new(Span::new_from_str(
"|| use_signal(|| 0)",
LineColumn {
line: 2,
column: 24,
},
))
),]
);
}
#[test]
fn test_hook_inside_hook_async_initialization() {
let contents = indoc! {r#"
fn use_thing() {
let _a = use_future(|| async move { use_signal(|| 0) });
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![
Issue::HookInsideAsync(
HookInfo::new(
Span::new_from_str(
"use_signal(|| 0)",
LineColumn {
line: 2,
column: 40,
},
),
Span::new_from_str(
"use_signal",
LineColumn {
line: 2,
column: 40,
},
),
"use_signal".to_string()
),
AsyncInfo::new(Span::new_from_str(
"async move { use_signal(|| 0) }",
LineColumn {
line: 2,
column: 27,
},
))
),
Issue::HookInsideClosure(
HookInfo::new(
Span::new_from_str(
"use_signal(|| 0)",
LineColumn {
line: 2,
column: 40,
},
),
Span::new_from_str(
"use_signal",
LineColumn {
line: 2,
column: 40,
},
),
"use_signal".to_string()
),
ClosureInfo::new(Span::new_from_str(
"|| async move { use_signal(|| 0) }",
LineColumn {
line: 2,
column: 24,
},
))
),
]
);
}
#[test]
fn test_hook_inside_spawn() {
let contents = indoc! {r#"
fn use_thing() {
let _a = spawn(async move { use_signal(|| 0) });
}
"#};
let report = check_file("app.rs".into(), contents);
assert_eq!(
report.issues,
vec![Issue::HookInsideAsync(
HookInfo::new(
Span::new_from_str(
"use_signal(|| 0)",
LineColumn {
line: 2,
column: 32,
},
),
Span::new_from_str(
"use_signal",
LineColumn {
line: 2,
column: 32,
},
),
"use_signal".to_string()
),
AsyncInfo::new(Span::new_from_str(
"async move { use_signal(|| 0) }",
LineColumn {
line: 2,
column: 19,
},
))
),]
);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/check/src/metadata.rs | packages/check/src/metadata.rs | #[derive(Debug, Clone, PartialEq, Eq)]
/// Information about a hook call or function.
pub struct HookInfo {
/// The name of the hook, e.g. `use_signal`.
pub name: String,
/// The span of the hook, e.g. `use_signal`.
pub span: Span,
/// The span of the name, e.g. `use_signal`.
pub name_span: Span,
}
impl HookInfo {
pub const fn new(span: Span, name_span: Span, name: String) -> Self {
Self {
span,
name_span,
name,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConditionalInfo {
If(IfInfo),
Match(MatchInfo),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IfInfo {
/// The span of the `if` statement, e.g. `if true { ... }`.
pub span: Span,
/// The span of the `if true` part only.
pub head_span: Span,
}
impl IfInfo {
pub const fn new(span: Span, head_span: Span) -> Self {
Self { span, head_span }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MatchInfo {
/// The span of the `match` statement, e.g. `match true { ... }`.
pub span: Span,
/// The span of the `match true` part only.
pub head_span: Span,
}
impl MatchInfo {
pub const fn new(span: Span, head_span: Span) -> Self {
Self { span, head_span }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about one of the possible loop types.
pub enum AnyLoopInfo {
For(ForInfo),
While(WhileInfo),
Loop(LoopInfo),
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about a `for` loop.
pub struct ForInfo {
pub span: Span,
pub head_span: Span,
}
impl ForInfo {
pub const fn new(span: Span, head_span: Span) -> Self {
Self { span, head_span }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about a `while` loop.
pub struct WhileInfo {
pub span: Span,
pub head_span: Span,
}
impl WhileInfo {
pub const fn new(span: Span, head_span: Span) -> Self {
Self { span, head_span }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about a `loop` loop.
pub struct LoopInfo {
pub span: Span,
}
impl LoopInfo {
pub const fn new(span: Span) -> Self {
Self { span }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about a closure.
pub struct ClosureInfo {
pub span: Span,
}
impl ClosureInfo {
pub const fn new(span: Span) -> Self {
Self { span }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about an async block.
pub struct AsyncInfo {
pub span: Span,
}
impl AsyncInfo {
pub const fn new(span: Span) -> Self {
Self { span }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about a component function.
pub struct ComponentInfo {
pub span: Span,
pub name: String,
pub name_span: Span,
}
impl ComponentInfo {
pub const fn new(span: Span, name: String, name_span: Span) -> Self {
Self {
span,
name,
name_span,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Information about a non-component, non-hook function.
pub struct FnInfo {
pub span: Span,
pub name: String,
pub name_span: Span,
}
impl FnInfo {
pub const fn new(span: Span, name: String, name_span: Span) -> Self {
Self {
span,
name,
name_span,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// A span of text in a source code file.
pub struct Span {
pub source_text: Option<String>,
pub start: LineColumn,
pub end: LineColumn,
}
impl Span {
pub fn new_from_str(source_text: &str, start: LineColumn) -> Self {
let mut lines = source_text.lines();
let first_line = lines.next().unwrap_or_default();
let mut end = LineColumn {
line: start.line,
column: start.column + first_line.len(),
};
for line in lines {
end.line += 1;
end.column = line.len();
}
Self {
source_text: Some(source_text.to_string()),
start,
end,
}
}
}
impl From<proc_macro2::Span> for Span {
fn from(span: proc_macro2::Span) -> Self {
Self {
source_text: span.source_text(),
start: span.start().into(),
end: span.end().into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// A location in a source code file.
pub struct LineColumn {
pub line: usize,
pub column: usize,
}
impl From<proc_macro2::LineColumn> for LineColumn {
fn from(lc: proc_macro2::LineColumn) -> Self {
Self {
line: lc.line,
column: lc.column,
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-hotreload/src/lib.rs | packages/rsx-hotreload/src/lib.rs | mod collect;
pub use collect::*;
mod diff;
pub use diff::*;
mod last_build_state;
mod extensions;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-hotreload/src/last_build_state.rs | packages/rsx-hotreload/src/last_build_state.rs | use dioxus_core::internal::{FmtSegment, FmtedSegments, HotReloadLiteral};
use dioxus_rsx::*;
use std::cell::Cell;
/// A pool of items we can grab from during hot reloading.
/// We have three different pools we can pull from:
/// - Dynamic text segments (eg: "{class}")
/// - Dynamic nodes (eg: {children})
/// - Dynamic attributes (eg: ..spread )
///
/// As we try to create a new hot reloaded template, we will pull from these pools to create the new template. We mark
/// each item as used the first time we use it in the new template. Once the new template if fully created, we can tally
/// up how many items are unused to determine how well the new template matches the old template.
///
/// The template that matches best will leave the least unused items in the pool.
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct BakedPool<T> {
pub inner: Vec<BakedItem<T>>,
}
impl<T> BakedPool<T> {
/// Create a new baked pool from an iterator of items
fn new(inner: impl IntoIterator<Item = T>) -> Self {
Self {
inner: inner.into_iter().map(BakedItem::new).collect(),
}
}
/// Find the first item in the pool that matches the condition and mark it as used
pub fn position(&self, condition: impl Fn(&T) -> bool) -> Option<usize> {
for (idx, baked_item) in self.inner.iter().enumerate() {
if condition(&baked_item.inner) {
baked_item.used.set(true);
return Some(idx);
}
}
None
}
/// Find the number of unused items in the pool
fn unused_dynamic_items(&self) -> usize {
self.inner
.iter()
.filter(|baked_item| !baked_item.used.get())
.count()
}
}
/// A single item in the baked item pool. We keep track if which items are used for scoring how well two templates match.
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct BakedItem<T> {
pub inner: T,
pub used: Cell<bool>,
}
impl<T> BakedItem<T> {
fn new(inner: T) -> Self {
Self {
inner,
used: Cell::new(false),
}
}
}
/// The state of the last full rebuild.
/// This object contains the pool of compiled dynamic segments we can pull from for hot reloading
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct LastBuildState {
/// The formatted segments that were used in the last build. Eg: "{class}", "{id}"
///
/// We are free to use each of these segments many times in the same build.
/// We just clone the result (assuming display + debug have no side effects)
pub dynamic_text_segments: BakedPool<FormattedSegment>,
/// The dynamic nodes that were used in the last build. Eg: div { {children} }
///
/// We are also free to clone these nodes many times in the same build.
pub dynamic_nodes: BakedPool<BodyNode>,
/// The attributes that were used in the last build. Eg: div { class: "{class}" }
///
/// We are also free to clone these nodes many times in the same build.
pub dynamic_attributes: BakedPool<Attribute>,
/// The component literal properties we can hot reload from the last build. Eg: Component { class: "{class}" }
///
/// In the new build, we must assign each of these a value even if we no longer use the component.
/// The type must be the same as the last time we compiled the property
pub component_properties: Vec<HotLiteral>,
/// The root indexes of the last build
pub root_index: DynIdx,
/// The name of the original template
pub name: String,
}
impl LastBuildState {
/// Create a new LastBuildState from the given [`TemplateBody`]
pub fn new(body: &TemplateBody, name: String) -> Self {
let dynamic_text_segments = body.dynamic_text_segments.iter().cloned();
let dynamic_nodes = body.dynamic_nodes().cloned();
let dynamic_attributes = body.dynamic_attributes().cloned();
let component_properties = body.literal_component_properties().cloned().collect();
Self {
dynamic_text_segments: BakedPool::new(dynamic_text_segments),
dynamic_nodes: BakedPool::new(dynamic_nodes),
dynamic_attributes: BakedPool::new(dynamic_attributes),
component_properties,
root_index: body.template_idx.clone(),
name,
}
}
/// Return the number of unused dynamic items in the pool
pub fn unused_dynamic_items(&self) -> usize {
self.dynamic_text_segments.unused_dynamic_items()
+ self.dynamic_nodes.unused_dynamic_items()
+ self.dynamic_attributes.unused_dynamic_items()
}
/// Hot reload a hot literal
pub fn hotreload_hot_literal(&self, hot_literal: &HotLiteral) -> Option<HotReloadLiteral> {
match hot_literal {
// If the literal is a formatted segment, map the segments to the new formatted segments
HotLiteral::Fmted(segments) => {
let new_segments = self.hot_reload_formatted_segments(segments)?;
Some(HotReloadLiteral::Fmted(new_segments))
}
// Otherwise just pass the literal through unchanged
HotLiteral::Bool(b) => Some(HotReloadLiteral::Bool(b.value())),
HotLiteral::Float(f) => Some(HotReloadLiteral::Float(f.base10_parse().ok()?)),
HotLiteral::Int(i) => Some(HotReloadLiteral::Int(i.base10_parse().ok()?)),
}
}
pub fn hot_reload_formatted_segments(
&self,
new: &HotReloadFormattedSegment,
) -> Option<FmtedSegments> {
// Go through each dynamic segment and look for a match in the formatted segments pool.
// If we find a match, we can hot reload the segment otherwise we need to do a full rebuild
let mut segments = Vec::new();
for segment in &new.segments {
match segment {
// If it is a literal, we can always hot reload it. Just add it to the segments
Segment::Literal(value) => {
segments.push(FmtSegment::Literal {
value: Box::leak(value.clone().into_boxed_str()),
});
} // If it is a dynamic segment, we need to check if it exists in the formatted segments pool
Segment::Formatted(formatted) => {
let index = self.dynamic_text_segments.position(|s| s == formatted)?;
segments.push(FmtSegment::Dynamic { id: index });
}
}
}
Some(FmtedSegments::new(segments))
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-hotreload/src/collect.rs | packages/rsx-hotreload/src/collect.rs | //! Compare two files and find any rsx calls that have changed
//!
//! This is used to determine if a hotreload is needed.
//! We use a special syn visitor to find all the rsx! calls in the file and then compare them to see
//! if they are the same. This visitor will actually remove the rsx! calls and replace them with a
//! dummy rsx! call. The final file type is thus mutated in place, leaving the original file idents
//! in place. We then compare the two files to see if they are the same. We're able to differentiate
//! between rust code changes and rsx code changes with much less code than the previous manual diff
//! approach.
use syn::visit_mut::VisitMut;
use syn::{File, Macro};
pub struct ChangedRsx {
/// The old macro - the original RSX from the original file
pub old: Macro,
/// The new macro
pub new: Macro,
}
#[derive(Debug)]
pub enum ReloadableRustCode {
Rsx { old: Macro, new: Macro },
}
/// Find any rsx calls in the given file and return a list of all the rsx calls that have changed.
///
/// Takes in the two files, clones them, removes the rsx! contents and prunes any doc comments.
/// Then it compares the two files to see if they are different - if they are, the code changed.
/// Otherwise, the code is the same and we can move on to handling the changed rsx
///
/// Returns `None` if the files are the same and `Some` if they are different
/// If there are no rsx! calls in the files, the vec will be empty.
pub fn diff_rsx(new: &File, old: &File) -> Option<Vec<ChangedRsx>> {
// Make a clone of these files in place so we don't have to worry about mutating the original
let mut old = old.clone();
let mut new = new.clone();
// Collect all the rsx! macros from the old file - modifying the files in place
let old_macros = collect_from_file(&mut old);
let new_macros = collect_from_file(&mut new);
// If the number of rsx! macros is different, then it's not hotreloadable
if old_macros.len() != new_macros.len() {
return None;
}
// If the files are not the same, then it's not hotreloadable
if old != new {
return None;
}
Some(
old_macros
.into_iter()
.zip(new_macros)
.map(|(old, new)| ChangedRsx { old, new })
.collect(),
)
}
pub fn collect_from_file(file: &mut File) -> Vec<Macro> {
struct MacroCollector(Vec<Macro>);
impl VisitMut for MacroCollector {
/// Take out the rsx! macros, leaving a default in their place
fn visit_macro_mut(&mut self, dest: &mut syn::Macro) {
let name = &dest.path.segments.last().map(|i| i.ident.to_string());
if let Some("rsx" | "render") = name.as_deref() {
let mut default: syn::Macro = syn::parse_quote! { rsx! {} };
std::mem::swap(dest, &mut default);
self.0.push(default)
}
}
/// Ignore doc comments by swapping them out with a default
fn visit_attribute_mut(&mut self, i: &mut syn::Attribute) {
if i.path().is_ident("doc") {
*i = syn::parse_quote! { #[doc = ""] };
}
}
}
let mut macros = MacroCollector(vec![]);
macros.visit_file_mut(file);
macros.0
}
#[test]
fn changing_files() {
let old = r#"
use dioxus::prelude::*;
/// some comment
pub fn CoolChild() -> Element {
let a = 123;
rsx! {
div {
{some_expr()}
}
}
}"#;
let new = r#"
use dioxus::prelude::*;
/// some comment
pub fn CoolChild() -> Element {
rsx! {
div {
{some_expr()}
}
}
}"#;
let same = r#"
use dioxus::prelude::*;
/// some comment!!!!!
pub fn CoolChild() -> Element {
let a = 123;
rsx! {
div {
{some_expr()}
}
}
}"#;
let old = syn::parse_file(old).unwrap();
let new = syn::parse_file(new).unwrap();
let same = syn::parse_file(same).unwrap();
assert!(
diff_rsx(&old, &new).is_none(),
"Files with different expressions should not be hotreloadable"
);
assert!(
diff_rsx(&new, &new).is_some(),
"The same file should be reloadable with itself"
);
assert!(
diff_rsx(&old, &same).is_some(),
"Files with changed comments should be hotreloadable"
);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-hotreload/src/diff.rs | packages/rsx-hotreload/src/diff.rs | //! This module contains the diffing logic for rsx hot reloading.
//!
//! There's a few details that I wish we could've gotten right but we can revisit later:
//!
//! - Expanding an if chain is not possible - only its contents can be hot reloaded
//!
//! - Components that don't start with children can't be hot reloaded - IE going from `Comp {}` to `Comp { "foo" }`
//! is not possible. We could in theory allow this by seeding all Components with a `children` field.
//!
//! - Cross-templates hot reloading is not possible - multiple templates don't share the dynamic pool. This would require handling aliases
//! in hot reload diffing.
//!
//! - We've proven that binary patching is feasible but has a longer path to stabilization for all platforms.
//! Binary patching is pretty quick, actually, and *might* remove the need to literal hot reloading.
//! However, you could imagine a scenario where literal hot reloading would be useful without the
//! compiler in the loop. Ideally we can slash most of this code once patching is stable.
//!
//! ## Assigning/Scoring Templates
//!
//! We can clone most dynamic items from the last full rebuild:
//! - Dynamic text segments: `div { width: "{x}%" } -> div { width: "{x}%", height: "{x}%" }`
//! - Dynamic attributes: `div { width: dynamic } -> div { width: dynamic, height: dynamic }`
//! - Dynamic nodes: `div { {children} } -> div { {children} {children} }`
//!
//! But we cannot clone rsx bodies themselves because we cannot hot reload the new rsx body:
//! - `div { Component { "{text}" } } -> div { Component { "{text}" } Component { "hello" } }` // We can't create a template for both "{text}" and "hello"
//!
//! In some cases, two nodes with children are ambiguous. For example:
//! ```rust, ignore
//! rsx! {
//! div {
//! Component { "{text}" }
//! Component { "hello" }
//! }
//! }
//! ```
//!
//! Outside of the template, both components are compatible for hot reloading.
//!
//! After we create a list of all components with compatible names and props, we need to find the best match for the
//! template.
//!
//!
//! Dioxus uses a greedy algorithm to find the best match. We first try to create the child template with the dynamic context from the last full rebuild.
//! Then we use the child template that leaves the least unused dynamic items in the pool to create the new template.
//!
//! For the example above:
//! - Hot reloading `Component { "hello" }`:
//! - Try to hot reload the component body `"hello"` with the dynamic pool from `"{text}"`: Success with 1 unused dynamic item
//! - Try to hot reload the component body `"hello"` with the dynamic pool from `"hello"`: Success with 0 unused dynamic items
//! - We use the the template that leaves the least unused dynamic items in the pool - `"hello"`
//! - Hot reloading `Component { "{text}" }`:
//! - Try to hot reload the component body `"{text}"` with the dynamic pool from `"{text}"`: Success with 0 unused dynamic items
//! - The `"hello"` template has already been hot reloaded, so we don't try to hot reload it again
//! - We use the the template that leaves the least unused dynamic items in the pool - `"{text}"`
//!
//! Greedy algorithms are optimal when:
//! - The step we take reduces the problem size
//! - The subproblem is optimal
//!
//! In this case, hot reloading a template removes it from the pool of templates we can use to hot reload the next template which reduces the problem size.
//!
//! The subproblem is optimal because the alternative is leaving less dynamic items for the remaining templates to hot reload which just makes it
//! more difficult to match future templates.
use dioxus_core::internal::{
FmtedSegments, HotReloadAttributeValue, HotReloadDynamicAttribute, HotReloadDynamicNode,
HotReloadLiteral, HotReloadedTemplate, NamedAttribute,
};
use dioxus_core_types::HotReloadingContext;
use dioxus_rsx::*;
use std::collections::HashMap;
use crate::extensions::{html_tag_and_namespace, intern, to_template_node};
use super::last_build_state::LastBuildState;
/// A result of hot reloading
///
/// This contains information about what has changed so the hotreloader can apply the right changes
#[non_exhaustive]
#[derive(Debug, PartialEq, Clone)]
pub struct HotReloadResult {
/// The child templates we have already used. As we walk through the template tree, we will run into child templates.
/// Each of those child templates also need to be hot reloaded. We keep track of which ones we've already hotreloaded
/// to avoid diffing the same template twice against different new templates.
///
/// ```rust, ignore
/// rsx! {
/// Component { class: "{class}", "{text}" } // The children of a Component is a new template
/// for item in items {
/// "{item}" // The children of a for loop is a new template
/// }
/// if true {
/// "{text}" // The children of an if chain is a new template
/// }
/// }
/// ```
///
/// If we hotreload the component, we don't need to hotreload the for loop
///
/// You should diff the result of this against the old template to see if you actually need to send down the result
pub templates: HashMap<usize, HotReloadedTemplate>,
/// The state of the last full rebuild.
full_rebuild_state: LastBuildState,
/// The dynamic nodes for the current node
dynamic_nodes: Vec<HotReloadDynamicNode>,
/// The dynamic attributes for the current node
dynamic_attributes: Vec<HotReloadDynamicAttribute>,
/// The literal component properties for the current node
literal_component_properties: Vec<HotReloadLiteral>,
}
impl HotReloadResult {
/// Calculate the hot reload diff between two template bodies
pub fn new<Ctx: HotReloadingContext>(
full_rebuild_state: &TemplateBody,
new: &TemplateBody,
name: String,
) -> Option<Self> {
// Normalize both the full rebuild state and the new state for rendering
let full_rebuild_state = full_rebuild_state.normalized();
let new = new.normalized();
let full_rebuild_state = LastBuildState::new(&full_rebuild_state, name);
let mut s = Self {
full_rebuild_state,
templates: Default::default(),
dynamic_nodes: Default::default(),
dynamic_attributes: Default::default(),
literal_component_properties: Default::default(),
};
s.hotreload_body::<Ctx>(&new)?;
Some(s)
}
fn extend(&mut self, other: Self) {
self.templates.extend(other.templates);
}
/// Walk the dynamic contexts and do our best to find hot reload-able changes between the two
/// sets of dynamic nodes/attributes. If there's a change we can't hot reload, we'll return None
///
/// Otherwise, we pump out the list of templates that need to be updated. The templates will be
/// re-ordered such that the node paths will be adjusted to match the new template for every
/// existing dynamic node.
///
/// ```ignore
/// old:
/// [[0], [1], [2]]
/// rsx! {
/// "{one}"
/// "{two}"
/// "{three}"
/// }
///
/// new:
/// [[0], [2], [1, 1]]
/// rsx! {
/// "{one}"
/// div { "{three}" }
/// "{two}"
/// }
/// ```
///
/// Generally we can't hot reload a node if:
/// - We add or modify a new rust expression
/// - Adding a new formatted segment we haven't seen before
/// - Adding a new dynamic node (loop, fragment, if chain, etc)
/// - We add a new component field
/// - We remove a component field
/// - We change the type of a component field
///
/// If a dynamic node is removed, we don't necessarily need to kill hot reload - just unmounting it should be enough
/// If the dynamic node is re-added, we want to be able to find it again.
///
/// This encourages the hot reloader to hot onto DynamicContexts directly instead of the CallBody since
/// you can preserve more information about the nodes as they've changed over time.
fn hotreload_body<Ctx: HotReloadingContext>(&mut self, new: &TemplateBody) -> Option<()> {
// Quickly run through dynamic attributes first attempting to invalidate them
// Move over old IDs onto the new template
self.hotreload_attributes::<Ctx>(new)?;
let new_dynamic_attributes = std::mem::take(&mut self.dynamic_attributes);
// Now we can run through the dynamic nodes and see if we can hot reload them
// Move over old IDs onto the new template
self.hotreload_dynamic_nodes::<Ctx>(new)?;
let new_dynamic_nodes = std::mem::take(&mut self.dynamic_nodes);
let literal_component_properties = std::mem::take(&mut self.literal_component_properties);
let key = self.hot_reload_key(new)?;
let roots: Vec<_> = new
.roots
.iter()
.map(|node| to_template_node::<Ctx>(node))
.collect();
let roots: &[dioxus_core::TemplateNode] = intern(&*roots);
let template = HotReloadedTemplate::new(
key,
new_dynamic_nodes,
new_dynamic_attributes,
literal_component_properties,
roots,
);
self.templates
.insert(self.full_rebuild_state.root_index.get(), template);
Some(())
}
fn hot_reload_key(&mut self, new: &TemplateBody) -> Option<Option<FmtedSegments>> {
match new.implicit_key() {
Some(AttributeValue::AttrLiteral(HotLiteral::Fmted(value))) => Some(Some(
self.full_rebuild_state
.hot_reload_formatted_segments(value)?,
)),
None => Some(None),
_ => None,
}
}
fn hotreload_dynamic_nodes<Ctx: HotReloadingContext>(
&mut self,
new: &TemplateBody,
) -> Option<()> {
for new_node in new.dynamic_nodes() {
self.hot_reload_node::<Ctx>(new_node)?
}
Some(())
}
fn hot_reload_node<Ctx: HotReloadingContext>(&mut self, node: &BodyNode) -> Option<()> {
match node {
BodyNode::Text(text) => self.hotreload_text_node(text),
BodyNode::Component(component) => self.hotreload_component::<Ctx>(component),
BodyNode::ForLoop(forloop) => self.hotreload_for_loop::<Ctx>(forloop),
BodyNode::IfChain(ifchain) => self.hotreload_if_chain::<Ctx>(ifchain),
BodyNode::RawExpr(expr) => self.hotreload_raw_expr(expr),
BodyNode::Element(_) => Some(()),
}
}
fn hotreload_raw_expr(&mut self, expr: &ExprNode) -> Option<()> {
// Try to find the raw expr in the last build
let expr_index = self
.full_rebuild_state
.dynamic_nodes
.position(|node| match &node {
BodyNode::RawExpr(raw_expr) => raw_expr.expr == expr.expr,
_ => false,
})?;
// If we find it, push it as a dynamic node
self.dynamic_nodes
.push(HotReloadDynamicNode::Dynamic(expr_index));
Some(())
}
fn hotreload_for_loop<Ctx>(&mut self, forloop: &ForLoop) -> Option<()>
where
Ctx: HotReloadingContext,
{
// Find all for loops that have the same pattern and expression
let candidate_for_loops = self
.full_rebuild_state
.dynamic_nodes
.inner
.iter()
.enumerate()
.filter_map(|(index, node)| {
if let BodyNode::ForLoop(for_loop) = &node.inner {
if for_loop.pat == forloop.pat && for_loop.expr == forloop.expr {
return Some((index, for_loop));
}
}
None
})
.collect::<Vec<_>>();
// Then find the one that has the least wasted dynamic items when hot reloading the body
let (index, best_call_body) = self.diff_best_call_body::<Ctx>(
candidate_for_loops
.iter()
.map(|(_, for_loop)| &for_loop.body),
&forloop.body,
)?;
// Push the new for loop as a dynamic node
self.dynamic_nodes
.push(HotReloadDynamicNode::Dynamic(candidate_for_loops[index].0));
self.extend(best_call_body);
Some(())
}
fn hotreload_text_node(&mut self, text_node: &TextNode) -> Option<()> {
// If it is static, it is already included in the template and we don't need to do anything
if text_node.input.is_static() {
return Some(());
}
// Otherwise, hot reload the formatted segments and push that as a dynamic node
let formatted_segments = self
.full_rebuild_state
.hot_reload_formatted_segments(&text_node.input)?;
self.dynamic_nodes
.push(HotReloadDynamicNode::Formatted(formatted_segments));
Some(())
}
/// Find the call body that minimizes the number of wasted dynamic items
///
/// Returns the index of the best call body and the state of the best call body
fn diff_best_call_body<'a, Ctx>(
&self,
bodies: impl Iterator<Item = &'a TemplateBody>,
new_call_body: &TemplateBody,
) -> Option<(usize, Self)>
where
Ctx: HotReloadingContext,
{
let mut best_score = usize::MAX;
let mut best_output = None;
for (index, body) in bodies.enumerate() {
// Skip templates we've already hotreloaded
if self.templates.contains_key(&body.template_idx.get()) {
continue;
}
if let Some(state) =
Self::new::<Ctx>(body, new_call_body, self.full_rebuild_state.name.clone())
{
let score = state.full_rebuild_state.unused_dynamic_items();
if score < best_score {
best_score = score;
best_output = Some((index, state));
}
}
}
best_output
}
fn hotreload_component<Ctx>(&mut self, component: &Component) -> Option<()>
where
Ctx: HotReloadingContext,
{
// First we need to find the component that matches the best in the last build
// We try each build and choose the option that wastes the least dynamic items
let components_with_matching_attributes: Vec<_> = self
.full_rebuild_state
.dynamic_nodes
.inner
.iter()
.enumerate()
.filter_map(|(index, node)| {
if let BodyNode::Component(comp) = &node.inner {
return Some((
index,
comp,
self.hotreload_component_fields(comp, component)?,
));
}
None
})
.collect();
let possible_bodies = components_with_matching_attributes
.iter()
.map(|(_, comp, _)| &comp.children);
let (index, new_body) =
self.diff_best_call_body::<Ctx>(possible_bodies, &component.children)?;
let (index, _, literal_component_properties) = &components_with_matching_attributes[index];
let index = *index;
self.full_rebuild_state.dynamic_nodes.inner[index]
.used
.set(true);
self.literal_component_properties
.extend(literal_component_properties.iter().cloned());
self.extend(new_body);
// Push the new component as a dynamic node
self.dynamic_nodes
.push(HotReloadDynamicNode::Dynamic(index));
Some(())
}
fn hotreload_component_fields(
&self,
old_component: &Component,
new_component: &Component,
) -> Option<Vec<HotReloadLiteral>> {
// First check if the component is the same
if new_component.name != old_component.name {
return None;
}
// Then check if the fields are the same
let new_non_key_fields: Vec<_> = new_component.component_props().collect();
let old_non_key_fields: Vec<_> = old_component.component_props().collect();
if new_non_key_fields.len() != old_non_key_fields.len() {
return None;
}
let mut new_fields = new_non_key_fields.clone();
new_fields.sort_by_key(|attribute| attribute.name.to_string());
let mut old_fields = old_non_key_fields.iter().enumerate().collect::<Vec<_>>();
old_fields.sort_by_key(|(_, attribute)| attribute.name.to_string());
// The literal component properties for the component in same the order as the original component property literals
let mut literal_component_properties = vec![None; old_fields.len()];
for (new_field, (index, old_field)) in new_fields.iter().zip(old_fields.iter()) {
// Verify the names match
if new_field.name != old_field.name {
return None;
}
// Verify the values match
match (&new_field.value, &old_field.value) {
// If the values are both literals, we can try to hotreload them
(
AttributeValue::AttrLiteral(new_value),
AttributeValue::AttrLiteral(old_value),
) => {
// Make sure that the types are the same
if std::mem::discriminant(new_value) != std::mem::discriminant(old_value) {
return None;
}
let literal = self.full_rebuild_state.hotreload_hot_literal(new_value)?;
literal_component_properties[*index] = Some(literal);
}
_ => {
if new_field.value != old_field.value {
return None;
}
}
}
}
Some(literal_component_properties.into_iter().flatten().collect())
}
/// Hot reload an if chain
fn hotreload_if_chain<Ctx: HotReloadingContext>(
&mut self,
new_if_chain: &IfChain,
) -> Option<()> {
let mut best_if_chain = None;
let mut best_score = usize::MAX;
let if_chains = self
.full_rebuild_state
.dynamic_nodes
.inner
.iter()
.enumerate()
.filter_map(|(index, node)| {
if let BodyNode::IfChain(if_chain) = &node.inner {
return Some((index, if_chain));
}
None
});
// Find the if chain that matches all of the conditions and wastes the least dynamic items
for (index, old_if_chain) in if_chains {
let Some(chain_templates) = Self::diff_if_chains::<Ctx>(
old_if_chain,
new_if_chain,
self.full_rebuild_state.name.clone(),
) else {
continue;
};
let score = chain_templates
.iter()
.map(|t| t.full_rebuild_state.unused_dynamic_items())
.sum();
if score < best_score {
best_score = score;
best_if_chain = Some((index, chain_templates));
}
}
// If we found a hot reloadable if chain, hotreload it
let (index, chain_templates) = best_if_chain?;
// Mark the if chain as used
self.full_rebuild_state.dynamic_nodes.inner[index]
.used
.set(true);
// Merge the hot reload changes into the current state
for template in chain_templates {
self.extend(template);
}
// Push the new if chain as a dynamic node
self.dynamic_nodes
.push(HotReloadDynamicNode::Dynamic(index));
Some(())
}
/// Hot reload an if chain
fn diff_if_chains<Ctx: HotReloadingContext>(
old_if_chain: &IfChain,
new_if_chain: &IfChain,
name: String,
) -> Option<Vec<Self>> {
// Go through each part of the if chain and find the best match
let mut old_chain = old_if_chain;
let mut new_chain = new_if_chain;
let mut chain_templates = Vec::new();
loop {
// Make sure the conditions are the same
if old_chain.cond != new_chain.cond {
return None;
}
// If the branches are the same, we can hotreload them
let hot_reload =
Self::new::<Ctx>(&old_chain.then_branch, &new_chain.then_branch, name.clone())?;
chain_templates.push(hot_reload);
// Make sure the if else branches match
match (
old_chain.else_if_branch.as_ref(),
new_chain.else_if_branch.as_ref(),
) {
(Some(old), Some(new)) => {
old_chain = old;
new_chain = new;
}
(None, None) => {
break;
}
_ => return None,
}
}
// Make sure the else branches match
match (&old_chain.else_branch, &new_chain.else_branch) {
(Some(old), Some(new)) => {
let template = Self::new::<Ctx>(old, new, name.clone())?;
chain_templates.push(template);
}
(None, None) => {}
_ => return None,
}
Some(chain_templates)
}
/// Take a new template body and return the attributes that can be hot reloaded from the last build
///
/// IE if we shuffle attributes, remove attributes or add new attributes with the same dynamic segments, around we should be able to hot reload them.
///
/// ```rust, ignore
/// rsx! {
/// div { id: "{id}", class: "{class}", width, "Hi" }
/// }
///
/// rsx! {
/// div { width, class: "{class}", id: "{id} and {class}", "Hi" }
/// }
/// ```
fn hotreload_attributes<Ctx: HotReloadingContext>(&mut self, new: &TemplateBody) -> Option<()> {
// Walk through each attribute and create a new HotReloadAttribute for each one
for new_attr in new.dynamic_attributes() {
// While we're here, if it's a literal and not a perfect score, it's a mismatch and we need to
// hotreload the literal
self.hotreload_attribute::<Ctx>(new_attr)?;
}
Some(())
}
/// Try to hot reload an attribute and return the new HotReloadAttribute
fn hotreload_attribute<Ctx: HotReloadingContext>(
&mut self,
attribute: &Attribute,
) -> Option<()> {
let (tag, namespace) = html_tag_and_namespace::<Ctx>(attribute);
// If the attribute is a spread, try to grab it from the last build
// If it wasn't in the last build with the same name, we can't hot reload it
if let AttributeName::Spread(_) = &attribute.name {
let hot_reload_attribute = self
.full_rebuild_state
.dynamic_attributes
.position(|a| a.name == attribute.name && a.value == attribute.value)?;
self.dynamic_attributes
.push(HotReloadDynamicAttribute::Dynamic(hot_reload_attribute));
return Some(());
}
// Otherwise the attribute is named, try to hot reload the value
let value = match &attribute.value {
// If the attribute is a literal, we can generally hot reload it if the formatted segments exist in the last build
AttributeValue::AttrLiteral(literal) => {
// If it is static, it is already included in the template and we don't need to do anything
if literal.is_static() {
return Some(());
}
// Otherwise, hot reload the literal and push that as a dynamic attribute
let hot_reload_literal = self.full_rebuild_state.hotreload_hot_literal(literal)?;
HotReloadAttributeValue::Literal(hot_reload_literal)
}
// If it isn't a literal, try to find an exact match for the attribute value from the last build
_ => {
let value_index = self.full_rebuild_state.dynamic_attributes.position(|a| {
// Spread attributes are not hot reloaded
if matches!(a.name, AttributeName::Spread(_)) {
return false;
}
if a.value != attribute.value {
return false;
}
// The type of event handlers is influenced by the event name, so te cannot hot reload between different event
// names
if matches!(a.value, AttributeValue::EventTokens(_)) && a.name != attribute.name
{
return false;
}
true
})?;
HotReloadAttributeValue::Dynamic(value_index)
}
};
self.dynamic_attributes
.push(HotReloadDynamicAttribute::Named(NamedAttribute::new(
tag, namespace, value,
)));
Some(())
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-hotreload/src/extensions.rs | packages/rsx-hotreload/src/extensions.rs | use dioxus_core::TemplateNode;
use dioxus_core_types::HotReloadingContext;
use dioxus_rsx::*;
use internment::Intern;
use std::hash::Hash;
// interns a object into a static object, reusing the value if it already exists
pub(crate) fn intern<T: Eq + Hash + Send + Sync + ?Sized + 'static>(
s: impl Into<Intern<T>>,
) -> &'static T {
s.into().as_ref()
}
pub(crate) fn html_tag_and_namespace<Ctx: HotReloadingContext>(
attr: &Attribute,
) -> (&'static str, Option<&'static str>) {
let attribute_name_rust = attr.name.to_string();
let element_name = attr.el_name.as_ref().unwrap();
let rust_name = match element_name {
ElementName::Ident(i) => i.to_string(),
// If this is a web component, just use the name of the elements instead of mapping the attribute
// through the hot reloading context
ElementName::Custom(_) => return (intern(attribute_name_rust.as_str()), None),
};
Ctx::map_attribute(&rust_name, &attribute_name_rust)
.unwrap_or((intern(attribute_name_rust.as_str()), None))
}
pub fn to_template_attribute<Ctx: HotReloadingContext>(
attr: &Attribute,
) -> dioxus_core::TemplateAttribute {
use dioxus_core::TemplateAttribute;
// If it's a dynamic node, just return it
// For dynamic attributes, we need to check the mapping to see if that mapping exists
// todo: one day we could generate new dynamic attributes on the fly if they're a literal,
// or something sufficiently serializable
// (ie `checked`` being a bool and bools being interpretable)
//
// For now, just give up if that attribute doesn't exist in the mapping
if !attr.is_static_str_literal() {
let id = attr.dyn_idx.get();
return TemplateAttribute::Dynamic { id };
}
// Otherwise it's a static node and we can build it
let (_, value) = attr.as_static_str_literal().unwrap();
let (name, namespace) = html_tag_and_namespace::<Ctx>(attr);
TemplateAttribute::Static {
name,
namespace,
value: intern(value.to_static().unwrap().as_str()),
}
}
/// Convert this BodyNode into a TemplateNode.
///
/// dioxus-core uses this to understand templates at compiletime
pub fn to_template_node<Ctx: HotReloadingContext>(node: &BodyNode) -> dioxus_core::TemplateNode {
use dioxus_core::TemplateNode;
match node {
BodyNode::Element(el) => {
let rust_name = el.name.to_string();
let (tag, namespace) =
Ctx::map_element(&rust_name).unwrap_or((intern(rust_name.as_str()), None));
TemplateNode::Element {
tag,
namespace,
children: intern(
el.children
.iter()
.map(|c| to_template_node::<Ctx>(c))
.collect::<Vec<_>>(),
),
attrs: intern(
el.merged_attributes
.iter()
.map(|attr| to_template_attribute::<Ctx>(attr))
.collect::<Vec<_>>(),
),
}
}
BodyNode::Text(text) => text_to_template_node(text),
BodyNode::RawExpr(exp) => TemplateNode::Dynamic {
id: exp.dyn_idx.get(),
},
BodyNode::Component(comp) => TemplateNode::Dynamic {
id: comp.dyn_idx.get(),
},
BodyNode::ForLoop(floop) => TemplateNode::Dynamic {
id: floop.dyn_idx.get(),
},
BodyNode::IfChain(chain) => TemplateNode::Dynamic {
id: chain.dyn_idx.get(),
},
}
}
pub fn text_to_template_node(node: &TextNode) -> TemplateNode {
match node.input.to_static() {
Some(text) => TemplateNode::Text {
text: intern(text.as_str()),
},
None => TemplateNode::Dynamic {
id: node.dyn_idx.get(),
},
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-hotreload/tests/hotreloads.rs | packages/rsx-hotreload/tests/hotreloads.rs | use dioxus_rsx_hotreload::diff_rsx;
use syn::File;
macro_rules! assert_rsx_changed {
(
$( #[doc = $doc:expr] )*
$name:ident
) => {
$( #[doc = $doc] )*
#[test]
fn $name() {
let old = include_str!(concat!("./valid/", stringify!($name), ".old.rsx"));
let new = include_str!(concat!("./valid/", stringify!($name), ".new.rsx"));
let (old, new) = load_files(old, new);
assert!(diff_rsx(&new, &old).is_some());
}
};
}
fn load_files(old: &str, new: &str) -> (File, File) {
let old = syn::parse_file(old).unwrap();
let new = syn::parse_file(new).unwrap();
(old, new)
}
assert_rsx_changed![combo];
assert_rsx_changed![expr];
assert_rsx_changed![for_];
assert_rsx_changed![if_];
assert_rsx_changed![let_];
assert_rsx_changed![nested];
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/rsx-hotreload/tests/hotreload_pattern.rs | packages/rsx-hotreload/tests/hotreload_pattern.rs | #![allow(unused)]
use std::collections::HashMap;
use dioxus_core::{
internal::{
FmtSegment, FmtedSegments, HotReloadAttributeValue, HotReloadDynamicAttribute,
HotReloadDynamicNode, HotReloadLiteral, HotReloadedTemplate, NamedAttribute,
},
Template, TemplateAttribute, TemplateNode, VNode,
};
use dioxus_core_types::HotReloadingContext;
use dioxus_rsx::CallBody;
use dioxus_rsx_hotreload::{self, diff_rsx, ChangedRsx, HotReloadResult};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Parse, spanned::Spanned, token::Token, File};
#[derive(Debug)]
struct Mock;
impl HotReloadingContext for Mock {
fn map_attribute(
element_name_rust: &str,
attribute_name_rust: &str,
) -> Option<(&'static str, Option<&'static str>)> {
match element_name_rust {
"svg" => match attribute_name_rust {
"width" => Some(("width", Some("style"))),
"height" => Some(("height", Some("style"))),
_ => None,
},
_ => None,
}
}
fn map_element(element_name_rust: &str) -> Option<(&'static str, Option<&'static str>)> {
match element_name_rust {
"svg" => Some(("svg", Some("svg"))),
_ => None,
}
}
}
fn hot_reload_from_tokens(
old: TokenStream,
new: TokenStream,
) -> Option<HashMap<usize, HotReloadedTemplate>> {
let old: CallBody = syn::parse2(old).unwrap();
let new: CallBody = syn::parse2(new).unwrap();
hotreload_callbody::<Mock>(&old, &new)
}
fn can_hotreload(old: TokenStream, new: TokenStream) -> bool {
hot_reload_from_tokens(old, new).is_some()
}
fn hotreload_callbody<Ctx: HotReloadingContext>(
old: &CallBody,
new: &CallBody,
) -> Option<HashMap<usize, HotReloadedTemplate>> {
let results = HotReloadResult::new::<Ctx>(&old.body, &new.body, Default::default())?;
Some(results.templates)
}
fn callbody_to_template<Ctx: HotReloadingContext>(
old: &CallBody,
location: &'static str,
) -> Option<HotReloadedTemplate> {
let mut results = HotReloadResult::new::<Ctx>(&old.body, &old.body, Default::default())?;
Some(results.templates.remove(&0).unwrap())
}
fn base_stream() -> TokenStream {
quote! {
div {
for item in vec![1, 2, 3] {
div { "asasddasdasd" }
}
for item in vec![4, 5, 6] {
div { "asasddasdasd" }
}
}
}
}
fn base() -> CallBody {
syn::parse2(base_stream()).unwrap()
}
#[test]
fn simple_for_loop() {
let old = quote! {
div {
for item in vec![1, 2, 3] {
div { "asasddasdasd" }
}
}
};
let new_valid = quote! {
div {
for item in vec![1, 2, 3] {
div { "asasddasdasd" }
div { "123" }
}
}
};
let new_invalid = quote! {
div {
for item in vec![1, 2, 3, 4] {
div { "asasddasdasd" }
div { "123" }
}
}
};
let location = "file:line:col:0";
let old: CallBody = syn::parse2(old).unwrap();
let new_valid: CallBody = syn::parse2(new_valid).unwrap();
let new_invalid: CallBody = syn::parse2(new_invalid).unwrap();
assert!(hotreload_callbody::<Mock>(&old, &new_valid).is_some());
assert!(hotreload_callbody::<Mock>(&old, &new_invalid).is_none());
}
#[test]
fn valid_reorder() {
let old = base();
let new_valid = quote! {
div {
for item in vec![4, 5, 6] {
span { "asasddasdasd" }
span { "123" }
}
for item in vec![1, 2, 3] {
div { "asasddasdasd" }
div { "123" }
}
}
};
let new: CallBody = syn::parse2(new_valid).unwrap();
let valid = hotreload_callbody::<Mock>(&old, &new);
assert!(valid.is_some());
let templates = valid.unwrap();
// Currently we return all the templates, even if they didn't change
assert_eq!(templates.len(), 3);
let template = &templates[&0];
// It's an inversion, so we should get them in reverse
assert_eq!(
template.roots,
&[TemplateNode::Element {
tag: "div",
namespace: None,
attrs: &[],
children: &[
TemplateNode::Dynamic { id: 0 },
TemplateNode::Dynamic { id: 1 }
]
}]
);
assert_eq!(
template.dynamic_nodes,
&[
HotReloadDynamicNode::Dynamic(1),
HotReloadDynamicNode::Dynamic(0)
]
);
}
#[test]
fn valid_new_node() {
// Adding a new dynamic node should be hot reloadable as long as the text was present in the old version
// of the rsx block
let old = quote! {
div {
for item in vec![1, 2, 3] {
div { "item is {item}" }
}
}
};
let new = quote! {
div {
for item in vec![1, 2, 3] {
div { "item is {item}" }
div { "item is also {item}" }
}
}
};
let templates = hot_reload_from_tokens(old, new).unwrap();
// Currently we return all the templates, even if they didn't change
assert_eq!(templates.len(), 2);
let template = &templates[&1];
// The new dynamic node should be created from the formatted segments pool
assert_eq!(
template.dynamic_nodes,
&[
HotReloadDynamicNode::Formatted(FmtedSegments::new(vec![
FmtSegment::Literal { value: "item is " },
FmtSegment::Dynamic { id: 0 }
],)),
HotReloadDynamicNode::Formatted(FmtedSegments::new(vec![
FmtSegment::Literal {
value: "item is also "
},
FmtSegment::Dynamic { id: 0 }
],)),
]
);
}
#[test]
fn valid_new_dynamic_attribute() {
// Adding a new dynamic attribute should be hot reloadable as long as the text was present in the old version
// of the rsx block
let old = quote! {
div {
for item in vec![1, 2, 3] {
div {
class: "item is {item}"
}
}
}
};
let new = quote! {
div {
for item in vec![1, 2, 3] {
div {
class: "item is {item}"
}
div {
class: "item is also {item}"
}
}
}
};
let templates = hot_reload_from_tokens(old, new).unwrap();
// Currently we return all the templates, even if they didn't change
assert_eq!(templates.len(), 2);
let template = &templates[&1];
// We should have a new dynamic attribute
assert_eq!(
template.roots,
&[
TemplateNode::Element {
tag: "div",
namespace: None,
attrs: &[TemplateAttribute::Dynamic { id: 0 }],
children: &[]
},
TemplateNode::Element {
tag: "div",
namespace: None,
attrs: &[TemplateAttribute::Dynamic { id: 1 }],
children: &[]
}
]
);
// The new dynamic attribute should be created from the formatted segments pool
assert_eq!(
template.dynamic_attributes,
&[
HotReloadDynamicAttribute::Named(NamedAttribute::new(
"class",
None,
HotReloadAttributeValue::Literal(HotReloadLiteral::Fmted(FmtedSegments::new(
vec![
FmtSegment::Literal { value: "item is " },
FmtSegment::Dynamic { id: 0 }
],
)))
)),
HotReloadDynamicAttribute::Named(NamedAttribute::new(
"class",
None,
HotReloadAttributeValue::Literal(HotReloadLiteral::Fmted(FmtedSegments::new(
vec![
FmtSegment::Literal {
value: "item is also "
},
FmtSegment::Dynamic { id: 0 }
],
)))
)),
]
);
}
#[test]
fn valid_move_dynamic_segment_between_nodes() {
// Hot reloading should let you move around a dynamic formatted segment between nodes
let old = quote! {
div {
for item in vec![1, 2, 3] {
div {
class: "item is {item}"
}
}
}
};
let new = quote! {
div {
for item in vec![1, 2, 3] {
"item is {item}"
}
}
};
let templates = hot_reload_from_tokens(old, new).unwrap();
// Currently we return all the templates, even if they didn't change
assert_eq!(templates.len(), 2);
let template = &templates[&1];
// We should have a new dynamic node and no attributes
assert_eq!(template.roots, &[TemplateNode::Dynamic { id: 0 }]);
// The new dynamic node should be created from the formatted segments pool
assert_eq!(
template.dynamic_nodes,
&[HotReloadDynamicNode::Formatted(FmtedSegments::new(vec![
FmtSegment::Literal { value: "item is " },
FmtSegment::Dynamic { id: 0 }
])),]
);
}
#[test]
fn valid_keys() {
let a = quote! {
div {
key: "{value}",
}
};
// we can clone dynamic nodes to hot reload them
let b = quote! {
div {
key: "{value}-1234",
}
};
let hot_reload = hot_reload_from_tokens(a, b).unwrap();
assert_eq!(hot_reload.len(), 1);
let template = &hot_reload[&0];
assert_eq!(
template.key,
Some(FmtedSegments::new(vec![
FmtSegment::Dynamic { id: 0 },
FmtSegment::Literal { value: "-1234" }
]))
);
}
#[test]
fn invalid_cases() {
let new_invalid = quote! {
div {
for item in vec![1, 2, 3, 4] {
div { "asasddasdasd" }
div { "123" }
}
for item in vec![4, 5, 6] {
span { "asasddasdasd" }
span { "123" }
}
}
};
// just remove an entire for loop
let new_valid_removed = quote! {
div {
for item in vec![4, 5, 6] {
span { "asasddasdasd" }
span { "123" }
}
}
};
let new_invalid_new_dynamic_internal = quote! {
div {
for item in vec![1, 2, 3] {
div { "asasddasdasd" }
div { "123" }
}
for item in vec![4, 5, 6] {
span { "asasddasdasd" }
// this is a new dynamic node, and thus can't be hot reloaded
// Eventually we might be able to do a format like this, but not right now
span { "123 {item}" }
}
}
};
let new_invalid_added = quote! {
div {
for item in vec![1, 2, 3] {
div { "asasddasdasd" }
div { "123" }
}
for item in vec![4, 5, 6] {
span { "asasddasdasd" }
span { "123" }
}
for item in vec![7, 8, 9] {
span { "asasddasdasd" }
span { "123" }
}
}
};
let location = "file:line:col:0";
let old = base();
let new_invalid: CallBody = syn::parse2(new_invalid).unwrap();
let new_valid_removed: CallBody = syn::parse2(new_valid_removed).unwrap();
let new_invalid_new_dynamic_internal: CallBody =
syn::parse2(new_invalid_new_dynamic_internal).unwrap();
let new_invalid_added: CallBody = syn::parse2(new_invalid_added).unwrap();
assert!(hotreload_callbody::<Mock>(&old, &new_invalid).is_none());
assert!(hotreload_callbody::<Mock>(&old, &new_invalid_new_dynamic_internal).is_none());
let templates = hotreload_callbody::<Mock>(&old, &new_valid_removed).unwrap();
// we don't get the removed template back
assert_eq!(templates.len(), 2);
let template = &templates.get(&0).unwrap();
// We just completely removed the dynamic node, so it should be a "dud" path and then the placement
assert_eq!(
template.roots,
&[TemplateNode::Element {
tag: "div",
namespace: None,
attrs: &[],
children: &[TemplateNode::Dynamic { id: 0 }]
}]
);
assert_eq!(template.dynamic_nodes, &[HotReloadDynamicNode::Dynamic(1)]);
// Adding a new dynamic node should not be hot reloadable
let added = hotreload_callbody::<Mock>(&old, &new_invalid_added);
assert!(added.is_none());
}
#[test]
fn invalid_empty_rsx() {
let old_template = quote! {
div {
for item in vec![1, 2, 3, 4] {
div { "asasddasdasd" }
div { "123" }
}
for item in vec![4, 5, 6] {
span { "asasddasdasd" }
span { "123" }
}
}
};
// empty out the whole rsx block
let new_template = quote! {};
let location = "file:line:col:0";
let old_template: CallBody = syn::parse2(old_template).unwrap();
let new_template: CallBody = syn::parse2(new_template).unwrap();
assert!(hotreload_callbody::<Mock>(&old_template, &new_template).is_none());
}
#[test]
fn attributes_reload() {
let old = quote! {
div {
class: "{class}",
id: "{id}",
name: "name",
}
};
// Same order, just different contents
let new_valid_internal = quote! {
div {
id: "{id}",
name: "name",
class: "{class}"
}
};
let templates = hot_reload_from_tokens(old, new_valid_internal).unwrap();
dbg!(templates);
}
#[test]
fn template_generates() {
let old = quote! {
svg {
width: 100,
height: "100px",
"width2": 100,
"height2": "100px",
p { "hello world" }
{(0..10).map(|i| rsx! {"{i}"})}
}
div {
width: 120,
div {
height: "100px",
"width2": 130,
"height2": "100px",
for i in 0..10 {
div {
"asdasd"
}
}
}
}
};
let old: CallBody = syn::parse2(old).unwrap();
let template = callbody_to_template::<Mock>(&old, "file:line:col:0");
}
#[test]
fn diffs_complex() {
#[allow(unused, non_snake_case)]
fn Comp() -> dioxus_core::Element {
VNode::empty()
}
let old = quote! {
svg {
width: 100,
height: "100px",
"width2": 100,
"height2": "100px",
p { "hello world" }
{(0..10).map(|i| rsx! {"{i}"})},
{(0..10).map(|i| rsx! {"{i}"})},
{(0..11).map(|i| rsx! {"{i}"})},
Comp {}
}
};
// scrambling the attributes should not cause a full rebuild
let new = quote! {
div {
width: 100,
height: "100px",
"width2": 100,
"height2": "100px",
p { "hello world" }
Comp {}
{(0..10).map(|i| rsx! {"{i}"})},
{(0..10).map(|i| rsx! {"{i}"})},
{(0..11).map(|i| rsx! {"{i}"})},
}
};
let old: CallBody = syn::parse2(old).unwrap();
let new: CallBody = syn::parse2(new).unwrap();
let templates = hotreload_callbody::<Mock>(&old, &new).unwrap();
}
#[test]
fn remove_node() {
let valid = hot_reload_from_tokens(
quote! {
svg {
Comp {}
{(0..10).map(|i| rsx! {"{i}"})},
}
},
quote! {
div {
{(0..10).map(|i| rsx! {"{i}"})},
}
},
)
.unwrap();
dbg!(valid);
}
#[test]
fn if_chains() {
let valid = hot_reload_from_tokens(
quote! {
if cond {
"foo"
}
},
quote! {
if cond {
"baz"
}
},
)
.unwrap();
let very_complex_chain = hot_reload_from_tokens(
quote! {
if cond {
if second_cond {
"foo"
}
} else if othercond {
"bar"
} else {
"baz"
}
},
quote! {
if cond {
if second_cond {
span { "asasddasdasd 789" }
}
} else if othercond {
span { "asasddasdasd 123" }
} else {
span { "asasddasdas 456" }
}
},
)
.unwrap();
dbg!(very_complex_chain);
}
#[test]
fn component_bodies() {
let valid = can_hotreload(
quote! {
Comp {
"foo"
}
},
quote! {
Comp {
"baz"
}
},
);
assert!(valid);
}
// We currently don't track aliasing which means we can't allow dynamic nodes/formatted segments to be moved between scopes
#[test]
fn moving_between_scopes() {
let valid = can_hotreload(
quote! {
for x in 0..10 {
for y in 0..10 {
div { "x is {x}" }
}
}
},
quote! {
for x in 0..10 {
div { "x is {x}" }
}
},
);
assert!(!valid);
}
/// Everything reloads!
#[test]
fn kitch_sink_of_reloadability() {
let valid = hot_reload_from_tokens(
quote! {
div {
for i in 0..10 {
div { "123" }
Comp {
"foo"
}
if cond {
"foo"
}
}
}
},
quote! {
div {
"hi!"
for i in 0..10 {
div { "456" }
Comp { "bar" }
if cond {
"baz"
}
}
}
},
)
.unwrap();
dbg!(valid);
}
/// Moving nodes inbetween multiple rsx! calls currently doesn't work
/// Sad. Needs changes to core to work, and is technically flawed?
#[test]
fn entire_kitchen_sink() {
let valid = hot_reload_from_tokens(
quote! {
div {
for i in 0..10 {
div { "123" }
}
Comp {
"foo"
}
if cond {
"foo"
}
}
},
quote! {
div {
"hi!"
Comp {
for i in 0..10 {
div { "456" }
}
"bar"
if cond {
"baz"
}
}
}
},
);
assert!(valid.is_none());
}
#[test]
fn tokenstreams_and_locations() {
let valid = hot_reload_from_tokens(
quote! {
div { "hhi" }
div {
{rsx! { "hi again!" }},
for i in 0..2 {
"first"
div { "hi {i}" }
}
for i in 0..3 {
"Second"
div { "hi {i}" }
}
if false {
div { "hi again!?" }
} else if true {
div { "its cool?" }
} else {
div { "not nice !" }
}
}
},
quote! {
div { "hhi" }
div {
{rsx! { "hi again!" }},
for i in 0..2 {
"first"
div { "hi {i}" }
}
for i in 0..3 {
"Second"
div { "hi {i}" }
}
if false {
div { "hi again?" }
} else if true {
div { "cool?" }
} else {
div { "nice !" }
}
}
},
);
dbg!(valid);
}
#[test]
fn ide_testcase() {
let valid = hot_reload_from_tokens(
quote! {
div {
div { "hi!!!123 in!stant relo123a1123dasasdasdasdasd" }
for x in 0..5 {
h3 { "For loop contents" }
}
}
},
quote! {
div {
div { "hi!!!123 in!stant relo123a1123dasasdasdasdasd" }
for x in 0..5 {
h3 { "For loop contents" }
}
}
},
);
dbg!(valid);
}
#[test]
fn assigns_ids() {
let toks = quote! {
div {
div { "hi!!!123 in!stant relo123a1123dasasdasdasdasd" }
for x in 0..5 {
h3 { "For loop contents" }
}
}
};
let parsed = syn::parse2::<CallBody>(toks).unwrap();
let node = parsed.body.get_dyn_node(&[0, 1]);
dbg!(node);
}
#[test]
fn simple_start() {
let valid = can_hotreload(
//
quote! {
div {
class: "Some {one}",
id: "Something {two}",
"One"
}
},
quote! {
div {
id: "Something {two}",
class: "Some {one}",
"One"
}
},
);
assert!(valid);
}
#[test]
fn complex_cases() {
let valid = can_hotreload(
quote! {
div {
class: "Some {one}",
id: "Something {two}",
"One"
}
},
quote! {
div {
class: "Some {one}",
id: "Something else {two}",
"One"
}
},
);
assert!(valid);
}
#[test]
fn attribute_cases() {
let valid = can_hotreload(
quote! {
div {
class: "Some {one}",
id: "Something {two}",
"One"
}
},
quote! {
div {
id: "Something {two}",
"One"
}
},
);
assert!(valid);
let valid = can_hotreload(
//
quote! { div { class: 123 } },
quote! { div { class: 456 } },
);
assert!(valid);
let valid = can_hotreload(
//
quote! { div { class: 123.0 } },
quote! { div { class: 456.0 } },
);
assert!(valid);
let valid = can_hotreload(
//
quote! { div { class: "asd {123}", } },
quote! { div { class: "def", } },
);
assert!(valid);
}
#[test]
fn text_node_cases() {
let valid = can_hotreload(
//
quote! { div { "hello {world}" } },
quote! { div { "world {world}" } },
);
assert!(valid);
let valid = can_hotreload(
//
quote! { div { "hello {world}" } },
quote! { div { "world" } },
);
assert!(valid);
let valid = can_hotreload(
//
quote! { div { "hello {world}" } },
quote! { div { "world {world} {world}" } },
);
assert!(valid);
let valid = can_hotreload(
//
quote! { div { "hello" } },
quote! { div { "world {world}" } },
);
assert!(!valid);
}
#[test]
fn simple_carry() {
let a = quote! {
// start with
"thing {abc} {def}" // 1, 1, 1
"thing {def}" // 1, 0, 1
"other {hij}" // 1, 1, 1
};
let b = quote! {
// end with
"thing {def}"
"thing {abc}"
"thing {hij}"
};
let valid = can_hotreload(a, b);
assert!(valid);
}
#[test]
fn complex_carry_text() {
let a = quote! {
// start with
"thing {abc} {def}" // 1, 1, 1
"thing {abc}" // 1, 0, 1
"other {abc} {def} {hij}" // 1, 1, 1
};
let b = quote! {
// end with
"thing {abc}"
"thing {hij}"
};
let valid = can_hotreload(a, b);
assert!(valid);
}
#[test]
fn complex_carry() {
let a = quote! {
Component {
class: "thing {abc}",
other: "other {abc} {def}",
}
Component {
class: "thing {abc}",
other: "other",
}
};
let b = quote! {
// how about shuffling components, for, if, etc
Component {
class: "thing {abc}",
other: "other {abc} {def}",
}
Component {
class: "thing",
other: "other",
}
};
let valid = can_hotreload(a, b);
assert!(valid);
}
#[test]
fn component_with_lits() {
let a = quote! {
Component {
class: 123,
id: 456.789,
other: true,
blah: "hello {world}",
}
};
// changing lit values
let b = quote! {
Component {
class: 456,
id: 789.456,
other: false,
blah: "goodbye {world}",
}
};
let valid = can_hotreload(a, b);
assert!(valid);
}
#[test]
fn component_with_handlers() {
let a = quote! {
Component {
class: 123,
id: 456.789,
other: true,
blah: "hello {world}",
onclick: |e| { println!("clicked") },
}
};
// changing lit values
let b = quote! {
Component {
class: 456,
id: 789.456,
other: false,
blah: "goodbye {world}",
onclick: |e| { println!("clicked") },
}
};
let hot_reload = hot_reload_from_tokens(a, b).unwrap();
let template = hot_reload.get(&0).unwrap();
assert_eq!(
template.component_values,
&[
HotReloadLiteral::Int(456),
HotReloadLiteral::Float(789.456),
HotReloadLiteral::Bool(false),
HotReloadLiteral::Fmted(FmtedSegments::new(vec![
FmtSegment::Literal { value: "goodbye " },
FmtSegment::Dynamic { id: 0 }
])),
]
);
}
#[test]
fn component_remove_key() {
let a = quote! {
Component {
key: "{key}",
class: 123,
id: 456.789,
other: true,
dynamic1,
dynamic2,
blah: "hello {world}",
onclick: |e| { println!("clicked") },
}
};
// changing lit values
let b = quote! {
Component {
class: 456,
id: 789.456,
other: false,
dynamic1,
dynamic2,
blah: "goodbye {world}",
onclick: |e| { println!("clicked") },
}
};
let hot_reload = hot_reload_from_tokens(a, b).unwrap();
let template = hot_reload.get(&0).unwrap();
assert_eq!(
template.component_values,
&[
HotReloadLiteral::Int(456),
HotReloadLiteral::Float(789.456),
HotReloadLiteral::Bool(false),
HotReloadLiteral::Fmted(FmtedSegments::new(vec![
FmtSegment::Literal { value: "goodbye " },
FmtSegment::Dynamic { id: 1 }
]))
]
);
}
#[test]
fn component_modify_key() {
let a = quote! {
Component {
key: "{key}",
class: 123,
id: 456.789,
other: true,
dynamic1,
dynamic2,
blah1: "hello {world123}",
blah2: "hello {world}",
onclick: |e| { println!("clicked") },
}
};
// changing lit values
let b = quote! {
Component {
key: "{key}-{world}",
class: 456,
id: 789.456,
other: false,
dynamic1,
dynamic2,
blah1: "hello {world123}",
blah2: "hello {world}",
onclick: |e| { println!("clicked") },
}
};
let hot_reload = hot_reload_from_tokens(a, b).unwrap();
let template = hot_reload.get(&0).unwrap();
assert_eq!(
template.key,
Some(FmtedSegments::new(vec![
FmtSegment::Dynamic { id: 0 },
FmtSegment::Literal { value: "-" },
FmtSegment::Dynamic { id: 2 },
]))
);
assert_eq!(
template.component_values,
&[
HotReloadLiteral::Int(456),
HotReloadLiteral::Float(789.456),
HotReloadLiteral::Bool(false),
HotReloadLiteral::Fmted(FmtedSegments::new(vec![
FmtSegment::Literal { value: "hello " },
FmtSegment::Dynamic { id: 1 }
])),
HotReloadLiteral::Fmted(FmtedSegments::new(vec![
FmtSegment::Literal { value: "hello " },
FmtSegment::Dynamic { id: 2 }
]))
]
);
}
#[test]
fn duplicating_dynamic_nodes() {
let a = quote! {
div {
{some_expr}
}
};
// we can clone dynamic nodes to hot reload them
let b = quote! {
div {
{some_expr}
{some_expr}
}
};
let valid = can_hotreload(a, b);
assert!(valid);
}
#[test]
fn duplicating_dynamic_attributes() {
let a = quote! {
div {
width: value,
}
};
// we can clone dynamic nodes to hot reload them
let b = quote! {
div {
width: value,
height: value,
}
};
let valid = can_hotreload(a, b);
assert!(valid);
}
// We should be able to fill in empty nodes
#[test]
fn valid_fill_empty() {
let valid = can_hotreload(
quote! {},
quote! {
div { "x is 123" }
},
);
assert!(valid);
}
// We should be able to hot reload spreads
#[test]
fn valid_spread() {
let valid = can_hotreload(
quote! {
div {
..spread
}
},
quote! {
div {
"hello world"
}
h1 {
..spread
}
},
);
assert!(valid);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/devtools-types/src/lib.rs | packages/devtools-types/src/lib.rs | use dioxus_core::internal::HotReloadTemplateWithLocation;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use subsecond_types::JumpTable;
/// A message the hot reloading server sends to the client
#[non_exhaustive]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum DevserverMsg {
/// Attempt a hotreload
/// This includes all the templates/literals/assets/binary patches that have changed in one shot
HotReload(HotReloadMsg),
/// Starting a hotpatch
HotPatchStart,
/// The devserver is starting a full rebuild.
FullReloadStart,
/// The full reload failed.
FullReloadFailed,
/// The app should reload completely if it can
FullReloadCommand,
/// The program is shutting down completely - maybe toss up a splash screen or something?
Shutdown,
}
/// A message the client sends from the frontend to the devserver
///
/// This is used to communicate with the devserver
#[non_exhaustive]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum ClientMsg {
Log {
level: String,
messages: Vec<String>,
},
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub struct HotReloadMsg {
pub templates: Vec<HotReloadTemplateWithLocation>,
pub assets: Vec<PathBuf>,
pub ms_elapsed: u64,
pub jump_table: Option<JumpTable>,
pub for_build_id: Option<u64>,
pub for_pid: Option<u32>,
}
impl HotReloadMsg {
pub fn is_empty(&self) -> bool {
self.templates.is_empty() && self.assets.is_empty() && self.jump_table.is_none()
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/build.rs | packages/cli-opt/build.rs | fn main() {
built::write_built_file().expect("Failed to acquire build-time information");
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/css.rs | packages/cli-opt/src/css.rs | use std::{hash::Hasher, path::Path};
use anyhow::{anyhow, Context};
use codemap::SpanLoc;
use grass::OutputStyle;
use lightningcss::{
printer::PrinterOptions,
stylesheet::{MinifyOptions, ParserOptions, StyleSheet},
targets::{Browsers, Targets},
};
use manganis_core::{create_module_hash, transform_css, CssAssetOptions, CssModuleAssetOptions};
pub(crate) fn process_css(
css_options: &CssAssetOptions,
source: &Path,
output_path: &Path,
) -> anyhow::Result<()> {
let css = std::fs::read_to_string(source)?;
let css = if css_options.minified() {
// Try to minify the css. If we fail, log the error and use the unminified css
match minify_css(&css) {
Ok(minified) => minified,
Err(err) => {
tracing::error!(
"Failed to minify css; Falling back to unminified css. Error: {}",
err
);
css
}
}
} else {
css
};
std::fs::write(output_path, css).with_context(|| {
format!(
"Failed to write css to output location: {}",
output_path.display()
)
})?;
Ok(())
}
pub(crate) fn process_css_module(
css_options: &CssModuleAssetOptions,
source: &Path,
output_path: &Path,
) -> anyhow::Result<()> {
let css = std::fs::read_to_string(source)?;
// Collect the file hash name.
let mut src_name = source
.file_name()
.and_then(|x| x.to_str())
.ok_or_else(|| {
anyhow!(
"Failed to read name of css module file `{}`.",
source.display()
)
})?
.strip_suffix(".css")
.ok_or_else(|| {
anyhow!(
"Css module file `{}` should end with a `.css` suffix.",
source.display(),
)
})?
.to_string();
src_name.push('-');
let hash = create_module_hash(source);
let css = transform_css(css.as_str(), hash.as_str()).map_err(|error| {
anyhow!(
"Invalid css for file `{}`\nError:\n{}",
source.display(),
error
)
})?;
// Minify CSS
let css = if css_options.minified() {
// Try to minify the css. If we fail, log the error and use the unminified css
match minify_css(&css) {
Ok(minified) => minified,
Err(err) => {
tracing::error!(
"Failed to minify css module; Falling back to unminified css. Error: {}",
err
);
css
}
}
} else {
css
};
std::fs::write(output_path, css).with_context(|| {
format!(
"Failed to write css module to output location: {}",
output_path.display()
)
})?;
Ok(())
}
pub(crate) fn minify_css(css: &str) -> anyhow::Result<String> {
let options = ParserOptions {
error_recovery: true,
..Default::default()
};
let mut stylesheet = StyleSheet::parse(css, options).map_err(|err| err.into_owned())?;
// We load the browser list from the standard browser list file or use the browserslist default if we don't find any
// settings. Without the browser lists default, lightningcss will default to supporting only the newest versions of
// browsers.
let browsers_list = match Browsers::load_browserslist()? {
Some(browsers) => Some(browsers),
None => {
Browsers::from_browserslist(["defaults"]).expect("borwserslists should have defaults")
}
};
let targets = Targets {
browsers: browsers_list,
..Default::default()
};
stylesheet.minify(MinifyOptions {
targets,
..Default::default()
})?;
let printer = PrinterOptions {
targets,
minify: true,
..Default::default()
};
let res = stylesheet.to_css(printer)?;
Ok(res.code)
}
/// Compile scss with grass
pub(crate) fn compile_scss(
scss_options: &CssAssetOptions,
source: &Path,
) -> anyhow::Result<String> {
let style = match scss_options.minified() {
true => OutputStyle::Compressed,
false => OutputStyle::Expanded,
};
let options = grass::Options::default()
.style(style)
.quiet(false)
.logger(&ScssLogger {});
let css = grass::from_path(source, &options)
.with_context(|| format!("Failed to compile scss file: {}", source.display()))?;
Ok(css)
}
/// Process an scss/sass file into css.
pub(crate) fn process_scss(
scss_options: &CssAssetOptions,
source: &Path,
output_path: &Path,
) -> anyhow::Result<()> {
let css = compile_scss(scss_options, source)?;
let minified = minify_css(&css)?;
std::fs::write(output_path, minified).with_context(|| {
format!(
"Failed to write css to output location: {}",
output_path.display()
)
})?;
Ok(())
}
/// Logger for Grass that re-uses their StdLogger formatting but with tracing.
#[derive(Debug)]
struct ScssLogger {}
impl grass::Logger for ScssLogger {
fn debug(&self, location: SpanLoc, message: &str) {
tracing::debug!(
"{}:{} DEBUG: {}",
location.file.name(),
location.begin.line + 1,
message
);
}
fn warn(&self, location: SpanLoc, message: &str) {
tracing::warn!(
"Warning: {}\n ./{}:{}:{}",
message,
location.file.name(),
location.begin.line + 1,
location.begin.column + 1
);
}
}
/// Hash the inputs to the scss file
pub(crate) fn hash_scss(
scss_options: &CssAssetOptions,
source: &Path,
hasher: &mut impl Hasher,
) -> anyhow::Result<()> {
// Grass doesn't expose the ast for us to traverse the imports in the file. Instead of parsing scss ourselves
// we just hash the expanded version of the file for now
let css = compile_scss(scss_options, source)?;
// Hash the compiled css
hasher.write(css.as_bytes());
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/lib.rs | packages/cli-opt/src/lib.rs | use anyhow::Context;
use manganis::AssetOptions;
use manganis_core::BundledAsset;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
mod build_info;
mod css;
mod file;
mod folder;
mod hash;
mod image;
mod js;
mod json;
pub use file::process_file_to;
pub use hash::add_hash_to_asset;
/// A manifest of all assets collected from dependencies
///
/// This will be filled in primarily by incremental compilation artifacts.
#[derive(Debug, PartialEq, Default, Clone, Serialize, Deserialize)]
pub struct AssetManifest {
/// Map of bundled asset name to the asset itself
assets: BTreeMap<PathBuf, HashSet<BundledAsset>>,
}
impl AssetManifest {
/// Manually add an asset to the manifest
pub fn register_asset(
&mut self,
asset_path: &Path,
options: manganis::AssetOptions,
) -> anyhow::Result<BundledAsset> {
let output_path_str = asset_path.to_str().ok_or(anyhow::anyhow!(
"Failed to convert wasm bindgen output path to string"
))?;
let mut bundled_asset =
manganis::macro_helpers::create_bundled_asset(output_path_str, options);
add_hash_to_asset(&mut bundled_asset);
self.assets
.entry(asset_path.to_path_buf())
.or_default()
.insert(bundled_asset);
Ok(bundled_asset)
}
/// Insert an existing bundled asset to the manifest
pub fn insert_asset(&mut self, asset: BundledAsset) {
let asset_path = asset.absolute_source_path();
self.assets
.entry(asset_path.into())
.or_default()
.insert(asset);
}
/// Get any assets that are tied to a specific source file
pub fn get_assets_for_source(&self, path: &Path) -> Option<&HashSet<BundledAsset>> {
self.assets.get(path)
}
/// Get the first asset that matches the given source path
pub fn get_first_asset_for_source(&self, path: &Path) -> Option<&BundledAsset> {
self.assets
.get(path)
.and_then(|assets| assets.iter().next())
}
/// Check if the manifest contains a specific asset
pub fn contains(&self, asset: &BundledAsset) -> bool {
self.assets
.get(&PathBuf::from(asset.absolute_source_path()))
.is_some_and(|assets| assets.contains(asset))
}
/// Iterate over all the assets with unique output paths in the manifest. This will not include
/// assets that have different source paths, but the same file contents.
pub fn unique_assets(&self) -> impl Iterator<Item = &BundledAsset> {
let mut seen = HashSet::new();
self.assets
.values()
.flat_map(|assets| assets.iter())
.filter(move |asset| seen.insert(asset.bundled_path()))
}
pub fn load_from_file(path: &Path) -> anyhow::Result<Self> {
let src = std::fs::read_to_string(path)?;
serde_json::from_str(&src)
.with_context(|| format!("Failed to parse asset manifest from {path:?}\n{src}"))
}
}
/// Optimize a list of assets in parallel
pub fn optimize_all_assets(
assets_to_transfer: Vec<(PathBuf, PathBuf, AssetOptions)>,
on_optimization_start: impl FnMut(&Path, &Path, &AssetOptions) + Sync + Send,
on_optimization_end: impl FnMut(&Path, &Path, &AssetOptions) + Sync + Send,
) -> anyhow::Result<()> {
let on_optimization_start = Arc::new(RwLock::new(on_optimization_start));
let on_optimization_end = Arc::new(RwLock::new(on_optimization_end));
assets_to_transfer
.par_iter()
.try_for_each(|(from, to, options)| {
{
let mut on_optimization_start = on_optimization_start.write().unwrap();
on_optimization_start(from, to, options);
}
let res = process_file_to(options, from, to);
if let Err(err) = res.as_ref() {
tracing::error!("Failed to copy asset {from:?}: {err}");
}
{
let mut on_optimization_end = on_optimization_end.write().unwrap();
on_optimization_end(from, to, options);
}
res.map(|_| ())
})
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/build_info.rs | packages/cli-opt/src/build_info.rs | // The file has been placed there by the build script.
include!(concat!(env!("OUT_DIR"), "/built.rs"));
pub(crate) fn version() -> String {
format!(
"{} ({})",
PKG_VERSION,
GIT_COMMIT_HASH_SHORT.unwrap_or("was built without git repository")
)
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/json.rs | packages/cli-opt/src/json.rs | use std::{io::Read, path::Path};
use anyhow::Context;
pub(crate) fn minify_json(source: &str) -> anyhow::Result<String> {
// First try to parse the json
let json: serde_json::Value = serde_json::from_str(source)?;
// Then print it in a minified format
let json = serde_json::to_string(&json)?;
Ok(json)
}
pub(crate) fn process_json(source: &Path, output_path: &Path) -> anyhow::Result<()> {
let mut source_file = std::fs::File::open(source)?;
let mut source = String::new();
source_file.read_to_string(&mut source)?;
let json = match minify_json(&source) {
Ok(json) => json,
Err(err) => {
tracing::error!("Failed to minify json: {}", err);
source
}
};
std::fs::write(output_path, json).with_context(|| {
format!(
"Failed to write json to output location: {}",
output_path.display()
)
})?;
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/file.rs | packages/cli-opt/src/file.rs | use anyhow::Context;
use manganis::{AssetOptions, CssModuleAssetOptions, FolderAssetOptions};
use manganis_core::{AssetVariant, CssAssetOptions, ImageAssetOptions, JsAssetOptions};
use std::path::Path;
use crate::css::{process_css_module, process_scss};
use super::{
css::process_css, folder::process_folder, image::process_image, js::process_js,
json::process_json,
};
/// Process a specific file asset with the given options reading from the source and writing to the output path
pub fn process_file_to(
options: &AssetOptions,
source: &Path,
output_path: &Path,
) -> anyhow::Result<()> {
process_file_to_with_options(options, source, output_path, false)
}
/// Process a specific file asset with additional options
pub(crate) fn process_file_to_with_options(
options: &AssetOptions,
source: &Path,
output_path: &Path,
in_folder: bool,
) -> anyhow::Result<()> {
// If the file already exists and this is a hashed asset, then we must have a file
// with the same hash already. The hash has the file contents and options, so if we
// find a file with the same hash, we probably already created this file in the past
if output_path.exists() && options.hash_suffix() {
return Ok(());
}
if let Some(parent) = output_path.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent).context("Failed to create directory")?;
}
}
// Processing can be slow. Write to a temporary file first and then rename it to the final output path. If everything
// goes well. Without this, the user could quit in the middle of processing and the file will look complete to the
// caching system even though it is empty.
let temp_path = output_path.with_file_name(format!(
"partial.{}",
output_path
.file_name()
.unwrap_or_default()
.to_string_lossy()
));
let resolved_options = resolve_asset_options(source, options.variant());
match &resolved_options {
ResolvedAssetType::Css(options) => {
process_css(options, source, &temp_path)?;
}
ResolvedAssetType::CssModule(options) => {
process_css_module(options, source, &temp_path)?;
}
ResolvedAssetType::Scss(options) => {
process_scss(options, source, &temp_path)?;
}
ResolvedAssetType::Js(options) => {
process_js(options, source, &temp_path, !in_folder)?;
}
ResolvedAssetType::Image(options) => {
process_image(options, source, &temp_path)?;
}
ResolvedAssetType::Json => {
process_json(source, &temp_path)?;
}
ResolvedAssetType::Folder(_) => {
process_folder(source, &temp_path)?;
}
ResolvedAssetType::File => {
let source_file = std::fs::File::open(source)?;
let mut reader = std::io::BufReader::new(source_file);
let output_file = std::fs::File::create(&temp_path)?;
let mut writer = std::io::BufWriter::new(output_file);
std::io::copy(&mut reader, &mut writer).with_context(|| {
format!(
"Failed to write file to output location: {}",
temp_path.display()
)
})?;
}
}
// Remove the existing output file if it exists
if output_path.exists() {
if output_path.is_file() {
std::fs::remove_file(output_path).context("Failed to remove previous output file")?;
} else if output_path.is_dir() {
std::fs::remove_dir_all(output_path)
.context("Failed to remove previous output file")?;
}
}
// If everything was successful, rename the temp file to the final output path
std::fs::rename(temp_path, output_path)
.with_context(|| format!("Failed to rename output file to: {}", output_path.display()))?;
Ok(())
}
pub(crate) enum ResolvedAssetType {
/// An image asset
Image(ImageAssetOptions),
/// A css asset
Css(CssAssetOptions),
/// A css module asset
CssModule(CssModuleAssetOptions),
/// A SCSS asset
Scss(CssAssetOptions),
/// A javascript asset
Js(JsAssetOptions),
/// A json asset
Json,
/// A folder asset
Folder(FolderAssetOptions),
/// A generic file
File,
}
pub(crate) fn resolve_asset_options(source: &Path, options: &AssetVariant) -> ResolvedAssetType {
match options {
AssetVariant::Image(image) => ResolvedAssetType::Image(*image),
AssetVariant::Css(css) => ResolvedAssetType::Css(*css),
AssetVariant::CssModule(css) => ResolvedAssetType::CssModule(*css),
AssetVariant::Js(js) => ResolvedAssetType::Js(*js),
AssetVariant::Folder(folder) => ResolvedAssetType::Folder(*folder),
AssetVariant::Unknown => resolve_unknown_asset_options(source),
_ => {
tracing::warn!("Unknown asset options... you may need to update the Dioxus CLI. Defaulting to a generic file: {:?}", options);
resolve_unknown_asset_options(source)
}
}
}
fn resolve_unknown_asset_options(source: &Path) -> ResolvedAssetType {
match source.extension().map(|e| e.to_string_lossy()).as_deref() {
Some("scss" | "sass") => ResolvedAssetType::Scss(CssAssetOptions::default()),
Some("css") => ResolvedAssetType::Css(CssAssetOptions::default()),
Some("js") => ResolvedAssetType::Js(JsAssetOptions::default()),
Some("json") => ResolvedAssetType::Json,
Some("jpg" | "jpeg" | "png" | "webp" | "avif") => {
ResolvedAssetType::Image(ImageAssetOptions::default())
}
_ if source.is_dir() => ResolvedAssetType::Folder(FolderAssetOptions::default()),
_ => ResolvedAssetType::File,
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/js.rs | packages/cli-opt/src/js.rs | use std::hash::Hasher;
use std::path::Path;
use std::path::PathBuf;
use anyhow::Context;
use manganis_core::JsAssetOptions;
use swc_common::errors::Emitter;
use swc_common::errors::Handler;
use swc_common::input::SourceFileInput;
use swc_ecma_minifier::option::{ExtraOptions, MinifyOptions};
use swc_ecma_parser::lexer::Lexer;
use swc_ecma_parser::Parser;
use swc_ecma_transforms_base::fixer::fixer;
use swc_ecma_visit::VisitMutWith;
use std::collections::HashMap;
use anyhow::Error;
use swc_bundler::{Bundler, Config, Load, ModuleData, ModuleRecord};
use swc_common::{
errors::HANDLER, sync::Lrc, FileName, FilePathMapping, Globals, Mark, SourceMap, Span, GLOBALS,
};
use swc_ecma_ast::*;
use swc_ecma_codegen::text_writer::JsWriter;
use swc_ecma_loader::{resolvers::node::NodeModulesResolver, TargetEnv};
use swc_ecma_parser::{parse_file_as_module, Syntax};
use crate::hash::hash_file_contents;
struct TracingEmitter;
impl Emitter for TracingEmitter {
fn emit(&mut self, db: &mut swc_common::errors::DiagnosticBuilder<'_>) {
match db.level {
swc_common::errors::Level::Bug
| swc_common::errors::Level::Fatal
| swc_common::errors::Level::PhaseFatal
| swc_common::errors::Level::Error => tracing::error!("{}", db.message()),
swc_common::errors::Level::Warning
| swc_common::errors::Level::FailureNote
| swc_common::errors::Level::Cancelled => tracing::warn!("{}", db.message()),
swc_common::errors::Level::Note | swc_common::errors::Level::Help => {
tracing::trace!("{}", db.message())
}
}
}
}
/// Run a closure with the swc globals and handler set up
fn inside_handler<O>(f: impl FnOnce(&Globals, Lrc<SourceMap>) -> O) -> O {
let globals = Globals::new();
let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let handler = Handler::with_emitter_and_flags(Box::new(TracingEmitter), Default::default());
GLOBALS.set(&globals, || HANDLER.set(&handler, || f(&globals, cm)))
}
fn bundle_js_to_writer(
file: PathBuf,
bundle: bool,
minify: bool,
write_to: &mut impl std::io::Write,
) -> anyhow::Result<()> {
inside_handler(|globals, cm| {
bundle_js_to_writer_inside_handler(globals, cm, file, bundle, minify, write_to)
})
}
fn resolve_js_inside_handler(
globals: &Globals,
file: PathBuf,
bundle: bool,
cm: &Lrc<SourceMap>,
) -> anyhow::Result<Module> {
if bundle {
let node_resolver = NodeModulesResolver::new(TargetEnv::Browser, Default::default(), true);
let mut bundler = Bundler::new(
globals,
cm.clone(),
PathLoader { cm: cm.clone() },
node_resolver,
Config {
require: true,
..Default::default()
},
Box::new(Hook),
);
let mut entries = HashMap::default();
entries.insert("main".to_string(), FileName::Real(file));
let mut bundles = bundler
.bundle(entries)
.context("failed to bundle javascript with swc")?;
// Since we only inserted one entry, there should only be one bundle in the output
let bundle = bundles
.pop()
.ok_or_else(|| anyhow::anyhow!("swc did not output any bundles"))?;
Ok(bundle.module)
} else {
let fm = cm.load_file(Path::new(&file)).expect("Failed to load file");
let lexer = Lexer::new(
Default::default(),
Default::default(),
SourceFileInput::from(&*fm),
None,
);
let mut parser = Parser::new_from(lexer);
parser.parse_module().map_err(|err| {
HANDLER.with(|handler| {
let mut error = err.into_diagnostic(handler);
// swc errors panic on drop if you don't cancel them
error.cancel();
anyhow::anyhow!("{}", error.message())
})
})
}
}
fn bundle_js_to_writer_inside_handler(
globals: &Globals,
cm: Lrc<SourceMap>,
file: PathBuf,
bundle: bool,
minify: bool,
write_to: &mut impl std::io::Write,
) -> anyhow::Result<()> {
let mut module = resolve_js_inside_handler(globals, file, bundle, &cm)?;
if minify {
module = swc_ecma_minifier::optimize(
std::mem::take(&mut module).into(),
cm.clone(),
None,
None,
&MinifyOptions {
rename: true,
compress: None,
mangle: None,
..Default::default()
},
&ExtraOptions {
unresolved_mark: Mark::new(),
top_level_mark: Mark::new(),
mangle_name_cache: None,
},
)
.expect_module();
module.visit_mut_with(&mut fixer(None));
}
let mut emitter = swc_ecma_codegen::Emitter {
cfg: swc_ecma_codegen::Config::default().with_minify(minify),
cm: cm.clone(),
comments: None,
wr: Box::new(JsWriter::new(cm, "\n", write_to, None)),
};
emitter.emit_module(&module)?;
Ok(())
}
struct PathLoader {
cm: Lrc<SourceMap>,
}
impl Load for PathLoader {
fn load(&self, file: &FileName) -> anyhow::Result<ModuleData> {
let file = match file {
FileName::Real(v) => v,
_ => anyhow::bail!("Only real files are supported"),
};
let fm = self.cm.load_file(file)?;
let module = HANDLER.with(|handler| {
parse_file_as_module(
&fm,
Syntax::Es(Default::default()),
Default::default(),
None,
&mut Vec::new(),
)
.map_err(|err| {
let mut error = err.into_diagnostic(handler);
// swc errors panic on drop if you don't cancel them
error.cancel();
anyhow::anyhow!("{}", error.message())
})
.context("Failed to parse javascript")
})?;
Ok(ModuleData {
fm,
module,
helpers: Default::default(),
})
}
}
// Adapted from https://github.com/swc-project/swc/blob/624680b7896cef9d8e30bd5ff910538298016974/bindings/binding_core_node/src/bundle.rs#L266-L302
struct Hook;
impl swc_bundler::Hook for Hook {
fn get_import_meta_props(
&self,
span: Span,
module_record: &ModuleRecord,
) -> Result<Vec<KeyValueProp>, Error> {
let file_name = module_record.file_name.to_string();
Ok(vec![
KeyValueProp {
key: PropName::Ident(IdentName::new("url".into(), span)),
value: Box::new(Expr::Lit(Lit::Str(Str {
span,
raw: None,
value: file_name.into(),
}))),
},
KeyValueProp {
key: PropName::Ident(IdentName::new("main".into(), span)),
value: Box::new(if module_record.is_entry {
Expr::Member(MemberExpr {
span,
obj: Box::new(Expr::MetaProp(MetaPropExpr {
span,
kind: MetaPropKind::ImportMeta,
})),
prop: MemberProp::Ident(IdentName::new("main".into(), span)),
})
} else {
Expr::Lit(Lit::Bool(Bool { span, value: false }))
}),
},
])
}
}
pub(crate) fn process_js(
js_options: &JsAssetOptions,
source: &Path,
output_path: &Path,
bundle: bool,
) -> anyhow::Result<()> {
let mut writer = std::io::BufWriter::new(std::fs::File::create(output_path)?);
if js_options.minified() {
if let Err(err) = bundle_js_to_writer(source.to_path_buf(), bundle, true, &mut writer) {
tracing::error!("Failed to minify js. Falling back to non-minified: {err}");
} else {
return Ok(());
}
}
let mut source_file = std::fs::File::open(source)?;
std::io::copy(&mut source_file, &mut writer).with_context(|| {
format!(
"Failed to write js to output location: {}",
output_path.display()
)
})?;
Ok(())
}
fn hash_js_module(file: PathBuf, hasher: &mut impl Hasher, bundle: bool) -> anyhow::Result<()> {
inside_handler(|globals, cm| {
_ = resolve_js_inside_handler(globals, file, bundle, &cm)?;
for file in cm.files().iter() {
let hash = file.src_hash;
hasher.write(&hash.to_le_bytes());
}
Ok(())
})
}
pub(crate) fn hash_js(
js_options: &JsAssetOptions,
source: &Path,
hasher: &mut impl Hasher,
bundle: bool,
) -> anyhow::Result<()> {
if js_options.minified() {
if let Err(err) = hash_js_module(source.to_path_buf(), hasher, bundle) {
tracing::error!("Failed to minify js. Falling back to non-minified: {err}");
hash_file_contents(source, hasher)?;
}
} else {
hash_file_contents(source, hasher)?;
}
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/hash.rs | packages/cli-opt/src/hash.rs | //! Utilities for creating hashed paths to assets in Manganis. This module defines [`AssetHash`] which is used to create a hashed path to an asset in both the CLI and the macro.
use std::{
hash::{Hash, Hasher},
io::Read,
path::{Path, PathBuf},
};
use crate::{
css::hash_scss,
file::{resolve_asset_options, ResolvedAssetType},
js::hash_js,
};
use manganis::{AssetOptions, BundledAsset};
/// The opaque hash type manganis uses to identify assets. Each time an asset or asset options change, this hash will
/// change. This hash is included in the URL of the bundled asset for cache busting.
struct AssetHash {
/// We use a wrapper type here to hide the exact size of the hash so we can switch to a sha hash in a minor version bump
hash: [u8; 8],
}
impl AssetHash {
/// Create a new asset hash
const fn new(hash: u64) -> Self {
Self {
hash: hash.to_le_bytes(),
}
}
/// Get the hash bytes
pub const fn bytes(&self) -> &[u8] {
&self.hash
}
/// Create a new asset hash for a file. The input file to this function should be fully resolved
pub fn hash_file_contents(
options: &AssetOptions,
file_path: impl AsRef<Path>,
) -> anyhow::Result<AssetHash> {
hash_file(options, file_path.as_ref())
}
}
/// Process a specific file asset with the given options reading from the source and writing to the output path
fn hash_file(options: &AssetOptions, source: &Path) -> anyhow::Result<AssetHash> {
// Create a hasher
let mut hash = std::collections::hash_map::DefaultHasher::new();
options.hash(&mut hash);
// Hash the version of CLI opt
hash.write(crate::build_info::version().as_bytes());
hash_file_with_options(options, source, &mut hash, false)?;
let hash = hash.finish();
Ok(AssetHash::new(hash))
}
/// Process a specific file asset with additional options
pub(crate) fn hash_file_with_options(
options: &AssetOptions,
source: &Path,
hasher: &mut impl Hasher,
in_folder: bool,
) -> anyhow::Result<()> {
let resolved_options = resolve_asset_options(source, options.variant());
match &resolved_options {
// Scss and JS can import files during the bundling process. We need to hash
// both the files themselves and any imports they have
ResolvedAssetType::Scss(options) => {
hash_scss(options, source, hasher)?;
}
ResolvedAssetType::Js(options) => {
hash_js(options, source, hasher, !in_folder)?;
}
// Otherwise, we can just hash the file contents
ResolvedAssetType::CssModule(_)
| ResolvedAssetType::Css(_)
| ResolvedAssetType::Image(_)
| ResolvedAssetType::Json
| ResolvedAssetType::File => {
hash_file_contents(source, hasher)?;
}
// Or the folder contents recursively
ResolvedAssetType::Folder(_) => {
for file in std::fs::read_dir(source)?.flatten() {
let path = file.path();
hash_file_with_options(
// We can't reuse the options here since they contain the source variant which no
// longer applies to the nested files
//
// We don't hash nested files either since we assume the parent here is already being hashed
// (or being opted out of hashing)
&AssetOptions::builder()
.with_hash_suffix(false)
.into_asset_options(),
&path,
hasher,
true,
)?;
}
}
}
Ok(())
}
pub(crate) fn hash_file_contents(source: &Path, hasher: &mut impl Hasher) -> anyhow::Result<()> {
// Otherwise, open the file to get its contents
let mut file = std::fs::File::open(source)?;
// We add a hash to the end of the file so it is invalidated when the bundled version of the file changes
// The hash includes the file contents, the options, and the version of manganis. From the macro, we just
// know the file contents, so we only include that hash
let mut buffer = [0; 8192];
loop {
let read = file.read(&mut buffer)?;
if read == 0 {
break;
}
hasher.write(&buffer[..read]);
}
Ok(())
}
/// Add a hash to the asset, or log an error if it fails
pub fn add_hash_to_asset(asset: &mut BundledAsset) {
let source = asset.absolute_source_path();
match AssetHash::hash_file_contents(asset.options(), source) {
Ok(hash) => {
let options = *asset.options();
// Set the bundled path to the source path with the hash appended before the extension
let source_path = PathBuf::from(source);
let Some(file_name) = source_path.file_name() else {
tracing::error!("Failed to get file name from path: {source}");
return;
};
// The output extension path is the extension set by the options
// or the extension of the source file if we don't recognize the file
let mut ext = asset.options().extension().map(Into::into).or_else(|| {
source_path
.extension()
.map(|ext| ext.to_string_lossy().to_string())
});
// Rewrite scss as css
if let Some("scss" | "sass") = ext.as_deref() {
ext = Some("css".to_string());
}
let hash = hash.bytes();
let hash = hash
.iter()
.map(|byte| format!("{byte:x}"))
.collect::<String>();
let file_stem = source_path.file_stem().unwrap_or(file_name);
let mut bundled_path = if asset.options().hash_suffix() {
PathBuf::from(format!("{}-dxh{hash}", file_stem.to_string_lossy()))
} else {
PathBuf::from(file_stem)
};
if let Some(ext) = ext {
// Push the extension to the bundled path. There may be multiple extensions (e.g. .js.map)
// with one left after the file_stem is extracted above so we need to push the extension
// instead of setting it
bundled_path.as_mut_os_string().push(format!(".{ext}"));
}
let bundled_path = bundled_path.to_string_lossy().to_string();
*asset = BundledAsset::new(source, &bundled_path, options);
}
Err(err) => {
tracing::error!("Failed to hash asset {source}: {err}");
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/folder.rs | packages/cli-opt/src/folder.rs | use std::path::Path;
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use crate::file::process_file_to_with_options;
/// Process a folder, optimizing and copying all assets into the output folder
pub fn process_folder(source: &Path, output_folder: &Path) -> anyhow::Result<()> {
// Create the folder
std::fs::create_dir_all(output_folder)?;
// Then optimize children
let files: Vec<_> = std::fs::read_dir(source)
.into_iter()
.flatten()
.flatten()
.collect();
files.par_iter().try_for_each(|file| {
let file = file.path();
let metadata = file.metadata()?;
let output_path = output_folder.join(file.strip_prefix(source)?);
if metadata.is_dir() {
process_folder(&file, &output_path)
} else {
process_file_minimal(&file, &output_path)
}
})?;
Ok(())
}
/// Optimize a file without changing any of its contents significantly (e.g. by changing the extension)
fn process_file_minimal(input_path: &Path, output_path: &Path) -> anyhow::Result<()> {
process_file_to_with_options(
&manganis_core::AssetOptions::builder().into_asset_options(),
input_path,
output_path,
true,
)?;
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/image/png.rs | packages/cli-opt/src/image/png.rs | use std::{io::BufWriter, path::Path};
use image::DynamicImage;
pub(crate) fn compress_png(image: DynamicImage, output_location: &Path) {
// Image loading/saving is outside scope of this library
let width = image.width() as usize;
let height = image.height() as usize;
let bitmap: Vec<_> = image
.into_rgba8()
.pixels()
.map(|px| imagequant::RGBA::new(px[0], px[1], px[2], px[3]))
.collect();
// Configure the library
let mut liq = imagequant::new();
liq.set_speed(5).unwrap();
liq.set_quality(0, 99).unwrap();
// Describe the bitmap
let mut img = liq.new_image(&bitmap[..], width, height, 0.0).unwrap();
// The magic happens in quantize()
let mut res = match liq.quantize(&mut img) {
Ok(res) => res,
Err(err) => panic!("Quantization failed, because: {err:?}"),
};
let (palette, pixels) = res.remapped(&mut img).unwrap();
let file = std::fs::File::create(output_location).unwrap();
let w = &mut BufWriter::new(file);
let mut encoder = png::Encoder::new(w, width as u32, height as u32);
encoder.set_color(png::ColorType::Rgba);
let mut flattened_palette = Vec::new();
let mut alpha_palette = Vec::new();
for px in palette {
flattened_palette.push(px.r);
flattened_palette.push(px.g);
flattened_palette.push(px.b);
alpha_palette.push(px.a);
}
encoder.set_palette(flattened_palette);
encoder.set_trns(alpha_palette);
encoder.set_depth(png::BitDepth::Eight);
encoder.set_color(png::ColorType::Indexed);
encoder.set_compression(png::Compression::Best);
let mut writer = encoder.write_header().unwrap();
writer.write_image_data(&pixels).unwrap();
writer.finish().unwrap();
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/image/mod.rs | packages/cli-opt/src/image/mod.rs | use std::path::Path;
use anyhow::Context;
use jpg::compress_jpg;
use manganis_core::{ImageAssetOptions, ImageFormat, ImageSize};
use png::compress_png;
mod jpg;
mod png;
pub(crate) fn process_image(
image_options: &ImageAssetOptions,
source: &Path,
output_path: &Path,
) -> anyhow::Result<()> {
let mut image = image::ImageReader::new(std::io::Cursor::new(&*std::fs::read(source)?))
.with_guessed_format()
.context("Failed to guess image format")?
.decode();
if let Ok(image) = &mut image {
if let ImageSize::Manual { width, height } = image_options.size() {
*image = image.resize_exact(width, height, image::imageops::FilterType::Lanczos3);
}
}
match (image, image_options.format()) {
(image, ImageFormat::Png) => {
compress_png(image.context("Failed to decode image")?, output_path);
}
(image, ImageFormat::Jpg) => {
compress_jpg(image.context("Failed to decode image")?, output_path)?;
}
(Ok(image), ImageFormat::Avif) => {
if let Err(error) = image.save(output_path) {
tracing::error!("Failed to save avif image: {} with path {}. You must have the avif feature enabled to use avif assets", error, output_path.display());
}
}
(Ok(image), ImageFormat::Webp) => {
if let Err(err) = image.save(output_path) {
tracing::error!("Failed to save webp image: {}. You must have the avif feature enabled to use webp assets", err);
}
}
(Ok(image), _) => {
image.save(output_path).with_context(|| {
format!(
"Failed to save image (from {}) with path {}",
source.display(),
output_path.display()
)
})?;
}
// If we can't decode the image or it is of an unknown type, we just copy the file
_ => {
let source_file = std::fs::File::open(source).context("Failed to open source file")?;
let mut reader = std::io::BufReader::new(source_file);
let output_file = std::fs::File::create(output_path).with_context(|| {
format!("Failed to create output file: {}", output_path.display())
})?;
let mut writer = std::io::BufWriter::new(output_file);
std::io::copy(&mut reader, &mut writer)
.with_context(|| {
format!(
"Failed to write image to output location: {}",
output_path.display()
)
})
.context("Failed to copy image data")?;
}
}
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/cli-opt/src/image/jpg.rs | packages/cli-opt/src/image/jpg.rs | use image::{DynamicImage, EncodableLayout};
use std::{
io::{BufWriter, Write},
path::Path,
};
pub(crate) fn compress_jpg(image: DynamicImage, output_location: &Path) -> anyhow::Result<()> {
let mut comp = mozjpeg::Compress::new(mozjpeg::ColorSpace::JCS_EXT_RGBX);
let width = image.width() as usize;
let height = image.height() as usize;
comp.set_size(width, height);
let mut comp = comp.start_compress(Vec::new())?; // any io::Write will work
comp.write_scanlines(image.to_rgba8().as_bytes())?;
let jpeg_bytes = comp.finish()?;
let file = std::fs::File::create(output_location)?;
let w = &mut BufWriter::new(file);
w.write_all(&jpeg_bytes)?;
Ok(())
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/lib.rs | packages/signals/src/lib.rs | #![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/79236386")]
#![doc(html_favicon_url = "https://avatars.githubusercontent.com/u/79236386")]
#![warn(missing_docs)]
#![allow(clippy::type_complexity)]
mod copy_value;
pub use copy_value::*;
pub(crate) mod signal;
pub use signal::*;
mod map;
pub use map::*;
mod map_mut;
pub use map_mut::*;
mod set_compare;
pub use set_compare::*;
mod memo;
pub use memo::*;
mod global;
pub use global::*;
mod impls;
pub use generational_box::{
AnyStorage, BorrowError, BorrowMutError, Owner, Storage, SyncStorage, UnsyncStorage,
};
mod read;
pub use read::*;
mod write;
pub use write::*;
mod props;
pub use props::*;
pub mod warnings;
mod boxed;
pub use boxed::*;
/// A macro to define extension methods for signal types that call the method with either `with` or `with_mut` depending on the mutability of self.
macro_rules! ext_methods {
(
$(
$(#[$meta:meta])*
fn $name:ident $(<$($gen:tt),*>)? (&$($self:ident)+ $(, $arg_name:ident: $arg_type:ty )* ) $(-> $ret:ty)? = $expr:expr;
)*
) => {
$(
$(#[$meta])*
#[track_caller]
fn $name$(<$($gen),*>)? (& $($self)+ $(, $arg_name: $arg_type )* ) $(-> $ret)?
{
ext_methods!(@with $($self)+, $($arg_name),*; $expr)
}
)*
};
(@with mut $self:ident, $($arg_name:ident),*; $expr:expr) => {
$self.with_mut(|_self| ($expr)(_self, $($arg_name),*))
};
(@with $self:ident, $($arg_name:ident),*; $expr:expr) => {
$self.with(|_self| ($expr)(_self, $($arg_name),*))
};
}
pub(crate) use ext_methods;
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/set_compare.rs | packages/signals/src/set_compare.rs | use crate::{write::WritableExt, ReadableExt};
use std::hash::Hash;
use dioxus_core::ReactiveContext;
use futures_util::StreamExt;
use generational_box::{Storage, UnsyncStorage};
use crate::{CopyValue, ReadSignal, Signal, SignalData};
use rustc_hash::FxHashMap;
/// An object that can efficiently compare a value to a set of values.
pub struct SetCompare<R, S: 'static = UnsyncStorage> {
subscribers: CopyValue<FxHashMap<R, Signal<bool, S>>>,
}
impl<R: Eq + Hash + 'static> SetCompare<R> {
/// Creates a new [`SetCompare`] which efficiently tracks when a value changes to check if it is equal to a set of values.
///
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::Memo`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
#[track_caller]
pub fn new(f: impl FnMut() -> R + 'static) -> SetCompare<R> {
Self::new_maybe_sync(f)
}
}
impl<R: Eq + Hash + 'static, S: Storage<SignalData<bool>> + 'static> SetCompare<R, S> {
/// Creates a new [`SetCompare`] that may be `Sync + Send` which efficiently tracks when a value changes to check if it is equal to a set of values.
///
/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::Memo`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
#[track_caller]
pub fn new_maybe_sync(mut f: impl FnMut() -> R + 'static) -> SetCompare<R, S> {
let subscribers: CopyValue<FxHashMap<R, Signal<bool, S>>> =
CopyValue::new(FxHashMap::default());
let mut previous = CopyValue::new(None);
let mut recompute = move || {
let subscribers = subscribers.read();
let mut previous = previous.write();
if let Some(previous) = previous.take() {
if let Some(mut value) = subscribers.get(&previous).cloned() {
*value.write() = false;
}
}
let current = f();
if let Some(mut value) = subscribers.get(¤t).cloned() {
*value.write() = true;
}
*previous = Some(current);
};
let (rc, mut changed) = ReactiveContext::new();
dioxus_core::spawn(async move {
loop {
// Recompute the value
rc.reset_and_run_in(&mut recompute);
// Wait for context to change
let _ = changed.next().await;
}
});
SetCompare { subscribers }
}
}
impl<R: Eq + Hash + 'static> SetCompare<R> {
/// Returns a signal which is true when the value is equal to the value passed to this function.
pub fn equal(&mut self, value: R) -> ReadSignal<bool> {
let subscribers = self.subscribers.write();
match subscribers.get(&value) {
Some(&signal) => signal.into(),
None => {
drop(subscribers);
let mut subscribers = self.subscribers.write();
let signal = Signal::new_maybe_sync(false);
subscribers.insert(value, signal);
signal.into()
}
}
}
}
impl<R, S: Storage<SignalData<bool>>> PartialEq for SetCompare<R, S> {
fn eq(&self, other: &Self) -> bool {
self.subscribers == other.subscribers
}
}
impl<R, S: Storage<SignalData<bool>>> Clone for SetCompare<R, S> {
fn clone(&self) -> Self {
*self
}
}
impl<R, S: Storage<SignalData<bool>>> Copy for SetCompare<R, S> {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/write.rs | packages/signals/src/write.rs | use std::{
collections::{HashMap, HashSet},
ops::{Deref, DerefMut, IndexMut},
};
use generational_box::{AnyStorage, UnsyncStorage};
use crate::{ext_methods, read::Readable, read::ReadableExt, MappedMutSignal, WriteSignal};
/// A reference to a value that can be written to.
#[allow(type_alias_bounds)]
pub type WritableRef<'a, T: Writable, O = <T as Readable>::Target> =
WriteLock<'a, O, <T as Readable>::Storage, <T as Writable>::WriteMetadata>;
/// A trait for states that can be written to like [`crate::Signal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API.
///
/// # Example
/// ```rust
/// # use dioxus::prelude::*;
/// enum MyEnum {
/// String(String),
/// Number(i32),
/// }
///
/// fn MyComponent(mut count: Signal<MyEnum>) -> Element {
/// rsx! {
/// button {
/// onclick: move |_| {
/// // You can use any methods from the Writable trait on Signals
/// match &mut *count.write() {
/// MyEnum::String(s) => s.push('a'),
/// MyEnum::Number(n) => *n += 1,
/// }
/// },
/// "Add value"
/// }
/// }
/// }
/// ```
pub trait Writable: Readable {
/// Additional data associated with the write reference.
type WriteMetadata;
/// Try to get a mutable reference to the value without checking the lifetime. This will update any subscribers.
///
/// NOTE: This method is completely safe because borrow checking is done at runtime.
fn try_write_unchecked(
&self,
) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError>
where
Self::Target: 'static;
}
/// A mutable reference to a writable value. This reference acts similarly to [`std::cell::RefMut`], but it has extra debug information
/// and integrates with the reactive system to automatically update dependents.
///
/// [`WriteLock`] 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 [`WriteLock::deref_mut`].
///
/// # Example
/// ```rust
/// # use dioxus::prelude::*;
/// fn app() -> Element {
/// let mut value = use_signal(|| String::from("hello"));
///
/// rsx! {
/// button {
/// onclick: move |_| {
/// 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");
/// },
/// "Click to add world to the string"
/// }
/// div { "{value}" }
/// }
/// }
/// ```
///
/// ## Matching on WriteLock
///
/// You need to get the inner mutable reference with [`WriteLock::deref_mut`] before you match the inner value. If you try to match
/// without calling [`WriteLock::deref_mut`], you will get an error like this:
///
/// ```compile_fail
/// # use dioxus::prelude::*;
/// #[derive(Debug)]
/// enum Colors {
/// Red(u32),
/// Green
/// }
/// fn app() -> Element {
/// let mut value = use_signal(|| Colors::Red(0));
///
/// rsx! {
/// button {
/// onclick: move |_| {
/// let mut mutable_reference = value.write();
///
/// match mutable_reference {
/// // Since we are matching on the `Write` type instead of &mut Colors, we can't match on the enum directly
/// Colors::Red(brightness) => *brightness += 1,
/// Colors::Green => {}
/// }
/// },
/// "Click to add brightness to the red color"
/// }
/// div { "{value:?}" }
/// }
/// }
/// ```
///
/// ```text
/// error[E0308]: mismatched types
/// --> src/main.rs:18:21
/// |
/// 16 | match mutable_reference {
/// | ----------------- this expression has type `dioxus::prelude::Write<'_, Colors>`
/// 17 | // Since we are matching on the `Write` t...
/// 18 | Colors::Red(brightness) => *brightness += 1,
/// | ^^^^^^^^^^^^^^^^^^^^^^^ expected `Write<'_, Colors>`, found `Colors`
/// |
/// = note: expected struct `dioxus::prelude::Write<'_, Colors, >`
/// 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 dioxus::prelude::*;
/// #[derive(Debug)]
/// enum Colors {
/// Red(u32),
/// Green
/// }
/// fn app() -> Element {
/// let mut value = use_signal(|| Colors::Red(0));
///
/// rsx! {
/// button {
/// onclick: move |_| {
/// let mut mutable_reference = value.write();
///
/// // DerefMut converts the `Write` into a `&mut Colors`
/// match mutable_reference.deref_mut() {
/// // Now we can match on the inner value
/// Colors::Red(brightness) => *brightness += 1,
/// Colors::Green => {}
/// }
/// },
/// "Click to add brightness to the red color"
/// }
/// div { "{value:?}" }
/// }
/// }
/// ```
///
/// ## Generics
/// - T is the current type of the write
/// - S is the storage type of the signal. This type determines if the signal is local to the current thread, or it can be shared across threads.
/// - D is the additional data associated with the write reference. This is used by signals to track when the write is dropped
pub struct WriteLock<'a, T: ?Sized + 'a, S: AnyStorage = UnsyncStorage, D = ()> {
write: S::Mut<'a, T>,
data: D,
}
impl<'a, T: ?Sized, S: AnyStorage> WriteLock<'a, T, S> {
/// Create a new write reference
pub fn new(write: S::Mut<'a, T>) -> Self {
Self { write, data: () }
}
}
impl<'a, T: ?Sized, S: AnyStorage, D> WriteLock<'a, T, S, D> {
/// Create a new write reference with additional data.
pub fn new_with_metadata(write: S::Mut<'a, T>, data: D) -> Self {
Self { write, data }
}
/// Get the inner value of the write reference.
pub fn into_inner(self) -> S::Mut<'a, T> {
self.write
}
/// Get the additional data associated with the write reference.
pub fn data(&self) -> &D {
&self.data
}
/// Split into the inner value and the additional data.
pub fn into_parts(self) -> (S::Mut<'a, T>, D) {
(self.write, self.data)
}
/// Map the metadata of the write reference to a new type.
pub fn map_metadata<O>(self, f: impl FnOnce(D) -> O) -> WriteLock<'a, T, S, O> {
WriteLock {
write: self.write,
data: f(self.data),
}
}
/// Map the mutable reference to the signal's value to a new type.
pub fn map<O: ?Sized>(
myself: Self,
f: impl FnOnce(&mut T) -> &mut O,
) -> WriteLock<'a, O, S, D> {
let Self { write, data, .. } = myself;
WriteLock {
write: S::map_mut(write, f),
data,
}
}
/// Try to map the mutable reference to the signal's value to a new type
pub fn filter_map<O: ?Sized>(
myself: Self,
f: impl FnOnce(&mut T) -> Option<&mut O>,
) -> Option<WriteLock<'a, O, S, D>> {
let Self { write, data, .. } = myself;
let write = S::try_map_mut(write, f);
write.map(|write| WriteLock { write, data })
}
/// Downcast the lifetime of the mutable reference to the signal's value.
///
/// 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.
pub fn downcast_lifetime<'b>(mut_: Self) -> WriteLock<'b, T, S, D>
where
'a: 'b,
{
WriteLock {
write: S::downcast_lifetime_mut(mut_.write),
data: mut_.data,
}
}
}
impl<T, S, D> Deref for WriteLock<'_, T, S, D>
where
S: AnyStorage,
T: ?Sized,
{
type Target = T;
fn deref(&self) -> &Self::Target {
&self.write
}
}
impl<T, S, D> DerefMut for WriteLock<'_, T, S, D>
where
S: AnyStorage,
T: ?Sized,
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.write
}
}
/// An extension trait for [`Writable`] that provides some convenience methods.
pub trait WritableExt: Writable {
/// Get a mutable reference to the value. If the value has been dropped, this will panic.
#[track_caller]
fn write(&mut self) -> WritableRef<'_, Self>
where
Self::Target: 'static,
{
self.try_write().unwrap()
}
/// Try to get a mutable reference to the value.
#[track_caller]
fn try_write(&mut self) -> Result<WritableRef<'_, Self>, generational_box::BorrowMutError>
where
Self::Target: 'static,
{
self.try_write_unchecked().map(WriteLock::downcast_lifetime)
}
/// Get a mutable reference to the value without checking the lifetime. This will update any subscribers.
///
/// NOTE: This method is completely safe because borrow checking is done at runtime.
#[track_caller]
fn write_unchecked(&self) -> WritableRef<'static, Self>
where
Self::Target: 'static,
{
self.try_write_unchecked().unwrap()
}
/// Map the references and mutable references of the writable value to a new type. This lets you provide a view
/// into the writable value without creating a new signal or cloning the value.
///
/// Anything that subscribes to the writable value will be rerun whenever the original value changes or you write to this
/// scoped value, even if the view does not change. If you want to memorize the view, you can use a [`crate::Memo`] instead.
/// For fine grained scoped updates, use stores instead
///
/// # Example
/// ```rust
/// # use dioxus::prelude::*;
/// fn List(list: Signal<Vec<i32>>) -> Element {
/// rsx! {
/// for index in 0..list.len() {
/// // We can use the `map` method to provide a view into the single item in the list that the child component will render
/// Item { item: list.map_mut(move |v| &v[index], move |v| &mut v[index]) }
/// }
/// }
/// }
///
/// // The child component doesn't need to know that the mapped value is coming from a list
/// #[component]
/// fn Item(item: WriteSignal<i32>) -> Element {
/// rsx! {
/// button {
/// onclick: move |_| *item.write() += 1,
/// "{item}"
/// }
/// }
/// }
/// ```
fn map_mut<O, F, FMut>(self, f: F, f_mut: FMut) -> MappedMutSignal<O, Self, F, FMut>
where
Self: Sized,
O: ?Sized,
F: Fn(&Self::Target) -> &O,
FMut: Fn(&mut Self::Target) -> &mut O,
{
MappedMutSignal::new(self, f, f_mut)
}
/// Run a function with a mutable reference to the value. If the value has been dropped, this will panic.
#[track_caller]
fn with_mut<O>(&mut self, f: impl FnOnce(&mut Self::Target) -> O) -> O
where
Self::Target: 'static,
{
f(&mut *self.write())
}
/// Set the value of the signal. This will trigger an update on all subscribers.
#[track_caller]
fn set(&mut self, value: Self::Target)
where
Self::Target: Sized + 'static,
{
*self.write() = value;
}
/// Invert the boolean value of the signal. This will trigger an update on all subscribers.
#[track_caller]
fn toggle(&mut self)
where
Self::Target: std::ops::Not<Output = Self::Target> + Clone + 'static,
{
let inverted = !(*self.peek()).clone();
self.set(inverted);
}
/// Index into the inner value and return a reference to the result.
#[track_caller]
fn index_mut<I>(
&mut self,
index: I,
) -> WritableRef<'_, Self, <Self::Target as std::ops::Index<I>>::Output>
where
Self::Target: std::ops::IndexMut<I> + 'static,
{
WriteLock::map(self.write(), |v| v.index_mut(index))
}
/// Takes the value out of the Signal, leaving a Default in its place.
#[track_caller]
fn take(&mut self) -> Self::Target
where
Self::Target: Default + 'static,
{
self.with_mut(std::mem::take)
}
/// Replace the value in the Signal, returning the old value.
#[track_caller]
fn replace(&mut self, value: Self::Target) -> Self::Target
where
Self::Target: Sized + 'static,
{
self.with_mut(|v| std::mem::replace(v, value))
}
}
impl<W: Writable + ?Sized> WritableExt for W {}
/// An extension trait for [`Writable`] values that can be boxed into a trait object.
pub trait WritableBoxedExt: Writable<Storage = UnsyncStorage> {
/// Box the writable value into a trait object. This is useful for passing around writable values without knowing their concrete type.
fn boxed_mut(self) -> WriteSignal<Self::Target>
where
Self: Sized + 'static,
{
WriteSignal::new(self)
}
}
impl<T: Writable<Storage = UnsyncStorage> + 'static> WritableBoxedExt for T {
fn boxed_mut(self) -> WriteSignal<Self::Target> {
WriteSignal::new(self)
}
}
/// An extension trait for [`Writable<Option<T>>`]` that provides some convenience methods.
pub trait WritableOptionExt<T>: Writable<Target = Option<T>> {
/// Gets the value out of the Option, or inserts the given value if the Option is empty.
#[track_caller]
fn get_or_insert(&mut self, default: T) -> WritableRef<'_, Self, T>
where
T: 'static,
{
self.get_or_insert_with(|| default)
}
/// Gets the value out of the Option, or inserts the value returned by the given function if the Option is empty.
#[track_caller]
fn get_or_insert_with(&mut self, default: impl FnOnce() -> T) -> WritableRef<'_, Self, T>
where
T: 'static,
{
let is_none = self.read().is_none();
if is_none {
self.with_mut(|v| *v = Some(default()));
WriteLock::map(self.write(), |v| v.as_mut().unwrap())
} else {
WriteLock::map(self.write(), |v| v.as_mut().unwrap())
}
}
/// Attempts to write the inner value of the Option.
#[track_caller]
fn as_mut(&mut self) -> Option<WritableRef<'_, Self, T>>
where
T: 'static,
{
WriteLock::filter_map(self.write(), |v: &mut Option<T>| v.as_mut())
}
}
impl<T, W> WritableOptionExt<T> for W where W: Writable<Target = Option<T>> {}
/// An extension trait for [`Writable<Vec<T>>`] that provides some convenience methods.
pub trait WritableVecExt<T>: Writable<Target = Vec<T>> {
/// Pushes a new value to the end of the vector.
#[track_caller]
fn push(&mut self, value: T)
where
T: 'static,
{
self.with_mut(|v| v.push(value))
}
/// Pops the last value from the vector.
#[track_caller]
fn pop(&mut self) -> Option<T>
where
T: 'static,
{
self.with_mut(|v| v.pop())
}
/// Inserts a new value at the given index.
#[track_caller]
fn insert(&mut self, index: usize, value: T)
where
T: 'static,
{
self.with_mut(|v| v.insert(index, value))
}
/// Removes the value at the given index.
#[track_caller]
fn remove(&mut self, index: usize) -> T
where
T: 'static,
{
self.with_mut(|v| v.remove(index))
}
/// Clears the vector, removing all values.
#[track_caller]
fn clear(&mut self)
where
T: 'static,
{
self.with_mut(|v| v.clear())
}
/// Extends the vector with the given iterator.
#[track_caller]
fn extend(&mut self, iter: impl IntoIterator<Item = T>)
where
T: 'static,
{
self.with_mut(|v| v.extend(iter))
}
/// Truncates the vector to the given length.
#[track_caller]
fn truncate(&mut self, len: usize)
where
T: 'static,
{
self.with_mut(|v| v.truncate(len))
}
/// Swaps two values in the vector.
#[track_caller]
fn swap_remove(&mut self, index: usize) -> T
where
T: 'static,
{
self.with_mut(|v| v.swap_remove(index))
}
/// Retains only the values that match the given predicate.
#[track_caller]
fn retain(&mut self, f: impl FnMut(&T) -> bool)
where
T: 'static,
{
self.with_mut(|v| v.retain(f))
}
/// Splits the vector into two at the given index.
#[track_caller]
fn split_off(&mut self, at: usize) -> Vec<T>
where
T: 'static,
{
self.with_mut(|v| v.split_off(at))
}
/// Try to mutably get an element from the vector.
#[track_caller]
fn get_mut(&mut self, index: usize) -> Option<WritableRef<'_, Self, T>>
where
T: 'static,
{
WriteLock::filter_map(self.write(), |v: &mut Vec<T>| v.get_mut(index))
}
/// Gets an iterator over the values of the vector.
#[track_caller]
fn iter_mut(&mut self) -> WritableValueIterator<'_, Self>
where
Self: Sized + Clone,
{
WritableValueIterator {
index: 0,
value: self,
}
}
}
/// An iterator over the values of a [`Writable<Vec<T>>`].
pub struct WritableValueIterator<'a, R> {
index: usize,
value: &'a mut R,
}
impl<'a, T: 'static, R: Writable<Target = Vec<T>>> Iterator for WritableValueIterator<'a, R> {
type Item = WritableRef<'a, R, T>;
fn next(&mut self) -> Option<Self::Item> {
let index = self.index;
self.index += 1;
WriteLock::filter_map(
self.value.try_write_unchecked().unwrap(),
|v: &mut Vec<T>| v.get_mut(index),
)
.map(WriteLock::downcast_lifetime)
}
}
impl<W, T> WritableVecExt<T> for W where W: Writable<Target = Vec<T>> {}
/// An extension trait for [`Writable<String>`] that provides some convenience methods.
pub trait WritableStringExt: Writable<Target = String> {
ext_methods! {
/// Pushes a character to the end of the string.
fn push_str(&mut self, s: &str) = String::push_str;
/// Pushes a character to the end of the string.
fn push(&mut self, c: char) = String::push;
/// Pops a character from the end of the string.
fn pop(&mut self) -> Option<char> = String::pop;
/// Inserts a string at the given index.
fn insert_str(&mut self, idx: usize, s: &str) = String::insert_str;
/// Inserts a character at the given index.
fn insert(&mut self, idx: usize, c: char) = String::insert;
/// Remove a character at the given index
fn remove(&mut self, idx: usize) -> char = String::remove;
/// Replace a range of the string with the given string.
fn replace_range(&mut self, range: impl std::ops::RangeBounds<usize>, replace_with: &str) = String::replace_range;
/// Clears the string, removing all characters.
fn clear(&mut self) = String::clear;
/// Extends the string with the given iterator of characters.
fn extend(&mut self, iter: impl IntoIterator<Item = char>) = String::extend;
/// Truncates the string to the given length.
fn truncate(&mut self, len: usize) = String::truncate;
/// Splits the string off at the given index, returning the tail as a new string.
fn split_off(&mut self, at: usize) -> String = String::split_off;
}
}
impl<W> WritableStringExt for W where W: Writable<Target = String> {}
/// An extension trait for [`Writable<HashMap<K, V, H>>`] that provides some convenience methods.
pub trait WritableHashMapExt<K: 'static, V: 'static, H: 'static>:
Writable<Target = HashMap<K, V, H>>
{
ext_methods! {
/// Clears the map, removing all key-value pairs.
fn clear(&mut self) = HashMap::clear;
/// Retains only the key-value pairs that match the given predicate.
fn retain(&mut self, f: impl FnMut(&K, &mut V) -> bool) = HashMap::retain;
}
/// Inserts a key-value pair into the map. If the key was already present, the old value is returned.
#[track_caller]
fn insert(&mut self, k: K, v: V) -> Option<V>
where
K: std::cmp::Eq + std::hash::Hash,
H: std::hash::BuildHasher,
{
self.with_mut(|map: &mut HashMap<K, V, H>| map.insert(k, v))
}
/// Extends the map with the key-value pairs from the given iterator.
#[track_caller]
fn extend(&mut self, iter: impl IntoIterator<Item = (K, V)>)
where
K: std::cmp::Eq + std::hash::Hash,
H: std::hash::BuildHasher,
{
self.with_mut(|map: &mut HashMap<K, V, H>| map.extend(iter))
}
/// Removes a key from the map, returning the value at the key if the key was previously in the map.
#[track_caller]
fn remove(&mut self, k: &K) -> Option<V>
where
K: std::cmp::Eq + std::hash::Hash,
H: std::hash::BuildHasher,
{
self.with_mut(|map: &mut HashMap<K, V, H>| map.remove(k))
}
/// Get a mutable reference to the value at the given key.
#[track_caller]
fn get_mut(&mut self, k: &K) -> Option<WritableRef<'_, Self, V>>
where
K: std::cmp::Eq + std::hash::Hash,
H: std::hash::BuildHasher,
{
WriteLock::filter_map(self.write(), |map: &mut HashMap<K, V, H>| map.get_mut(k))
}
}
impl<K: 'static, V: 'static, H: 'static, R> WritableHashMapExt<K, V, H> for R where
R: Writable<Target = HashMap<K, V, H>>
{
}
/// An extension trait for [`Writable<HashSet<V, H>>`] that provides some convenience methods.
pub trait WritableHashSetExt<V: 'static, H: 'static>: Writable<Target = HashSet<V, H>> {
ext_methods! {
/// Clear the hash set.
fn clear(&mut self) = HashSet::clear;
/// Retain only the elements specified by the predicate.
fn retain(&mut self, f: impl FnMut(&V) -> bool) = HashSet::retain;
}
/// Inserts a value into the set. Returns true if the value was not already present.
#[track_caller]
fn insert(&mut self, k: V) -> bool
where
V: std::cmp::Eq + std::hash::Hash,
H: std::hash::BuildHasher,
{
self.with_mut(|set| set.insert(k))
}
/// Extends the set with the values from the given iterator.
#[track_caller]
fn extend(&mut self, iter: impl IntoIterator<Item = V>)
where
V: std::cmp::Eq + std::hash::Hash,
H: std::hash::BuildHasher,
{
self.with_mut(|set| set.extend(iter))
}
/// Removes a value from the set. Returns true if the value was present.
#[track_caller]
fn remove(&mut self, k: &V) -> bool
where
V: std::cmp::Eq + std::hash::Hash,
H: std::hash::BuildHasher,
{
self.with_mut(|set| set.remove(k))
}
}
impl<V: 'static, H: 'static, R> WritableHashSetExt<V, H> for R where
R: Writable<Target = HashSet<V, H>>
{
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/signal.rs | packages/signals/src/signal.rs | use crate::{
default_impl, fmt_impls, read::*, write::*, write_impls, CopyValue, Global, GlobalMemo,
GlobalSignal, Memo, ReadableRef, WritableRef,
};
use dioxus_core::{IntoAttributeValue, IntoDynNode, ReactiveContext, ScopeId, Subscribers};
use generational_box::{BorrowResult, Storage, SyncStorage, UnsyncStorage};
use std::{collections::HashSet, ops::Deref, sync::Arc, sync::Mutex};
#[doc = include_str!("../docs/signals.md")]
#[doc(alias = "State")]
#[doc(alias = "UseState")]
#[doc(alias = "UseRef")]
pub struct Signal<T, S: 'static = UnsyncStorage> {
pub(crate) inner: CopyValue<SignalData<T>, S>,
}
/// A signal that can safely shared between threads.
#[doc(alias = "SendSignal")]
#[doc(alias = "UseRwLock")]
#[doc(alias = "UseRw")]
#[doc(alias = "UseMutex")]
pub type SyncSignal<T> = Signal<T, SyncStorage>;
/// The data stored for tracking in a signal.
pub struct SignalData<T> {
pub(crate) subscribers: Arc<Mutex<HashSet<ReactiveContext>>>,
pub(crate) value: T,
}
impl<T: 'static> Signal<T> {
/// Creates a new [`Signal`]. Signals are a Copy state management solution with automatic dependency tracking.
///
/// <div class="warning">
///
/// This function should generally only be called inside hooks. The signal that this function creates is owned by the current component and will only be dropped when the component is dropped. If you call this function outside of a hook many times, you will leak memory until the component is dropped.
///
/// ```rust
/// # use dioxus::prelude::*;
/// fn MyComponent() {
/// // ❌ Every time MyComponent runs, it will create a new signal that is only dropped when MyComponent is dropped
/// let signal = Signal::new(0);
/// use_context_provider(|| signal);
/// // ✅ Since the use_context_provider hook only runs when the component is created, the signal will only be created once and it will be dropped when MyComponent is dropped
/// let signal = use_context_provider(|| Signal::new(0));
/// }
/// ```
///
/// </div>
#[track_caller]
pub fn new(value: T) -> Self {
Self::new_maybe_sync(value)
}
/// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
#[track_caller]
pub fn new_in_scope(value: T, owner: ScopeId) -> Self {
Self::new_maybe_sync_in_scope(value, owner)
}
/// Creates a new [`GlobalSignal`] that can be used anywhere inside your dioxus app. This signal will automatically be created once per app the first time you use it.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// // Create a new global signal that can be used anywhere in your app
/// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
///
/// fn App() -> Element {
/// rsx! {
/// button {
/// onclick: move |_| *SIGNAL.write() += 1,
/// "{SIGNAL}"
/// }
/// }
/// }
/// ```
///
/// <div class="warning">
///
/// Global signals are generally not recommended for use in libraries because it makes it more difficult to allow multiple instances of components you define in your library.
///
/// </div>
#[track_caller]
pub const fn global(constructor: fn() -> T) -> GlobalSignal<T> {
Global::new(constructor)
}
}
impl<T: PartialEq + 'static> Signal<T> {
/// Creates a new [`GlobalMemo`] that can be used anywhere inside your dioxus app. This memo will automatically be created once per app the first time you use it.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
/// // Create a new global memo that can be used anywhere in your app
/// static DOUBLED: GlobalMemo<i32> = Signal::global_memo(|| SIGNAL() * 2);
///
/// fn App() -> Element {
/// rsx! {
/// button {
/// // When SIGNAL changes, the memo will update because the SIGNAL is read inside DOUBLED
/// onclick: move |_| *SIGNAL.write() += 1,
/// "{DOUBLED}"
/// }
/// }
/// }
/// ```
///
/// <div class="warning">
///
/// Global memos are generally not recommended for use in libraries because it makes it more difficult to allow multiple instances of components you define in your library.
///
/// </div>
#[track_caller]
pub const fn global_memo(constructor: fn() -> T) -> GlobalMemo<T>
where
T: PartialEq,
{
GlobalMemo::new(constructor)
}
/// Creates a new unsync Selector. The selector will be run immediately and whenever any signal it reads changes.
///
/// Selectors can be used to efficiently compute derived data from signals.
#[track_caller]
pub fn memo(f: impl FnMut() -> T + 'static) -> Memo<T> {
Memo::new(f)
}
/// Creates a new unsync Selector with an explicit location. The selector will be run immediately and whenever any signal it reads changes.
///
/// Selectors can be used to efficiently compute derived data from signals.
pub fn memo_with_location(
f: impl FnMut() -> T + 'static,
location: &'static std::panic::Location<'static>,
) -> Memo<T> {
Memo::new_with_location(f, location)
}
}
impl<T, S: Storage<SignalData<T>>> Signal<T, S> {
/// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
#[track_caller]
#[tracing::instrument(skip(value))]
pub fn new_maybe_sync(value: T) -> Self
where
T: 'static,
{
Self {
inner: CopyValue::<SignalData<T>, S>::new_maybe_sync(SignalData {
subscribers: Default::default(),
value,
}),
}
}
/// Creates a new Signal with an explicit caller. Signals are a Copy state management solution with automatic dependency tracking.
///
/// This method can be used to provide the correct caller information for signals that are created in closures:
///
/// ```rust
/// # use dioxus::prelude::*;
/// #[track_caller]
/// fn use_my_signal(function: impl FnOnce() -> i32) -> Signal<i32> {
/// // We capture the caller information outside of the closure so that it points to the caller of use_my_custom_hook instead of the closure
/// let caller = std::panic::Location::caller();
/// use_hook(move || Signal::new_with_caller(function(), caller))
/// }
/// ```
pub fn new_with_caller(value: T, caller: &'static std::panic::Location<'static>) -> Self
where
T: 'static,
{
Self {
inner: CopyValue::new_with_caller(
SignalData {
subscribers: Default::default(),
value,
},
caller,
),
}
}
/// Create a new Signal without an owner. This will leak memory if you don't manually drop it.
pub fn leak_with_caller(value: T, caller: &'static std::panic::Location<'static>) -> Self
where
T: 'static,
{
Self {
inner: CopyValue::leak_with_caller(
SignalData {
subscribers: Default::default(),
value,
},
caller,
),
}
}
/// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
#[track_caller]
#[tracing::instrument(skip(value))]
pub fn new_maybe_sync_in_scope(value: T, owner: ScopeId) -> Self {
Self::new_maybe_sync_in_scope_with_caller(value, owner, std::panic::Location::caller())
}
/// Create a new signal with a custom owner scope and a custom caller. The signal will be dropped when the owner scope is dropped instead of the current scope.
#[tracing::instrument(skip(value))]
pub fn new_maybe_sync_in_scope_with_caller(
value: T,
owner: ScopeId,
caller: &'static std::panic::Location<'static>,
) -> Self {
Self {
inner: CopyValue::<SignalData<T>, S>::new_maybe_sync_in_scope_with_caller(
SignalData {
subscribers: Default::default(),
value,
},
owner,
caller,
),
}
}
/// Point to another signal. This will subscribe the other signal to all subscribers of this signal.
pub fn point_to(&self, other: Self) -> BorrowResult
where
T: 'static,
{
#[allow(clippy::mutable_key_type)]
let this_subscribers = self.inner.value.read().subscribers.lock().unwrap().clone();
let other_read = other.inner.value.read();
for subscriber in this_subscribers.iter() {
subscriber.subscribe(other_read.subscribers.clone());
}
self.inner.point_to(other.inner)
}
/// Drop the value out of the signal, invalidating the signal in the process.
pub fn manually_drop(&self)
where
T: 'static,
{
self.inner.manually_drop()
}
/// Get the scope the signal was created in.
pub fn origin_scope(&self) -> ScopeId {
self.inner.origin_scope()
}
fn update_subscribers(&self)
where
T: 'static,
{
{
let inner = self.inner.read();
// We cannot hold the subscribers lock while calling mark_dirty, because mark_dirty can run user code which may cause a new subscriber to be added. If we hold the lock, we will deadlock.
#[allow(clippy::mutable_key_type)]
let mut subscribers = std::mem::take(&mut *inner.subscribers.lock().unwrap());
subscribers.retain(|reactive_context| reactive_context.mark_dirty());
// Extend the subscribers list instead of overwriting it in case a subscriber is added while reactive contexts are marked dirty
inner.subscribers.lock().unwrap().extend(subscribers);
}
}
/// Get the generational id of the signal.
pub fn id(&self) -> generational_box::GenerationalBoxId {
self.inner.id()
}
/// **This pattern is no longer recommended. Prefer [`peek`](ReadableExt::peek) or creating new signals instead.**
///
/// This function is the equivalent of the [write_silent](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseRef.html#method.write_silent) method on use_ref.
///
/// ## What you should use instead
///
/// ### Reading and Writing to data in the same scope
///
/// Reading and writing to the same signal in the same scope will cause that scope to rerun forever:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// let mut signal = use_signal(|| 0);
/// // This makes the scope rerun whenever we write to the signal
/// println!("{}", *signal.read());
/// // This will rerun the scope because we read the signal earlier in the same scope
/// *signal.write() += 1;
/// ```
///
/// You may have used the write_silent method to avoid this infinite loop with use_ref like this:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// let signal = use_signal(|| 0);
/// // This makes the scope rerun whenever we write to the signal
/// println!("{}", *signal.read());
/// // Write silent will not rerun any subscribers
/// *signal.write_silent() += 1;
/// ```
///
/// Instead you can use the [`peek`](ReadableExt::peek) and [`write`](WritableExt::write) methods instead. The peek method will not subscribe to the current scope which will avoid an infinite loop if you are reading and writing to the same signal in the same scope.
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// let mut signal = use_signal(|| 0);
/// // Peek will read the value but not subscribe to the current scope
/// println!("{}", *signal.peek());
/// // Write will update any subscribers which does not include the current scope
/// *signal.write() += 1;
/// ```
///
/// ### Reading and Writing to different data
///
///
///
/// ## Why is this pattern no longer recommended?
///
/// This pattern is no longer recommended because it is very easy to allow your state and UI to grow out of sync. `write_silent` globally opts out of automatic state updates which can be difficult to reason about.
///
///
/// Lets take a look at an example:
/// main.rs:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # fn Child() -> Element { unimplemented!() }
/// fn app() -> Element {
/// let signal = use_context_provider(|| Signal::new(0));
///
/// // We want to log the value of the signal whenever the app component reruns
/// println!("{}", *signal.read());
///
/// rsx! {
/// button {
/// // If we don't want to rerun the app component when the button is clicked, we can use write_silent
/// onclick: move |_| *signal.write_silent() += 1,
/// "Increment"
/// }
/// Child {}
/// }
/// }
/// ```
/// child.rs:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// fn Child() -> Element {
/// let signal: Signal<i32> = use_context();
///
/// // It is difficult to tell that changing the button to use write_silent in the main.rs file will cause UI to be out of sync in a completely different file
/// rsx! {
/// "{signal}"
/// }
/// }
/// ```
///
/// Instead [`peek`](ReadableExt::peek) locally opts out of automatic state updates explicitly for a specific read which is easier to reason about.
///
/// Here is the same example using peek:
/// main.rs:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// # fn Child() -> Element { unimplemented!() }
/// fn app() -> Element {
/// let mut signal = use_context_provider(|| Signal::new(0));
///
/// // We want to log the value of the signal whenever the app component reruns, but we don't want to rerun the app component when the signal is updated so we use peek instead of read
/// println!("{}", *signal.peek());
///
/// rsx! {
/// button {
/// // We can use write like normal and update the child component automatically
/// onclick: move |_| *signal.write() += 1,
/// "Increment"
/// }
/// Child {}
/// }
/// }
/// ```
/// child.rs:
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// fn Child() -> Element {
/// let signal: Signal<i32> = use_context();
///
/// rsx! {
/// "{signal}"
/// }
/// }
/// ```
#[track_caller]
#[deprecated = "This pattern is no longer recommended. Prefer `peek` or creating new signals instead."]
pub fn write_silent(&self) -> WriteLock<'static, T, S> {
WriteLock::map(self.inner.write_unchecked(), |inner: &mut SignalData<T>| {
&mut inner.value
})
}
}
impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
type Target = T;
type Storage = S;
#[track_caller]
fn try_read_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
where
T: 'static,
{
let inner = self.inner.try_read_unchecked()?;
if let Some(reactive_context) = ReactiveContext::current() {
tracing::trace!("Subscribing to the reactive context {}", reactive_context);
reactive_context.subscribe(inner.subscribers.clone());
}
Ok(S::map(inner, |v| &v.value))
}
/// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
///
/// If the signal has been dropped, this will panic.
#[track_caller]
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
where
T: 'static,
{
self.inner
.try_read_unchecked()
.map(|inner| S::map(inner, |v| &v.value))
}
fn subscribers(&self) -> Subscribers
where
T: 'static,
{
self.inner.read().subscribers.clone().into()
}
}
impl<T: 'static, S: Storage<SignalData<T>>> Writable for Signal<T, S> {
type WriteMetadata = SignalSubscriberDrop<T, S>;
#[track_caller]
fn try_write_unchecked(
&self,
) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> {
#[cfg(debug_assertions)]
let origin = std::panic::Location::caller();
self.inner.try_write_unchecked().map(|inner| {
let borrow = S::map_mut(inner.into_inner(), |v| &mut v.value);
WriteLock::new_with_metadata(
borrow,
SignalSubscriberDrop {
signal: *self,
#[cfg(debug_assertions)]
origin,
},
)
})
}
}
impl<T> IntoAttributeValue for Signal<T>
where
T: Clone + IntoAttributeValue + 'static,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<T> IntoDynNode for Signal<T>
where
T: Clone + IntoDynNode + 'static,
{
fn into_dyn_node(self) -> dioxus_core::DynamicNode {
self().into_dyn_node()
}
}
impl<T, S: Storage<SignalData<T>>> PartialEq for Signal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, S: Storage<SignalData<T>>> Eq for Signal<T, S> {}
/// Allow calling a signal with signal() syntax
///
/// Currently only limited to copy types, though could probably specialize for string/arc/rc
impl<T: Clone + 'static, S: Storage<SignalData<T>> + 'static> Deref for Signal<T, S> {
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
#[cfg(feature = "serialize")]
impl<T: serde::Serialize + 'static, Store: Storage<SignalData<T>> + 'static> serde::Serialize
for Signal<T, Store>
{
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.read().serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de, T: serde::Deserialize<'de> + 'static, Store: Storage<SignalData<T>> + 'static>
serde::Deserialize<'de> for Signal<T, Store>
{
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self::new_maybe_sync(T::deserialize(deserializer)?))
}
}
#[doc(hidden)]
/// A drop guard that will update the subscribers of the signal when it is dropped.
pub struct SignalSubscriberDrop<T: 'static, S: Storage<SignalData<T>> + 'static> {
signal: Signal<T, S>,
#[cfg(debug_assertions)]
origin: &'static std::panic::Location<'static>,
}
#[allow(clippy::no_effect)]
impl<T: 'static, S: Storage<SignalData<T>> + 'static> Drop for SignalSubscriberDrop<T, S> {
fn drop(&mut self) {
#[cfg(debug_assertions)]
{
tracing::trace!(
"Write on signal at {} finished, updating subscribers",
self.origin
);
}
self.signal.update_subscribers();
}
}
fmt_impls!(Signal<T, S: Storage<SignalData<T>>>);
default_impl!(Signal<T, S: Storage<SignalData<T>>>);
write_impls!(Signal<T, S: Storage<SignalData<T>>>);
impl<T, S> Clone for Signal<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Copy for Signal<T, S> {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/copy_value.rs | packages/signals/src/copy_value.rs | #![allow(clippy::unnecessary_operation)]
#![allow(clippy::no_effect)]
use dioxus_core::{current_owner, current_scope_id, ScopeId};
use dioxus_core::{Runtime, Subscribers};
use generational_box::{
AnyStorage, BorrowResult, GenerationalBox, GenerationalBoxId, Storage, UnsyncStorage,
};
use std::ops::Deref;
use crate::read_impls;
use crate::Readable;
use crate::ReadableExt;
use crate::ReadableRef;
use crate::Writable;
use crate::WritableRef;
use crate::WriteLock;
use crate::{default_impl, write_impls, WritableExt};
/// CopyValue is a wrapper around a value to make the value mutable and Copy.
///
/// It is internally backed by [`generational_box::GenerationalBox`].
pub struct CopyValue<T, S: 'static = UnsyncStorage> {
pub(crate) value: GenerationalBox<T, S>,
pub(crate) origin_scope: ScopeId,
}
#[cfg(feature = "serialize")]
impl<T, Store: Storage<T>> serde::Serialize for CopyValue<T, Store>
where
T: serde::Serialize + 'static,
{
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.value.read().serialize(serializer)
}
}
#[cfg(feature = "serialize")]
impl<'de, T, Store: Storage<T>> serde::Deserialize<'de> for CopyValue<T, Store>
where
T: serde::Deserialize<'de> + 'static,
{
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = T::deserialize(deserializer)?;
Ok(Self::new_maybe_sync(value))
}
}
impl<T: 'static> CopyValue<T> {
/// Create a new CopyValue. The value will be stored in the current component.
///
/// Once the component this value is created in is dropped, the value will be dropped.
#[track_caller]
pub fn new(value: T) -> Self {
Self::new_maybe_sync(value)
}
/// Create a new CopyValue. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped.
#[track_caller]
pub fn new_in_scope(value: T, scope: ScopeId) -> Self {
Self::new_maybe_sync_in_scope(value, scope)
}
}
impl<T, S: Storage<T>> CopyValue<T, S> {
/// Create a new CopyValue. The value will be stored in the current component.
///
/// Once the component this value is created in is dropped, the value will be dropped.
#[track_caller]
pub fn new_maybe_sync(value: T) -> Self
where
T: 'static,
{
Self::new_with_caller(value, std::panic::Location::caller())
}
/// Create a new CopyValue without an owner. This will leak memory if you don't manually drop it.
pub fn leak_with_caller(value: T, caller: &'static std::panic::Location<'static>) -> Self
where
T: 'static,
{
Self {
value: GenerationalBox::leak(value, caller),
origin_scope: current_scope_id(),
}
}
/// Point to another copy value
pub fn point_to(&self, other: Self) -> BorrowResult {
self.value.point_to(other.value)
}
pub(crate) fn new_with_caller(
value: T,
caller: &'static std::panic::Location<'static>,
) -> Self {
let owner = current_owner();
Self {
value: owner.insert_rc_with_caller(value, caller),
origin_scope: current_scope_id(),
}
}
/// Create a new CopyValue. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped.
#[track_caller]
pub fn new_maybe_sync_in_scope(value: T, scope: ScopeId) -> Self {
Self::new_maybe_sync_in_scope_with_caller(value, scope, std::panic::Location::caller())
}
/// Create a new CopyValue with a custom caller. The value will be stored in the given scope. When the specified scope is dropped, the value will be dropped.
#[track_caller]
pub fn new_maybe_sync_in_scope_with_caller(
value: T,
scope: ScopeId,
caller: &'static std::panic::Location<'static>,
) -> Self {
let owner = Runtime::current().scope_owner(scope);
Self {
value: owner.insert_rc_with_caller(value, caller),
origin_scope: scope,
}
}
/// Manually drop the value in the CopyValue, invalidating the value in the process.
pub fn manually_drop(&self)
where
T: 'static,
{
self.value.manually_drop()
}
/// Get the scope this value was created in.
pub fn origin_scope(&self) -> ScopeId {
self.origin_scope
}
/// Get the generational id of the value.
pub fn id(&self) -> GenerationalBoxId {
self.value.id()
}
/// Get the underlying [`GenerationalBox`] value.
pub fn value(&self) -> GenerationalBox<T, S> {
self.value
}
}
impl<T, S: Storage<T>> Readable for CopyValue<T, S> {
type Target = T;
type Storage = S;
#[track_caller]
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
crate::warnings::copy_value_hoisted(self, std::panic::Location::caller());
self.value.try_read()
}
#[track_caller]
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>> {
crate::warnings::copy_value_hoisted(self, std::panic::Location::caller());
self.value.try_read()
}
fn subscribers(&self) -> Subscribers {
Subscribers::new_noop()
}
}
impl<T, S: Storage<T>> Writable for CopyValue<T, S> {
type WriteMetadata = ();
#[track_caller]
fn try_write_unchecked(
&self,
) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> {
crate::warnings::copy_value_hoisted(self, std::panic::Location::caller());
self.value.try_write().map(WriteLock::new)
}
}
impl<T, S: AnyStorage> PartialEq for CopyValue<T, S> {
fn eq(&self, other: &Self) -> bool {
self.value.ptr_eq(&other.value)
}
}
impl<T, S: AnyStorage> Eq for CopyValue<T, S> {}
impl<T: Copy + 'static, S: Storage<T>> Deref for CopyValue<T, S> {
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
impl<T, S> Clone for CopyValue<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Copy for CopyValue<T, S> {}
read_impls!(CopyValue<T, S: Storage<T>>);
default_impl!(CopyValue<T, S: Storage<T>>);
write_impls!(CopyValue<T, S: Storage<T>>);
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/map.rs | packages/signals/src/map.rs | use crate::{read::Readable, read_impls, ReadableExt, ReadableRef};
use dioxus_core::{IntoAttributeValue, Subscribers};
use generational_box::{AnyStorage, BorrowResult};
use std::ops::Deref;
/// A read only signal that has been mapped to a new type.
pub struct MappedSignal<O: ?Sized, V, F = fn(&<V as Readable>::Target) -> &O> {
value: V,
map_fn: F,
_marker: std::marker::PhantomData<O>,
}
impl<V, O, F> Clone for MappedSignal<O, V, F>
where
V: Readable + Clone,
F: Clone,
{
fn clone(&self) -> Self {
MappedSignal {
value: self.value.clone(),
map_fn: self.map_fn.clone(),
_marker: std::marker::PhantomData,
}
}
}
impl<V, O, F> Copy for MappedSignal<O, V, F>
where
V: Readable + Copy,
F: Copy,
{
}
impl<V, O, F> MappedSignal<O, V, F>
where
O: ?Sized,
{
/// Create a new mapped signal.
pub fn new(value: V, map_fn: F) -> Self {
MappedSignal {
value,
map_fn,
_marker: std::marker::PhantomData,
}
}
}
impl<V, O, F> Readable for MappedSignal<O, V, F>
where
O: ?Sized,
V: Readable,
V::Target: 'static,
F: Fn(&V::Target) -> &O,
{
type Target = O;
type Storage = V::Storage;
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> {
let value = self.value.try_read_unchecked()?;
Ok(V::Storage::map(value, |v| (self.map_fn)(v)))
}
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>> {
let value = self.value.try_peek_unchecked()?;
Ok(V::Storage::map(value, |v| (self.map_fn)(v)))
}
fn subscribers(&self) -> Subscribers {
self.value.subscribers()
}
}
impl<V, O, F> IntoAttributeValue for MappedSignal<O, V, F>
where
O: Clone + IntoAttributeValue + 'static,
V: Readable,
V::Target: 'static,
F: Fn(&V::Target) -> &O,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<V, O, F> PartialEq for MappedSignal<O, V, F>
where
O: ?Sized,
V: Readable + PartialEq,
F: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.value == other.value && self.map_fn == other.map_fn
}
}
/// Allow calling a signal with signal() syntax
///
/// Currently only limited to clone types, though could probably specialize for string/arc/rc
impl<V, O, F> Deref for MappedSignal<O, V, F>
where
O: Clone + 'static,
V: Readable + 'static,
F: Fn(&V::Target) -> &O + 'static,
{
type Target = dyn Fn() -> O;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
read_impls!(MappedSignal<T, V, F> where V: Readable<Target: 'static>, F: Fn(&V::Target) -> &T);
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/props.rs | packages/signals/src/props.rs | use crate::{ReadSignal, Signal};
use dioxus_core::SuperFrom;
#[doc(hidden)]
pub struct ReadFromMarker<M>(std::marker::PhantomData<M>);
impl<T, O, M> SuperFrom<T, ReadFromMarker<M>> for ReadSignal<O>
where
O: SuperFrom<T, M> + 'static,
T: 'static,
{
fn super_from(input: T) -> Self {
ReadSignal::new(Signal::new(O::super_from(input)))
}
}
#[test]
#[allow(unused)]
fn into_signal_compiles() {
use dioxus_core::SuperInto;
fn takes_signal_string<M>(_: impl SuperInto<ReadSignal<String>, M>) {}
fn takes_option_signal_string<M>(_: impl SuperInto<ReadSignal<Option<String>>, M>) {}
fn don_t_run() {
takes_signal_string("hello world");
takes_signal_string(Signal::new(String::from("hello world")));
takes_option_signal_string("hello world");
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/read.rs | packages/signals/src/read.rs | use std::collections::{HashMap, HashSet};
use std::{
mem::MaybeUninit,
ops::{Deref, Index},
};
use crate::{ext_methods, MappedSignal, ReadSignal};
use dioxus_core::Subscribers;
use generational_box::{AnyStorage, UnsyncStorage};
/// A reference to a value that can be read from.
#[allow(type_alias_bounds)]
pub type ReadableRef<'a, T: Readable, O = <T as Readable>::Target> =
<T::Storage as AnyStorage>::Ref<'a, O>;
/// A trait for states that can be read from like [`crate::Signal`], [`crate::GlobalSignal`], or [`crate::ReadSignal`]. You may choose to accept this trait as a parameter instead of the concrete type to allow for more flexibility in your API. For example, instead of creating two functions, one that accepts a [`crate::Signal`] and one that accepts a [`crate::GlobalSignal`], you can create one function that accepts a [`Readable`] type.
///
/// # Example
/// ```rust
/// # use dioxus::prelude::*;
/// fn double(something_readable: &impl Readable<Target = i32>) -> i32 {
/// something_readable.cloned() * 2
/// }
///
/// static COUNT: GlobalSignal<i32> = Signal::global(|| 0);
///
/// fn MyComponent(count: Signal<i32>) -> Element {
/// // Since we defined the function in terms of the readable trait, we can use it with any readable type (Signal, GlobalSignal, ReadSignal, etc)
/// let doubled = use_memo(move || double(&count));
/// let global_count_doubled = use_memo(|| double(&COUNT));
/// rsx! {
/// div {
/// "Count local: {count}"
/// "Doubled local: {doubled}"
/// "Count global: {COUNT}"
/// "Doubled global: {global_count_doubled}"
/// }
/// }
/// }
/// ```
pub trait Readable {
/// The target type of the reference.
type Target: ?Sized;
/// The type of the storage this readable uses.
type Storage: AnyStorage;
/// Try to get a reference to the value without checking the lifetime. This will subscribe the current scope to the signal.
///
/// NOTE: This method is completely safe because borrow checking is done at runtime.
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
Self::Target: 'static;
/// Try to peek the current value of the signal without subscribing to updates. If the value has
/// been dropped, this will return an error.
///
/// NOTE: This method is completely safe because borrow checking is done at runtime.
fn try_peek_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
Self::Target: 'static;
/// Get the underlying subscriber list for this readable. This is used to track when the value changes and notify subscribers.
fn subscribers(&self) -> Subscribers
where
Self::Target: 'static;
}
/// An extension trait for `Readable` types that provides some convenience methods.
pub trait ReadableExt: Readable {
/// Get the current value of the state. If this is a signal, this will subscribe the current scope to the signal.
/// If the value has been dropped, this will panic. Calling this on a Signal is the same as
/// using the signal() syntax to read and subscribe to its value
#[track_caller]
fn read(&self) -> ReadableRef<'_, Self>
where
Self::Target: 'static,
{
self.try_read().unwrap()
}
/// Try to get the current value of the state. If this is a signal, this will subscribe the current scope to the signal.
#[track_caller]
fn try_read(&self) -> Result<ReadableRef<'_, Self>, generational_box::BorrowError>
where
Self::Target: 'static,
{
self.try_read_unchecked()
.map(Self::Storage::downcast_lifetime_ref)
}
/// Get a reference to the value without checking the lifetime. This will subscribe the current scope to the signal.
///
/// NOTE: This method is completely safe because borrow checking is done at runtime.
#[track_caller]
fn read_unchecked(&self) -> ReadableRef<'static, Self>
where
Self::Target: 'static,
{
self.try_read_unchecked().unwrap()
}
/// Get the current value of the state without subscribing to updates. If the value has been dropped, this will panic.
///
/// # Example
/// ```rust
/// # use dioxus::prelude::*;
/// fn MyComponent(mut count: Signal<i32>) -> Element {
/// let mut event_source = use_signal(|| None);
/// let doubled = use_memo(move || {
/// // We want to log the value of the event_source, but we don't need to rerun the doubled value if the event_source changes (because the value of doubled doesn't depend on the event_source)
/// // We can read the value with peek without subscribing to updates
/// let source = event_source.peek();
/// tracing::info!("Clicked: {source:?}");
/// count() * 2
/// });
/// rsx! {
/// div { "Count: {count}" }
/// div { "Doubled: {doubled}" }
/// button {
/// onclick: move |_| {
/// event_source.set(Some("Click me button"));
/// count += 1;
/// },
/// "Click me"
/// }
/// button {
/// onclick: move |_| {
/// event_source.set(Some("Double me button"));
/// count += 1;
/// },
/// "Double me"
/// }
/// }
/// }
/// ```
#[track_caller]
fn peek(&self) -> ReadableRef<'_, Self>
where
Self::Target: 'static,
{
Self::Storage::downcast_lifetime_ref(self.peek_unchecked())
}
/// Try to peek the current value of the signal without subscribing to updates. If the value has
/// been dropped, this will return an error.
#[track_caller]
fn try_peek(&self) -> Result<ReadableRef<'_, Self>, generational_box::BorrowError>
where
Self::Target: 'static,
{
self.try_peek_unchecked()
.map(Self::Storage::downcast_lifetime_ref)
}
/// Get the current value of the signal without checking the lifetime. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
///
/// If the signal has been dropped, this will panic.
#[track_caller]
fn peek_unchecked(&self) -> ReadableRef<'static, Self>
where
Self::Target: 'static,
{
self.try_peek_unchecked().unwrap()
}
/// Map the references of the readable value to a new type. This lets you provide a view
/// into the readable value without creating a new signal or cloning the value.
///
/// Anything that subscribes to the readable value will be rerun whenever the original value changes, even if the view does not
/// change. If you want to memorize the view, you can use a [`crate::Memo`] instead. For fine grained scoped updates, use
/// stores instead
///
/// # Example
/// ```rust
/// # use dioxus::prelude::*;
/// fn List(list: Signal<Vec<i32>>) -> Element {
/// rsx! {
/// for index in 0..list.len() {
/// // We can use the `map` method to provide a view into the single item in the list that the child component will render
/// Item { item: list.map(move |v| &v[index]) }
/// }
/// }
/// }
///
/// // The child component doesn't need to know that the mapped value is coming from a list
/// #[component]
/// fn Item(item: ReadSignal<i32>) -> Element {
/// rsx! {
/// div { "Item: {item}" }
/// }
/// }
/// ```
fn map<F, O>(self, f: F) -> MappedSignal<O, Self, F>
where
Self: Clone + Sized,
F: Fn(&Self::Target) -> &O,
{
MappedSignal::new(self, f)
}
/// Clone the inner value and return it. If the value has been dropped, this will panic.
#[track_caller]
fn cloned(&self) -> Self::Target
where
Self::Target: Clone + 'static,
{
self.read().clone()
}
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
#[track_caller]
fn with<O>(&self, f: impl FnOnce(&Self::Target) -> O) -> O
where
Self::Target: 'static,
{
f(&*self.read())
}
/// Run a function with a reference to the value. If the value has been dropped, this will panic.
#[track_caller]
fn with_peek<O>(&self, f: impl FnOnce(&Self::Target) -> O) -> O
where
Self::Target: 'static,
{
f(&*self.peek())
}
/// Index into the inner value and return a reference to the result. If the value has been dropped or the index is invalid, this will panic.
#[track_caller]
fn index<I>(
&self,
index: I,
) -> ReadableRef<'_, Self, <Self::Target as std::ops::Index<I>>::Output>
where
Self::Target: std::ops::Index<I> + 'static,
{
<Self::Storage as AnyStorage>::map(self.read(), |v| v.index(index))
}
/// SAFETY: You must call this function directly with `self` as the argument.
/// This function relies on the size of the object you return from the deref
/// being the same as the object you pass in
#[doc(hidden)]
unsafe fn deref_impl<'a>(&self) -> &'a dyn Fn() -> Self::Target
where
Self: Sized + 'a,
Self::Target: Clone + 'static,
{
// https://github.com/dtolnay/case-studies/tree/master/callable-types
// First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
let uninit_callable = MaybeUninit::<Self>::uninit();
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
let uninit_closure = move || Self::read(unsafe { &*uninit_callable.as_ptr() }).clone();
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
let size_of_closure = std::mem::size_of_val(&uninit_closure);
assert_eq!(size_of_closure, std::mem::size_of::<Self>());
// Then cast the lifetime of the closure to the lifetime of &self.
fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
b
}
let reference_to_closure = cast_lifetime(
{
// The real closure that we will never use.
&uninit_closure
},
#[allow(clippy::missing_transmute_annotations)]
// We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
unsafe {
std::mem::transmute(self)
},
);
// Cast the closure to a trait object.
reference_to_closure as &_
}
}
impl<R: Readable + ?Sized> ReadableExt for R {}
/// An extension trait for `Readable` types that can be boxed into a trait object.
pub trait ReadableBoxExt: Readable<Storage = UnsyncStorage> {
/// Box the readable value into a trait object. This is useful for passing around readable values without knowing their concrete type.
fn boxed(self) -> ReadSignal<Self::Target>
where
Self: Sized + 'static,
{
ReadSignal::new(self)
}
}
impl<R: Readable<Storage = UnsyncStorage> + ?Sized> ReadableBoxExt for R {}
/// An extension trait for `Readable<Vec<T>>` that provides some convenience methods.
pub trait ReadableVecExt<T>: Readable<Target = Vec<T>> {
/// Returns the length of the inner vector.
#[track_caller]
fn len(&self) -> usize
where
T: 'static,
{
self.with(|v| v.len())
}
/// Returns true if the inner vector is empty.
#[track_caller]
fn is_empty(&self) -> bool
where
T: 'static,
{
self.with(|v| v.is_empty())
}
/// Get the first element of the inner vector.
#[track_caller]
fn first(&self) -> Option<ReadableRef<'_, Self, T>>
where
T: 'static,
{
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.first())
}
/// Get the last element of the inner vector.
#[track_caller]
fn last(&self) -> Option<ReadableRef<'_, Self, T>>
where
T: 'static,
{
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.last())
}
/// Get the element at the given index of the inner vector.
#[track_caller]
fn get(&self, index: usize) -> Option<ReadableRef<'_, Self, T>>
where
T: 'static,
{
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.get(index))
}
/// Get an iterator over the values of the inner vector.
#[track_caller]
fn iter(&self) -> ReadableValueIterator<'_, Self>
where
Self: Sized,
{
ReadableValueIterator {
index: 0,
value: self,
}
}
}
/// An iterator over the values of a `Readable<Vec<T>>`.
pub struct ReadableValueIterator<'a, R> {
index: usize,
value: &'a R,
}
impl<'a, T: 'static, R: Readable<Target = Vec<T>>> Iterator for ReadableValueIterator<'a, R> {
type Item = ReadableRef<'a, R, T>;
fn next(&mut self) -> Option<Self::Item> {
let index = self.index;
self.index += 1;
self.value.get(index)
}
}
impl<T, R> ReadableVecExt<T> for R where R: Readable<Target = Vec<T>> {}
/// An extension trait for `Readable<Option<T>>` that provides some convenience methods.
pub trait ReadableOptionExt<T>: Readable<Target = Option<T>> {
/// Unwraps the inner value and clones it.
#[track_caller]
fn unwrap(&self) -> T
where
T: Clone + 'static,
{
self.as_ref().unwrap().clone()
}
/// Attempts to read the inner value of the Option.
#[track_caller]
fn as_ref(&self) -> Option<ReadableRef<'_, Self, T>>
where
T: 'static,
{
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.as_ref())
}
}
impl<T, R> ReadableOptionExt<T> for R where R: Readable<Target = Option<T>> {}
/// An extension trait for `Readable<Option<T>>` that provides some convenience methods.
pub trait ReadableResultExt<T, E>: Readable<Target = Result<T, E>> {
/// Unwraps the inner value and clones it.
#[track_caller]
fn unwrap(&self) -> T
where
T: Clone + 'static,
E: 'static,
{
self.as_ref()
.unwrap_or_else(|_| panic!("Tried to unwrap a Result that was an error"))
.clone()
}
/// Attempts to read the inner value of the Option.
#[track_caller]
fn as_ref(&self) -> Result<ReadableRef<'_, Self, T>, ReadableRef<'_, Self, E>>
where
T: 'static,
E: 'static,
{
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.as_ref().ok()).ok_or(
<Self::Storage as AnyStorage>::map(self.read(), |v| v.as_ref().err().unwrap()),
)
}
}
impl<T, E, R> ReadableResultExt<T, E> for R where R: Readable<Target = Result<T, E>> {}
/// An extension trait for [`Readable<String>`] that provides some convenience methods.
pub trait ReadableStringExt: Readable<Target = String> {
ext_methods! {
/// Check the capacity of the string.
fn capacity(&self) -> usize = String::capacity;
}
}
impl<W> ReadableStringExt for W where W: Readable<Target = String> {}
/// An extension trait for [`Readable<String>`] and [`Readable<str>`] that provides some convenience methods.
pub trait ReadableStrExt: Readable<Target: Deref<Target = str> + 'static> {
ext_methods! {
/// Check if the string is empty.
fn is_empty(&self) -> bool = |s: &Self::Target| s.deref().is_empty();
/// Get the length of the string.
fn len(&self) -> usize = |s: &Self::Target| s.deref().len();
/// Check if the string contains the given pattern.
fn contains(&self, pat: &str) -> bool = |s: &Self::Target, pat| s.deref().contains(pat);
}
}
impl<W> ReadableStrExt for W where W: Readable<Target: Deref<Target = str> + 'static> {}
/// An extension trait for [`Readable<HashMap<K, V, H>>`] that provides some convenience methods.
pub trait ReadableHashMapExt<K: 'static, V: 'static, H: 'static>:
Readable<Target = HashMap<K, V, H>>
{
ext_methods! {
/// Check if the hashmap is empty.
fn is_empty(&self) -> bool = HashMap::is_empty;
/// Get the length of the hashmap.
fn len(&self) -> usize = HashMap::len;
/// Get the capacity of the hashmap.
fn capacity(&self) -> usize = HashMap::capacity;
}
/// Get the value for the given key.
#[track_caller]
fn get(&self, key: &K) -> Option<ReadableRef<'_, Self, V>>
where
K: std::hash::Hash + Eq,
H: std::hash::BuildHasher,
{
<Self::Storage as AnyStorage>::try_map(self.read(), |v| v.get(key))
}
/// Check if the hashmap contains the given key.
#[track_caller]
fn contains_key(&self, key: &K) -> bool
where
K: std::hash::Hash + Eq,
H: std::hash::BuildHasher,
{
self.with(|v| v.contains_key(key))
}
}
impl<K: 'static, V: 'static, H: 'static, R> ReadableHashMapExt<K, V, H> for R where
R: Readable<Target = HashMap<K, V, H>>
{
}
/// An extension trait for [`Readable<HashSet<V, H>>`] that provides some convenience methods.
pub trait ReadableHashSetExt<V: 'static, H: 'static>: Readable<Target = HashSet<V, H>> {
ext_methods! {
/// Check if the hashset is empty.
fn is_empty(&self) -> bool = HashSet::is_empty;
/// Get the length of the hashset.
fn len(&self) -> usize = HashSet::len;
/// Get the capacity of the hashset.
fn capacity(&self) -> usize = HashSet::capacity;
}
/// Check if the hashset contains the given value.
#[track_caller]
fn contains(&self, value: &V) -> bool
where
V: std::hash::Hash + Eq,
H: std::hash::BuildHasher,
{
self.with(|v| v.contains(value))
}
}
impl<V: 'static, H: 'static, R> ReadableHashSetExt<V, H> for R where
R: Readable<Target = HashSet<V, H>>
{
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/boxed.rs | packages/signals/src/boxed.rs | use std::{any::Any, ops::Deref};
use dioxus_core::{IntoAttributeValue, IntoDynNode, Subscribers};
use generational_box::{BorrowResult, Storage, SyncStorage, UnsyncStorage};
use crate::{
read_impls, write_impls, CopyValue, Global, InitializeFromFunction, MappedMutSignal,
MappedSignal, Memo, Readable, ReadableExt, ReadableRef, Signal, SignalData, Writable,
WritableExt,
};
/// A signal that can only be read from.
#[deprecated(
since = "0.7.0",
note = "Use `ReadSignal` instead. Will be removed in 0.8"
)]
pub type ReadOnlySignal<T, S = UnsyncStorage> = ReadSignal<T, S>;
/// A boxed version of [Readable] that can be used to store any readable type.
pub struct ReadSignal<T: ?Sized, S: BoxedSignalStorage<T> = UnsyncStorage> {
value: CopyValue<Box<S::DynReadable<sealed::SealedToken>>, S>,
}
impl<T: ?Sized + 'static> ReadSignal<T> {
/// Create a new boxed readable value.
pub fn new(value: impl Readable<Target = T, Storage = UnsyncStorage> + 'static) -> Self {
Self::new_maybe_sync(value)
}
}
impl<T: ?Sized + 'static, S: BoxedSignalStorage<T>> ReadSignal<T, S> {
/// Create a new boxed readable value which may be sync
pub fn new_maybe_sync<R>(value: R) -> Self
where
S: CreateBoxedSignalStorage<R>,
R: Readable<Target = T>,
{
Self {
value: CopyValue::new_maybe_sync(S::new_readable(value, sealed::SealedToken)),
}
}
/// Point to another [ReadSignal]. This will subscribe the other [ReadSignal] to all subscribers of this [ReadSignal].
pub fn point_to(&self, other: Self) -> BorrowResult {
let this_subscribers = self.subscribers();
let mut this_subscribers_vec = Vec::new();
// Note we don't subscribe directly in the visit closure to avoid a deadlock when pointing to self
this_subscribers.visit(|subscriber| this_subscribers_vec.push(*subscriber));
let other_subscribers = other.subscribers();
for subscriber in this_subscribers_vec {
subscriber.subscribe(other_subscribers.clone());
}
self.value.point_to(other.value)?;
Ok(())
}
#[doc(hidden)]
/// This is only used by the `props` macro.
/// Mark any readers of the signal as dirty
pub fn mark_dirty(&mut self) {
let subscribers = self.subscribers();
let mut this_subscribers_vec = Vec::new();
subscribers.visit(|subscriber| this_subscribers_vec.push(*subscriber));
for subscriber in this_subscribers_vec {
subscribers.remove(&subscriber);
subscriber.mark_dirty();
}
}
}
impl<T: ?Sized, S: BoxedSignalStorage<T>> Clone for ReadSignal<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T: ?Sized, S: BoxedSignalStorage<T>> Copy for ReadSignal<T, S> {}
impl<T: ?Sized, S: BoxedSignalStorage<T>> PartialEq for ReadSignal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl<
T: Default + 'static,
S: CreateBoxedSignalStorage<Signal<T, S>> + BoxedSignalStorage<T> + Storage<SignalData<T>>,
> Default for ReadSignal<T, S>
{
fn default() -> Self {
Self::new_maybe_sync(Signal::new_maybe_sync(T::default()))
}
}
read_impls!(ReadSignal<T, S: BoxedSignalStorage<T>>);
impl<T, S: BoxedSignalStorage<T>> IntoAttributeValue for ReadSignal<T, S>
where
T: Clone + IntoAttributeValue + 'static,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<T, S> IntoDynNode for ReadSignal<T, S>
where
T: Clone + IntoDynNode + 'static,
S: BoxedSignalStorage<T>,
{
fn into_dyn_node(self) -> dioxus_core::DynamicNode {
self.with(|f| f.clone().into_dyn_node())
}
}
impl<T: Clone + 'static, S: BoxedSignalStorage<T>> Deref for ReadSignal<T, S> {
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
impl<T: ?Sized, S: BoxedSignalStorage<T>> Readable for ReadSignal<T, S> {
type Target = T;
type Storage = S;
#[track_caller]
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
T: 'static,
{
self.value
.try_peek_unchecked()
.unwrap()
.try_read_unchecked()
}
#[track_caller]
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
where
T: 'static,
{
self.value
.try_peek_unchecked()
.unwrap()
.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers
where
T: 'static,
{
self.value.try_peek_unchecked().unwrap().subscribers()
}
}
// We can't implement From<impl Readable<Target = T, Storage = S> > for ReadSignal<T, S>
// because it would conflict with the From<T> for T implementation, but we can implement it for
// all specific readable types
impl<
T: 'static,
S: CreateBoxedSignalStorage<Signal<T, S>> + BoxedSignalStorage<T> + Storage<SignalData<T>>,
> From<Signal<T, S>> for ReadSignal<T, S>
{
fn from(value: Signal<T, S>) -> Self {
Self::new_maybe_sync(value)
}
}
impl<T: PartialEq + 'static> From<Memo<T>> for ReadSignal<T> {
fn from(value: Memo<T>) -> Self {
Self::new(value)
}
}
impl<
T: 'static,
S: CreateBoxedSignalStorage<CopyValue<T, S>> + BoxedSignalStorage<T> + Storage<T>,
> From<CopyValue<T, S>> for ReadSignal<T, S>
{
fn from(value: CopyValue<T, S>) -> Self {
Self::new_maybe_sync(value)
}
}
impl<T, R> From<Global<T, R>> for ReadSignal<R>
where
T: Readable<Target = R, Storage = UnsyncStorage> + InitializeFromFunction<R> + Clone + 'static,
R: 'static,
{
fn from(value: Global<T, R>) -> Self {
Self::new(value)
}
}
impl<V, O, F, S> From<MappedSignal<O, V, F>> for ReadSignal<O, S>
where
O: ?Sized + 'static,
V: Readable<Storage = S> + 'static,
F: Fn(&V::Target) -> &O + 'static,
S: BoxedSignalStorage<O> + CreateBoxedSignalStorage<MappedSignal<O, V, F>>,
{
fn from(value: MappedSignal<O, V, F>) -> Self {
Self::new_maybe_sync(value)
}
}
impl<V, O, F, FMut, S> From<MappedMutSignal<O, V, F, FMut>> for ReadSignal<O, S>
where
O: ?Sized + 'static,
V: Readable<Storage = S> + 'static,
F: Fn(&V::Target) -> &O + 'static,
FMut: 'static,
S: BoxedSignalStorage<O> + CreateBoxedSignalStorage<MappedMutSignal<O, V, F, FMut>>,
{
fn from(value: MappedMutSignal<O, V, F, FMut>) -> Self {
Self::new_maybe_sync(value)
}
}
impl<T: ?Sized + 'static, S> From<WriteSignal<T, S>> for ReadSignal<T, S>
where
S: BoxedSignalStorage<T> + CreateBoxedSignalStorage<WriteSignal<T, S>>,
{
fn from(value: WriteSignal<T, S>) -> Self {
Self::new_maybe_sync(value)
}
}
/// A boxed version of [Writable] that can be used to store any writable type.
pub struct WriteSignal<T: ?Sized, S: BoxedSignalStorage<T> = UnsyncStorage> {
value: CopyValue<Box<S::DynWritable<sealed::SealedToken>>, S>,
}
impl<T: ?Sized + 'static> WriteSignal<T> {
/// Create a new boxed writable value.
pub fn new(
value: impl Writable<Target = T, Storage = UnsyncStorage, WriteMetadata: 'static> + 'static,
) -> Self {
Self::new_maybe_sync(value)
}
}
impl<T: ?Sized + 'static, S: BoxedSignalStorage<T>> WriteSignal<T, S> {
/// Create a new boxed writable value which may be sync
pub fn new_maybe_sync<R>(value: R) -> Self
where
R: Writable<Target = T, WriteMetadata: 'static>,
S: CreateBoxedSignalStorage<R>,
{
Self {
value: CopyValue::new_maybe_sync(S::new_writable(value, sealed::SealedToken)),
}
}
}
struct BoxWriteMetadata<W> {
value: W,
}
impl<W: Writable> BoxWriteMetadata<W> {
fn new(value: W) -> Self {
Self { value }
}
}
impl<W: Readable> Readable for BoxWriteMetadata<W> {
type Target = W::Target;
type Storage = W::Storage;
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
W::Target: 'static,
{
self.value.try_read_unchecked()
}
fn try_peek_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
W::Target: 'static,
{
self.value.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers
where
W::Target: 'static,
{
self.value.subscribers()
}
}
impl<W> Writable for BoxWriteMetadata<W>
where
W: Writable,
W::WriteMetadata: 'static,
{
type WriteMetadata = Box<dyn Any>;
fn try_write_unchecked(
&self,
) -> Result<crate::WritableRef<'static, Self>, generational_box::BorrowMutError>
where
W::Target: 'static,
{
self.value
.try_write_unchecked()
.map(|w| w.map_metadata(|data| Box::new(data) as Box<dyn Any>))
}
}
impl<T: ?Sized, S: BoxedSignalStorage<T>> Clone for WriteSignal<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T: ?Sized, S: BoxedSignalStorage<T>> Copy for WriteSignal<T, S> {}
impl<T: ?Sized, S: BoxedSignalStorage<T>> PartialEq for WriteSignal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
read_impls!(WriteSignal<T, S: BoxedSignalStorage<T>>);
write_impls!(WriteSignal<T, S: BoxedSignalStorage<T>>);
impl<T, S> IntoAttributeValue for WriteSignal<T, S>
where
T: Clone + IntoAttributeValue + 'static,
S: BoxedSignalStorage<T>,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<T, S> IntoDynNode for WriteSignal<T, S>
where
T: Clone + IntoDynNode + 'static,
S: BoxedSignalStorage<T>,
{
fn into_dyn_node(self) -> dioxus_core::DynamicNode {
self.with(|f| f.clone().into_dyn_node())
}
}
impl<T: Clone + 'static, S: BoxedSignalStorage<T>> Deref for WriteSignal<T, S> {
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
impl<T: ?Sized, S: BoxedSignalStorage<T>> Readable for WriteSignal<T, S> {
type Target = T;
type Storage = S;
#[track_caller]
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
T: 'static,
{
self.value
.try_peek_unchecked()
.unwrap()
.try_read_unchecked()
}
#[track_caller]
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
where
T: 'static,
{
self.value
.try_peek_unchecked()
.unwrap()
.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers
where
T: 'static,
{
self.value.try_peek_unchecked().unwrap().subscribers()
}
}
impl<T: ?Sized, S: BoxedSignalStorage<T>> Writable for WriteSignal<T, S> {
type WriteMetadata = Box<dyn Any>;
fn try_write_unchecked(
&self,
) -> Result<crate::WritableRef<'static, Self>, generational_box::BorrowMutError>
where
T: 'static,
{
self.value
.try_peek_unchecked()
.unwrap()
.try_write_unchecked()
}
}
// We can't implement From<impl Writable<Target = T, Storage = S>> for Write<T, S>
// because it would conflict with the From<T> for T implementation, but we can implement it for
// all specific readable types
impl<
T: 'static,
S: CreateBoxedSignalStorage<Signal<T, S>> + BoxedSignalStorage<T> + Storage<SignalData<T>>,
> From<Signal<T, S>> for WriteSignal<T, S>
{
fn from(value: Signal<T, S>) -> Self {
Self::new_maybe_sync(value)
}
}
impl<
T: 'static,
S: CreateBoxedSignalStorage<CopyValue<T, S>> + BoxedSignalStorage<T> + Storage<T>,
> From<CopyValue<T, S>> for WriteSignal<T, S>
{
fn from(value: CopyValue<T, S>) -> Self {
Self::new_maybe_sync(value)
}
}
impl<T, R> From<Global<T, R>> for WriteSignal<R>
where
T: Writable<Target = R, Storage = UnsyncStorage> + InitializeFromFunction<R> + Clone + 'static,
R: 'static,
{
fn from(value: Global<T, R>) -> Self {
Self::new(value)
}
}
impl<V, O, F, FMut, S> From<MappedMutSignal<O, V, F, FMut>> for WriteSignal<O, S>
where
O: ?Sized + 'static,
V: Writable<Storage = S> + 'static,
F: Fn(&V::Target) -> &O + 'static,
FMut: Fn(&mut V::Target) -> &mut O + 'static,
S: CreateBoxedSignalStorage<MappedMutSignal<O, V, F, FMut>> + BoxedSignalStorage<O>,
{
fn from(value: MappedMutSignal<O, V, F, FMut>) -> Self {
Self::new_maybe_sync(value)
}
}
/// A trait for creating boxed readable and writable signals. This is implemented for
/// [UnsyncStorage] and [SyncStorage].
///
/// You may need to add this trait as a bound when you use [ReadSignal] or [WriteSignal] while
/// remaining generic over syncness.
pub trait BoxedSignalStorage<T: ?Sized>:
Storage<Box<Self::DynReadable<sealed::SealedToken>>>
+ Storage<Box<Self::DynWritable<sealed::SealedToken>>>
+ sealed::Sealed
+ 'static
{
// This is not a public api, and is sealed to prevent external usage and implementations
#[doc(hidden)]
type DynReadable<Seal: sealed::SealedTokenTrait>: Readable<Target = T, Storage = Self> + ?Sized;
// This is not a public api, and is sealed to prevent external usage and implementations
#[doc(hidden)]
type DynWritable<Seal: sealed::SealedTokenTrait>: Writable<Target = T, Storage = Self, WriteMetadata = Box<dyn Any>>
+ ?Sized;
}
/// A trait for creating boxed readable and writable signals. This is implemented for
/// [UnsyncStorage] and [SyncStorage].
///
/// The storage type must implement `CreateReadOnlySignalStorage<T>` for every readable `T` type
/// to be used with `ReadSignal` and `WriteSignal`.
///
/// You may need to add this trait as a bound when you call [ReadSignal::new_maybe_sync] or
/// [WriteSignal::new_maybe_sync] while remaining generic over syncness.
pub trait CreateBoxedSignalStorage<T: Readable + ?Sized>:
BoxedSignalStorage<T::Target> + 'static
{
// This is not a public api, and is sealed to prevent external usage and implementations
#[doc(hidden)]
fn new_readable(
value: T,
_: sealed::SealedToken,
) -> Box<Self::DynReadable<sealed::SealedToken>>
where
T: Sized;
// This is not a public api, and is sealed to prevent external usage and implementations
#[doc(hidden)]
fn new_writable(
value: T,
_: sealed::SealedToken,
) -> Box<Self::DynWritable<sealed::SealedToken>>
where
T: Writable + Sized;
}
impl<T: ?Sized + 'static> BoxedSignalStorage<T> for UnsyncStorage {
type DynReadable<Seal: sealed::SealedTokenTrait> = dyn Readable<Target = T, Storage = Self>;
type DynWritable<Seal: sealed::SealedTokenTrait> =
dyn Writable<Target = T, Storage = Self, WriteMetadata = Box<dyn Any>>;
}
impl<T: Readable<Storage = UnsyncStorage> + ?Sized + 'static> CreateBoxedSignalStorage<T>
for UnsyncStorage
{
fn new_readable(value: T, _: sealed::SealedToken) -> Box<Self::DynReadable<sealed::SealedToken>>
where
T: Sized,
{
Box::new(value)
}
fn new_writable(value: T, _: sealed::SealedToken) -> Box<Self::DynWritable<sealed::SealedToken>>
where
T: Writable + Sized,
{
Box::new(BoxWriteMetadata::new(value))
}
}
impl<T: ?Sized + 'static> BoxedSignalStorage<T> for SyncStorage {
type DynReadable<Seal: sealed::SealedTokenTrait> =
dyn Readable<Target = T, Storage = Self> + Send + Sync;
type DynWritable<Seal: sealed::SealedTokenTrait> =
dyn Writable<Target = T, Storage = Self, WriteMetadata = Box<dyn Any>> + Send + Sync;
}
impl<T: Readable<Storage = SyncStorage> + Sync + Send + ?Sized + 'static>
CreateBoxedSignalStorage<T> for SyncStorage
{
fn new_readable(value: T, _: sealed::SealedToken) -> Box<Self::DynReadable<sealed::SealedToken>>
where
T: Sized,
{
Box::new(value)
}
fn new_writable(value: T, _: sealed::SealedToken) -> Box<Self::DynWritable<sealed::SealedToken>>
where
T: Writable + Sized,
{
Box::new(BoxWriteMetadata::new(value))
}
}
mod sealed {
use generational_box::{SyncStorage, UnsyncStorage};
pub trait Sealed {}
impl Sealed for UnsyncStorage {}
impl Sealed for SyncStorage {}
pub struct SealedToken;
pub trait SealedTokenTrait {}
impl SealedTokenTrait for SealedToken {}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/impls.rs | packages/signals/src/impls.rs | /// This macro is used to generate a `impl Default` block for any type with the function new_maybe_sync that takes a generic `T`
///
/// # Example
/// ```rust
/// use generational_box::*;
/// use dioxus::prelude::*;
/// use dioxus_core::Subscribers;
///
/// struct MyCopyValue<T, S: 'static> {
/// value: CopyValue<T, S>,
/// }
///
/// impl<T: 'static, S: Storage<T> + 'static> MyCopyValue<T, S> {
/// fn new_maybe_sync(value: T) -> Self {
/// Self { value: CopyValue::new_maybe_sync(value) }
/// }
/// }
///
/// impl<T, S: Storage<T> + 'static> Readable for MyCopyValue<T, S> {
/// type Target = T;
/// type Storage = S;
///
/// fn try_read_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn try_peek_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn subscribers(&self) -> Subscribers where T: 'static {
/// self.value.subscribers()
/// }
/// }
///
/// default_impl!(MyCopyValue<T, S: Storage<T>>);
/// ```
#[macro_export]
macro_rules! default_impl {
(
$ty:ident
// Accept generics
< T $(, $gen:ident $(: $gen_bound:path)?)* $(,)?>
// Accept extra bounds
$(
where
$(
$extra_bound_ty:ident: $extra_bound:path
),+
)?
) => {
impl<T: Default + 'static
$(, $gen $(: $gen_bound)?)*
> Default for $ty <T $(, $gen)*>
$(
where
$(
$extra_bound_ty: $extra_bound
),+
)?
{
#[track_caller]
fn default() -> Self {
Self::new_maybe_sync(Default::default())
}
}
}
}
/// This macro is used to generate `impl Display`, `impl Debug`, `impl PartialEq`, and `impl Eq` blocks for any Readable type that takes a generic `T`
///
/// # Example
/// ```rust
/// use generational_box::*;
/// use dioxus::prelude::*;
/// use dioxus_core::Subscribers;
///
/// struct MyCopyValue<T, S: 'static> {
/// value: CopyValue<T, S>,
/// }
///
/// impl<T: 'static, S: Storage<T> + 'static> Readable for MyCopyValue<T, S> where T: 'static {
/// type Target = T;
/// type Storage = S;
///
/// fn try_read_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn try_peek_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn subscribers(&self) -> Subscribers where T: 'static {
/// self.value.subscribers()
/// }
/// }
///
/// read_impls!(MyCopyValue<T, S: Storage<T>>);
/// ```
#[macro_export]
macro_rules! read_impls {
(
$ty:ident
// Accept generics
< T $(, $gen:ident $(: $gen_bound:path)?)* $(,)?>
// Accept extra bounds
$(
where
$(
$extra_bound_ty:ident: $extra_bound:path
),+
)?
) => {
$crate::fmt_impls!{
$ty<
T
$(
, $gen
$(: $gen_bound)?
)*
>
$(
where
$($extra_bound_ty: $extra_bound),*
)?
}
$crate::eq_impls!{
$ty<
T
$(
, $gen
$(: $gen_bound)?
)*
>
$(
where
$($extra_bound_ty: $extra_bound),*
)?
}
};
}
/// This macro is used to generate `impl Display`, and `impl Debug` blocks for any Readable type that takes a generic `T`
///
/// # Example
/// ```rust
/// use generational_box::*;
/// use dioxus::prelude::*;
/// use dioxus_core::Subscribers;
///
/// struct MyCopyValue<T, S: 'static> {
/// value: CopyValue<T, S>,
/// }
///
/// impl<T: 'static, S: Storage<T> + 'static> Readable for MyCopyValue<T, S> {
/// type Target = T;
/// type Storage = S;
///
/// fn try_read_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn try_peek_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn subscribers(&self) -> Subscribers where T: 'static {
/// self.value.subscribers()
/// }
/// }
///
/// fmt_impls!(MyCopyValue<T, S: Storage<T>>);
/// ```
#[macro_export]
macro_rules! fmt_impls {
(
$ty:ident
// Accept generics
< T $(, $gen:ident $(: $gen_bound:path)?)* $(,)?>
// Accept extra bounds
$(
where
$(
$extra_bound_ty:ident: $extra_bound:path
),+
)?
) => {
impl<
T: std::fmt::Display + 'static
$(, $gen $(: $gen_bound)?)*
> std::fmt::Display for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
#[track_caller]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.with(|v| std::fmt::Display::fmt(v, f))
}
}
impl<
T: std::fmt::Debug + 'static
$(, $gen $(: $gen_bound)?)*
> std::fmt::Debug for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
#[track_caller]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.with(|v| std::fmt::Debug::fmt(v, f))
}
}
};
}
/// This macro is used to generate `impl PartialEq` blocks for any Readable type that takes a generic `T`
///
/// # Example
/// ```rust
/// use generational_box::*;
/// use dioxus::prelude::*;
/// use dioxus_core::Subscribers;
///
/// struct MyCopyValue<T, S: 'static> {
/// value: CopyValue<T, S>,
/// }
///
/// impl<T: 'static, S: Storage<T> + 'static> Readable for MyCopyValue<T, S> {
/// type Target = T;
/// type Storage = S;
///
/// fn try_read_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn try_peek_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn subscribers(&self) -> Subscribers where T: 'static {
/// self.value.subscribers()
/// }
/// }
///
/// eq_impls!(MyCopyValue<T, S: Storage<T>>);
/// ```
#[macro_export]
macro_rules! eq_impls {
(
$ty:ident
// Accept generics
< T $(, $gen:ident $(: $gen_bound:path)?)* $(,)?>
// Accept extra bounds
$(
where
$(
$extra_bound_ty:ident: $extra_bound:path
),+
)?
) => {
impl<
T: PartialEq + 'static
$(, $gen $(: $gen_bound)?)*
> PartialEq<T> for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
#[track_caller]
fn eq(&self, other: &T) -> bool {
self.with(|v| *v == *other)
}
}
};
}
/// This macro is used to generate `impl Add`, `impl AddAssign`, `impl Sub`, `impl SubAssign`, `impl Mul`, `impl MulAssign`, `impl Div`, and `impl DivAssign` blocks for any Writable type that takes a generic `T`
///
/// # Example
/// ```rust, ignore
/// use generational_box::*;
/// use dioxus::prelude::*;
///
/// struct MyCopyValue<T, S: 'static> {
/// value: CopyValue<T, S>,
/// }
///
/// impl<T: 'static, S: Storage<T> + 'static> Readable for MyCopyValue<T, S> {
/// type Target = T;
/// type Storage = S;
///
/// fn try_read_unchecked(
/// &self,
/// ) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError> where T: 'static {
/// self.value.try_read_unchecked()
/// }
///
/// fn peek_unchecked(&self) -> ReadableRef<'static, Self> where T: 'static {
/// self.value.read_unchecked()
/// }
/// }
///
/// impl<T: 'static, S: Storage<T> + 'static> Writable for MyCopyValue<T, S> {
/// fn try_write_unchecked(
/// &self,
/// ) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> where T: 'static {
/// self.value.try_write_unchecked()
/// }
///
/// //...
/// }
///
/// write_impls!(MyCopyValue<T, S: Storage<T>>);
/// ```
#[macro_export]
macro_rules! write_impls {
(
$ty:ident
// Accept generics
< T $(, $gen:ident $(: $gen_bound:path)?)* $(,)?>
// Accept extra bounds
$(
where
$(
$extra_bound_ty:ident: $extra_bound:path
),+
)?) => {
impl<T: std::ops::Add<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::Add<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
type Output = T;
#[track_caller]
fn add(self, rhs: T) -> Self::Output {
self.with(|v| *v + rhs)
}
}
impl<T: std::ops::Add<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::AddAssign<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
#[track_caller]
fn add_assign(&mut self, rhs: T) {
self.with_mut(|v| *v = *v + rhs)
}
}
impl<T: std::ops::Sub<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::SubAssign<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
#[track_caller]
fn sub_assign(&mut self, rhs: T) {
self.with_mut(|v| *v = *v - rhs)
}
}
impl<T: std::ops::Sub<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::Sub<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
type Output = T;
#[track_caller]
fn sub(self, rhs: T) -> Self::Output {
self.with(|v| *v - rhs)
}
}
impl<T: std::ops::Mul<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::MulAssign<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
#[track_caller]
fn mul_assign(&mut self, rhs: T) {
self.with_mut(|v| *v = *v * rhs)
}
}
impl<T: std::ops::Mul<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::Mul<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
type Output = T;
#[track_caller]
fn mul(self, rhs: T) -> Self::Output {
self.with(|v| *v * rhs)
}
}
impl<T: std::ops::Div<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::DivAssign<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
#[track_caller]
fn div_assign(&mut self, rhs: T) {
self.with_mut(|v| *v = *v / rhs)
}
}
impl<T: std::ops::Div<Output = T> + Copy + 'static
$(, $gen $(: $gen_bound)?)*
> std::ops::Div<T>
for $ty<T $(, $gen)*>
$(
where
$($extra_bound_ty: $extra_bound,)*
)?
{
type Output = T;
#[track_caller]
fn div(self, rhs: T) -> Self::Output {
self.with(|v| *v / rhs)
}
}
};
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/memo.rs | packages/signals/src/memo.rs | use crate::{read::Readable, write_impls, ReadableRef, Signal};
use crate::{read_impls, GlobalMemo, ReadableExt, WritableExt};
use crate::{CopyValue, Writable};
use std::{
cell::RefCell,
ops::Deref,
sync::{atomic::AtomicBool, Arc},
};
use dioxus_core::{
current_scope_id, spawn_isomorphic, IntoAttributeValue, IntoDynNode, ReactiveContext, ScopeId,
Subscribers,
};
use futures_util::StreamExt;
use generational_box::{AnyStorage, BorrowResult, UnsyncStorage};
struct UpdateInformation<T> {
dirty: Arc<AtomicBool>,
callback: RefCell<Box<dyn FnMut() -> T>>,
}
#[doc = include_str!("../docs/memo.md")]
#[doc(alias = "Selector")]
#[doc(alias = "UseMemo")]
#[doc(alias = "Memorize")]
pub struct Memo<T> {
inner: Signal<T>,
update: CopyValue<UpdateInformation<T>>,
}
impl<T> Memo<T> {
/// Create a new memo
#[track_caller]
pub fn new(f: impl FnMut() -> T + 'static) -> Self
where
T: PartialEq + 'static,
{
Self::new_with_location(f, std::panic::Location::caller())
}
/// Create a new memo with an explicit location
pub fn new_with_location(
mut f: impl FnMut() -> T + 'static,
location: &'static std::panic::Location<'static>,
) -> Self
where
T: PartialEq + 'static,
{
let dirty = Arc::new(AtomicBool::new(false));
let (tx, mut rx) = futures_channel::mpsc::unbounded();
let callback = {
let dirty = dirty.clone();
move || {
dirty.store(true, std::sync::atomic::Ordering::Relaxed);
let _ = tx.unbounded_send(());
}
};
let rc = ReactiveContext::new_with_callback(callback, current_scope_id(), location);
// Create a new signal in that context, wiring up its dependencies and subscribers
let mut recompute = move || rc.reset_and_run_in(&mut f);
let value = recompute();
let recompute = RefCell::new(Box::new(recompute) as Box<dyn FnMut() -> T>);
let update = CopyValue::new(UpdateInformation {
dirty,
callback: recompute,
});
let state: Signal<T> = Signal::new_with_caller(value, location);
let memo = Memo {
inner: state,
update,
};
spawn_isomorphic(async move {
while rx.next().await.is_some() {
// Remove any pending updates
while rx.try_next().is_ok() {}
memo.recompute();
}
});
memo
}
/// Creates a new [`GlobalMemo`] that can be used anywhere inside your dioxus app. This memo will automatically be created once per app the first time you use it.
///
/// # Example
/// ```rust, no_run
/// # use dioxus::prelude::*;
/// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
/// // Create a new global memo that can be used anywhere in your app
/// static DOUBLED: GlobalMemo<i32> = Memo::global(|| SIGNAL() * 2);
///
/// fn App() -> Element {
/// rsx! {
/// button {
/// // When SIGNAL changes, the memo will update because the SIGNAL is read inside DOUBLED
/// onclick: move |_| *SIGNAL.write() += 1,
/// "{DOUBLED}"
/// }
/// }
/// }
/// ```
///
/// <div class="warning">
///
/// Global memos are generally not recommended for use in libraries because it makes it more difficult to allow multiple instances of components you define in your library.
///
/// </div>
#[track_caller]
pub const fn global(constructor: fn() -> T) -> GlobalMemo<T>
where
T: PartialEq + 'static,
{
GlobalMemo::new(constructor)
}
/// Rerun the computation and update the value of the memo if the result has changed.
#[tracing::instrument(skip(self))]
fn recompute(&self)
where
T: PartialEq + 'static,
{
let mut update_copy = self.update;
let update_write = update_copy.write();
let peak = self.inner.peek();
let new_value = (update_write.callback.borrow_mut())();
if new_value != *peak {
drop(peak);
let mut copy = self.inner;
copy.set(new_value);
}
// Always mark the memo as no longer dirty even if the value didn't change
update_write
.dirty
.store(false, std::sync::atomic::Ordering::Relaxed);
}
/// Get the scope that the signal was created in.
pub fn origin_scope(&self) -> ScopeId
where
T: 'static,
{
self.inner.origin_scope()
}
/// Get the id of the signal.
pub fn id(&self) -> generational_box::GenerationalBoxId
where
T: 'static,
{
self.inner.id()
}
}
impl<T> Readable for Memo<T>
where
T: PartialEq,
{
type Target = T;
type Storage = UnsyncStorage;
#[track_caller]
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
T: 'static,
{
// Read the inner generational box instead of the signal so we have more fine grained control over exactly when the subscription happens
let read = self.inner.inner.try_read_unchecked()?;
let needs_update = self
.update
.read()
.dirty
.swap(false, std::sync::atomic::Ordering::Relaxed);
let result = if needs_update {
drop(read);
// We shouldn't be subscribed to the value here so we don't trigger the scope we are currently in to rerun even though that scope got the latest value because we synchronously update the value: https://github.com/DioxusLabs/dioxus/issues/2416
self.recompute();
self.inner.inner.try_read_unchecked()
} else {
Ok(read)
};
// Subscribe to the current scope before returning the value
if let Ok(read) = &result {
if let Some(reactive_context) = ReactiveContext::current() {
tracing::trace!("Subscribing to the reactive context {}", reactive_context);
reactive_context.subscribe(read.subscribers.clone());
}
}
result.map(|read| <UnsyncStorage as AnyStorage>::map(read, |v| &v.value))
}
/// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
///
/// If the signal has been dropped, this will panic.
#[track_caller]
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
where
T: 'static,
{
self.inner.try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers
where
T: 'static,
{
self.inner.subscribers()
}
}
impl<T: 'static + PartialEq> Writable for Memo<T> {
type WriteMetadata = <Signal<T> as Writable>::WriteMetadata;
fn try_write_unchecked(
&self,
) -> Result<crate::WritableRef<'static, Self>, generational_box::BorrowMutError>
where
Self::Target: 'static,
{
self.inner.try_write_unchecked()
}
}
impl<T> IntoAttributeValue for Memo<T>
where
T: Clone + IntoAttributeValue + PartialEq + 'static,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<T> IntoDynNode for Memo<T>
where
T: Clone + IntoDynNode + PartialEq + 'static,
{
fn into_dyn_node(self) -> dioxus_core::DynamicNode {
self().into_dyn_node()
}
}
impl<T: 'static> PartialEq for Memo<T> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T: Clone> Deref for Memo<T>
where
T: PartialEq + 'static,
{
type Target = dyn Fn() -> T;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
read_impls!(Memo<T> where T: PartialEq);
write_impls!(Memo<T> where T: PartialEq);
impl<T> Clone for Memo<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Memo<T> {}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/warnings.rs | packages/signals/src/warnings.rs | //! Warnings that can be triggered by suspicious usage of signals
use warnings::warning;
/// A warning that is triggered when a copy value is used in a higher scope that it is owned by
#[warning]
pub fn copy_value_hoisted<T: 'static, S: generational_box::Storage<T> + 'static>(
value: &crate::CopyValue<T, S>,
caller: &'static std::panic::Location<'static>,
) {
let origin_scope = value.origin_scope;
let Some(rt) = dioxus_core::Runtime::try_current() else {
return;
};
if let Some(current_scope) = rt.try_current_scope_id() {
// If the current scope is a descendant of the origin scope or is the same scope, we don't need to warn
if origin_scope == current_scope || rt.is_descendant_of(current_scope, origin_scope) {
return;
}
let create_location = value.value.created_at().unwrap();
let broken_example = include_str!("../docs/hoist/error.rs");
let fixed_example = include_str!("../docs/hoist/fixed_list.rs");
// Otherwise, warn that the value is being used in a higher scope and may be dropped
tracing::warn!(
r#"A Copy Value created in {origin_scope:?} (at {create_location}). It will be dropped when that scope is dropped, but it was used in {current_scope:?} (at {caller}) which is not a descendant of the owning scope.
This may cause reads or writes to fail because the value is dropped while it still held.
Help:
Copy values (like CopyValue, Signal, Memo, and Resource) are owned by the scope they are created in. If you use the value in a scope that may be dropped after the origin scope,
it is very easy to use the value after it has been dropped. To fix this, you can move the value to the parent of all of the scopes that it is used in.
Broken example ❌:
```rust
{broken_example}
```
Fixed example ✅:
```rust
{fixed_example}
```"#
);
}
}
// Include the examples from the warning to make sure they compile
#[test]
#[allow(unused)]
fn hoist() {
mod broken {
use dioxus::prelude::*;
include!("../docs/hoist/error.rs");
}
mod fixed {
use dioxus::prelude::*;
include!("../docs/hoist/fixed_list.rs");
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/map_mut.rs | packages/signals/src/map_mut.rs | use std::ops::Deref;
use crate::{
read_impls, write_impls, Readable, ReadableExt, ReadableRef, Writable, WritableExt,
WritableRef, WriteLock,
};
use dioxus_core::{IntoAttributeValue, Subscribers};
use generational_box::{AnyStorage, BorrowResult};
/// A read only signal that has been mapped to a new type.
pub struct MappedMutSignal<
O: ?Sized,
V,
F = fn(&<V as Readable>::Target) -> &O,
FMut = fn(&mut <V as Readable>::Target) -> &mut O,
> {
value: V,
map_fn: F,
map_fn_mut: FMut,
_marker: std::marker::PhantomData<O>,
}
impl<V, O, F, FMut> Clone for MappedMutSignal<O, V, F, FMut>
where
V: Clone,
F: Clone,
FMut: Clone,
{
fn clone(&self) -> Self {
MappedMutSignal {
value: self.value.clone(),
map_fn: self.map_fn.clone(),
map_fn_mut: self.map_fn_mut.clone(),
_marker: std::marker::PhantomData,
}
}
}
impl<V, O, F, FMut> Copy for MappedMutSignal<O, V, F, FMut>
where
V: Copy,
F: Copy,
FMut: Copy,
{
}
impl<V, O, F, FMut> MappedMutSignal<O, V, F, FMut>
where
O: ?Sized,
{
/// Create a new mapped signal.
pub fn new(value: V, map_fn: F, map_fn_mut: FMut) -> Self {
MappedMutSignal {
value,
map_fn,
map_fn_mut,
_marker: std::marker::PhantomData,
}
}
}
impl<V, O, F, FMut> Readable for MappedMutSignal<O, V, F, FMut>
where
O: ?Sized,
V: Readable,
V::Target: 'static,
F: Fn(&V::Target) -> &O,
{
type Target = O;
type Storage = V::Storage;
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
O: 'static,
{
let value = self.value.try_read_unchecked()?;
Ok(V::Storage::map(value, |v| (self.map_fn)(v)))
}
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
where
O: 'static,
{
let value = self.value.try_peek_unchecked()?;
Ok(V::Storage::map(value, |v| (self.map_fn)(v)))
}
fn subscribers(&self) -> Subscribers
where
O: 'static,
{
self.value.subscribers()
}
}
impl<V, O, F, FMut> Writable for MappedMutSignal<O, V, F, FMut>
where
O: ?Sized,
V: Writable,
V::Target: 'static,
F: Fn(&V::Target) -> &O,
FMut: Fn(&mut V::Target) -> &mut O,
{
type WriteMetadata = V::WriteMetadata;
fn try_write_unchecked(
&self,
) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> {
let value = self.value.try_write_unchecked()?;
Ok(WriteLock::map(value, |v| (self.map_fn_mut)(v)))
}
}
impl<V, O, F, FMut> IntoAttributeValue for MappedMutSignal<O, V, F, FMut>
where
O: Clone + IntoAttributeValue + 'static,
V: Readable,
V::Target: 'static,
F: Fn(&V::Target) -> &O,
{
fn into_value(self) -> dioxus_core::AttributeValue {
self.with(|f| f.clone().into_value())
}
}
impl<V, O, F, FMut> PartialEq for MappedMutSignal<O, V, F, FMut>
where
O: ?Sized,
V: Readable + PartialEq,
F: PartialEq,
FMut: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.value == other.value
&& self.map_fn == other.map_fn
&& self.map_fn_mut == other.map_fn_mut
}
}
/// Allow calling a signal with signal() syntax
///
/// Currently only limited to clone types, though could probably specialize for string/arc/rc
impl<V, O, F, FMut> Deref for MappedMutSignal<O, V, F, FMut>
where
O: Clone + 'static,
V: Readable + 'static,
V::Target: 'static,
F: Fn(&V::Target) -> &O + 'static,
FMut: 'static,
{
type Target = dyn Fn() -> O;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
read_impls!(MappedMutSignal<T, V, F, FMut> where V: Readable<Target: 'static>, F: Fn(&V::Target) -> &T);
write_impls!(MappedMutSignal<T, V, F, FMut> where V: Writable<Target: 'static>, F: Fn(&V::Target) -> &T, FMut: Fn(&mut V::Target) -> &mut T);
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/global/signal.rs | packages/signals/src/global/signal.rs | use super::{Global, InitializeFromFunction};
use crate::read::ReadableExt;
use crate::read_impls;
use crate::Signal;
impl<T: 'static> InitializeFromFunction<T> for Signal<T> {
fn initialize_from_function(f: fn() -> T) -> Self {
Signal::new(f())
}
}
/// A signal that can be accessed from anywhere in the application and created in a static
pub type GlobalSignal<T> = Global<Signal<T>, T>;
impl<T: 'static> GlobalSignal<T> {
/// Get the generational id of the signal.
pub fn id(&self) -> generational_box::GenerationalBoxId {
self.resolve().id()
}
/// Resolve the global signal. This will try to get the existing value from the current virtual dom, and if it doesn't exist, it will create a new one.
pub fn signal(&self) -> Signal<T> {
self.resolve()
}
}
read_impls!(GlobalSignal<T>);
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/global/mod.rs | packages/signals/src/global/mod.rs | use dioxus_core::{Runtime, ScopeId, Subscribers};
use generational_box::BorrowResult;
use std::{any::Any, cell::RefCell, collections::HashMap, ops::Deref, panic::Location, rc::Rc};
mod memo;
pub use memo::*;
mod signal;
pub use signal::*;
use crate::{Readable, ReadableExt, ReadableRef, Signal, Writable, WritableExt, WritableRef};
/// A trait for an item that can be constructed from an initialization function
pub trait InitializeFromFunction<T> {
/// Create an instance of this type from an initialization function
fn initialize_from_function(f: fn() -> T) -> Self;
}
impl<T> InitializeFromFunction<T> for T {
fn initialize_from_function(f: fn() -> T) -> Self {
f()
}
}
/// A lazy value that is created once per application and can be accessed from anywhere in that application
pub struct Global<T, R = T> {
constructor: fn() -> R,
key: GlobalKey<'static>,
phantom: std::marker::PhantomData<fn() -> T>,
}
/// Allow calling a signal with signal() syntax
///
/// Currently only limited to copy types, though could probably specialize for string/arc/rc
impl<T: Clone, R: Clone> Deref for Global<T, R>
where
T: Readable<Target = R> + InitializeFromFunction<R> + 'static,
T::Target: 'static,
{
type Target = dyn Fn() -> R;
fn deref(&self) -> &Self::Target {
unsafe { ReadableExt::deref_impl(self) }
}
}
impl<T, R> Readable for Global<T, R>
where
T: Readable<Target = R> + InitializeFromFunction<R> + Clone + 'static,
{
type Target = R;
type Storage = T::Storage;
#[track_caller]
fn try_read_unchecked(
&self,
) -> Result<ReadableRef<'static, Self>, generational_box::BorrowError>
where
R: 'static,
{
self.resolve().try_read_unchecked()
}
#[track_caller]
fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
where
R: 'static,
{
self.resolve().try_peek_unchecked()
}
fn subscribers(&self) -> Subscribers
where
R: 'static,
{
self.resolve().subscribers()
}
}
impl<T: Clone, R> Writable for Global<T, R>
where
T: Writable<Target = R> + InitializeFromFunction<R> + 'static,
{
type WriteMetadata = T::WriteMetadata;
#[track_caller]
fn try_write_unchecked(
&self,
) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> {
self.resolve().try_write_unchecked()
}
}
impl<T: Clone, R> Global<T, R>
where
T: Writable<Target = R> + InitializeFromFunction<R> + 'static,
{
/// Write this value
pub fn write(&self) -> WritableRef<'static, T, R> {
self.resolve().try_write_unchecked().unwrap()
}
/// Run a closure with a mutable reference to the signal's value.
/// If the signal has been dropped, this will panic.
#[track_caller]
pub fn with_mut<O>(&self, f: impl FnOnce(&mut R) -> O) -> O
where
T::Target: 'static,
{
self.resolve().with_mut(f)
}
}
impl<T: Clone, R> Global<T, R>
where
T: InitializeFromFunction<R>,
{
#[track_caller]
/// Create a new global value
pub const fn new(constructor: fn() -> R) -> Self {
let key = std::panic::Location::caller();
Self {
constructor,
key: GlobalKey::new(key),
phantom: std::marker::PhantomData,
}
}
/// Create this global signal with a specific key.
/// This is useful for ensuring that the signal is unique across the application and accessible from
/// outside the application too.
#[track_caller]
pub const fn with_name(constructor: fn() -> R, key: &'static str) -> Self {
Self {
constructor,
key: GlobalKey::File {
file: key,
line: 0,
column: 0,
index: 0,
},
phantom: std::marker::PhantomData,
}
}
/// Create this global signal with a specific key.
/// This is useful for ensuring that the signal is unique across the application and accessible from
/// outside the application too.
#[track_caller]
pub const fn with_location(
constructor: fn() -> R,
file: &'static str,
line: u32,
column: u32,
index: usize,
) -> Self {
Self {
constructor,
key: GlobalKey::File {
file,
line: line as _,
column: column as _,
index: index as _,
},
phantom: std::marker::PhantomData,
}
}
/// Get the key for this global
pub fn key(&self) -> GlobalKey<'static> {
self.key.clone()
}
/// Resolve the global value. This will try to get the existing value from the current virtual dom, and if it doesn't exist, it will create a new one.
// NOTE: This is not called "get" or "value" because those methods overlap with Readable and Writable
pub fn resolve(&self) -> T
where
T: 'static,
{
let key = self.key();
let context = get_global_context();
// Get the entry if it already exists
{
let read = context.map.borrow();
if let Some(signal) = read.get(&key) {
return signal.downcast_ref::<T>().cloned().unwrap();
}
}
// Otherwise, create it
// Constructors are always run in the root scope
let signal = dioxus_core::Runtime::current().in_scope(ScopeId::ROOT, || {
T::initialize_from_function(self.constructor)
});
context
.map
.borrow_mut()
.insert(key, Box::new(signal.clone()));
signal
}
/// Get the scope the signal was created in.
pub fn origin_scope(&self) -> ScopeId {
ScopeId::ROOT
}
}
/// The context for global signals
#[derive(Clone, Default)]
pub struct GlobalLazyContext {
map: Rc<RefCell<HashMap<GlobalKey<'static>, Box<dyn Any>>>>,
}
/// A key used to identify a signal in the global signal context
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum GlobalKey<'a> {
/// A key derived from a `std::panic::Location` type
File {
/// The file name
file: &'a str,
/// The line number
line: u32,
/// The column number
column: u32,
/// The index of the signal in the file - used to disambiguate macro calls
index: u32,
},
/// A raw key derived just from a string
Raw(&'a str),
}
impl<'a> GlobalKey<'a> {
/// Create a new key from a location
pub const fn new(key: &'a Location<'a>) -> Self {
GlobalKey::File {
file: key.file(),
line: key.line(),
column: key.column(),
index: 0,
}
}
}
impl From<&'static Location<'static>> for GlobalKey<'static> {
fn from(key: &'static Location<'static>) -> Self {
Self::new(key)
}
}
impl GlobalLazyContext {
/// Get a signal with the given string key
/// The key will be converted to a UUID with the appropriate internal namespace
pub fn get_signal_with_key<T: 'static>(&self, key: GlobalKey) -> Option<Signal<T>> {
self.map.borrow().get(&key).map(|f| {
*f.downcast_ref::<Signal<T>>().unwrap_or_else(|| {
panic!(
"Global signal with key {:?} is not of the expected type. Keys are {:?}",
key,
self.map.borrow().keys()
)
})
})
}
#[doc(hidden)]
/// Clear all global signals of a given type.
pub fn clear<T: 'static>(&self) {
self.map.borrow_mut().retain(|_k, v| !v.is::<T>());
}
}
/// Get the global context for signals
pub fn get_global_context() -> GlobalLazyContext {
let rt = Runtime::current();
match rt.has_context(ScopeId::ROOT) {
Some(context) => context,
None => rt.provide_context(ScopeId::ROOT, Default::default()),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Test that keys of global signals are correctly generated and different from one another.
/// We don't want signals to merge, but we also want them to use both string IDs and memory addresses.
#[test]
fn test_global_keys() {
// we're using consts since it's harder than statics due to merging - these won't be merged
const MYSIGNAL: GlobalSignal<i32> = GlobalSignal::new(|| 42);
const MYSIGNAL2: GlobalSignal<i32> = GlobalSignal::new(|| 42);
const MYSIGNAL3: GlobalSignal<i32> = GlobalSignal::with_name(|| 42, "custom-keyed");
let a = MYSIGNAL.key();
let b = MYSIGNAL.key();
let c = MYSIGNAL.key();
assert_eq!(a, b);
assert_eq!(b, c);
let d = MYSIGNAL2.key();
assert_ne!(a, d);
let e = MYSIGNAL3.key();
assert_ne!(a, e);
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/src/global/memo.rs | packages/signals/src/global/memo.rs | use super::{Global, InitializeFromFunction};
use crate::read::ReadableExt;
use crate::read_impls;
use crate::Memo;
impl<T: PartialEq + 'static> InitializeFromFunction<T> for Memo<T> {
fn initialize_from_function(f: fn() -> T) -> Self {
Memo::new(f)
}
}
/// A memo that can be accessed from anywhere in the application and created in a static
pub type GlobalMemo<T> = Global<Memo<T>, T>;
impl<T: PartialEq + 'static> GlobalMemo<T> {
/// Get the generational id of the signal.
pub fn id(&self) -> generational_box::GenerationalBoxId {
self.resolve().id()
}
/// Resolve the global memo. This will try to get the existing value from the current virtual dom, and if it doesn't exist, it will create a new one.
pub fn memo(&self) -> Memo<T> {
self.resolve()
}
}
read_impls!(GlobalMemo<T> where T: PartialEq);
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/tests/subscribe.rs | packages/signals/tests/subscribe.rs | #![allow(unused, non_upper_case_globals, non_snake_case)]
use dioxus_core::{current_scope_id, generation, NoOpMutations};
use std::collections::HashMap;
use std::rc::Rc;
use dioxus::prelude::*;
use dioxus_core::ElementId;
use dioxus_signals::*;
use std::cell::RefCell;
#[test]
fn reading_subscribes() {
tracing_subscriber::fmt::init();
#[derive(Default)]
struct RunCounter {
parent: usize,
children: HashMap<ScopeId, usize>,
}
let counter = Rc::new(RefCell::new(RunCounter::default()));
let mut dom = VirtualDom::new_with_props(
|props: Rc<RefCell<RunCounter>>| {
let mut signal = use_signal(|| 0);
println!("Parent: {:?}", current_scope_id());
if generation() == 1 {
signal += 1;
}
props.borrow_mut().parent += 1;
rsx! {
for id in 0..10 {
Child {
signal: signal,
counter: props.clone()
}
}
}
},
counter.clone(),
);
#[derive(Props, Clone)]
struct ChildProps {
signal: Signal<usize>,
counter: Rc<RefCell<RunCounter>>,
}
impl PartialEq for ChildProps {
fn eq(&self, other: &Self) -> bool {
self.signal == other.signal
}
}
fn Child(props: ChildProps) -> Element {
println!("Child: {:?}", current_scope_id());
*props
.counter
.borrow_mut()
.children
.entry(current_scope_id())
.or_default() += 1;
rsx! {
"{props.signal}"
}
}
dom.rebuild_in_place();
{
let current_counter = counter.borrow();
assert_eq!(current_counter.parent, 1);
for (scope_id, rerun_count) in current_counter.children.iter() {
assert_eq!(rerun_count, &1);
}
}
dom.mark_dirty(ScopeId::APP);
dom.render_immediate(&mut NoOpMutations);
dom.render_immediate(&mut NoOpMutations);
{
let current_counter = counter.borrow();
assert_eq!(current_counter.parent, 2);
for (scope_id, rerun_count) in current_counter.children.iter() {
assert_eq!(rerun_count, &2);
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/tests/memo.rs | packages/signals/tests/memo.rs | #![allow(unused, non_upper_case_globals, non_snake_case)]
use dioxus::html::p;
use dioxus::prelude::*;
use dioxus_core::NoOpMutations;
use dioxus_core::{generation, ElementId};
use dioxus_signals::*;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
fn memos_rerun() {
tracing_subscriber::fmt::init();
#[derive(Default)]
struct RunCounter {
component: usize,
effect: usize,
}
let counter = Rc::new(RefCell::new(RunCounter::default()));
let mut dom = VirtualDom::new_with_props(
|counter: Rc<RefCell<RunCounter>>| {
counter.borrow_mut().component += 1;
let mut signal = use_signal(|| 0);
let memo = use_memo({
to_owned![counter];
move || {
counter.borrow_mut().effect += 1;
println!("Signal: {:?}", signal);
signal()
}
});
assert_eq!(memo(), 0);
signal += 1;
assert_eq!(memo(), 1);
rsx! {
div {}
}
},
counter.clone(),
);
dom.rebuild_in_place();
let current_counter = counter.borrow();
assert_eq!(current_counter.component, 1);
assert_eq!(current_counter.effect, 2);
}
#[test]
fn memos_prevents_component_rerun() {
#[derive(Default)]
struct RunCounter {
component: usize,
memo: usize,
}
let counter = Rc::new(RefCell::new(RunCounter::default()));
let mut dom = VirtualDom::new_with_props(
|props: Rc<RefCell<RunCounter>>| {
let mut signal = use_signal(|| 0);
if generation() == 1 {
*signal.write() = 0;
}
if generation() == 2 {
println!("Writing to signal");
*signal.write() = 1;
}
rsx! {
Child {
signal: signal,
counter: props.clone(),
}
}
},
counter.clone(),
);
#[derive(Default, Props, Clone)]
struct ChildProps {
signal: Signal<usize>,
counter: Rc<RefCell<RunCounter>>,
}
impl PartialEq for ChildProps {
fn eq(&self, other: &Self) -> bool {
self.signal == other.signal
}
}
fn Child(props: ChildProps) -> Element {
let counter = &props.counter;
let signal = props.signal;
counter.borrow_mut().component += 1;
let memo = use_memo({
to_owned![counter];
move || {
counter.borrow_mut().memo += 1;
println!("Signal: {:?}", signal);
signal()
}
});
match generation() {
0 => {
assert_eq!(memo(), 0);
}
1 => {
assert_eq!(memo(), 1);
}
_ => panic!("Unexpected generation"),
}
rsx! {
div {}
}
}
dom.rebuild_in_place();
dom.mark_dirty(ScopeId::APP);
dom.render_immediate(&mut NoOpMutations);
{
let current_counter = counter.borrow();
assert_eq!(current_counter.component, 1);
assert_eq!(current_counter.memo, 2);
}
dom.mark_dirty(ScopeId::APP);
dom.render_immediate(&mut NoOpMutations);
dom.render_immediate(&mut NoOpMutations);
{
let current_counter = counter.borrow();
assert_eq!(current_counter.component, 2);
assert_eq!(current_counter.memo, 3);
}
}
// Regression test for https://github.com/DioxusLabs/dioxus/issues/2990
#[test]
fn memos_sync_rerun_after_unrelated_write() {
static PASSED: AtomicBool = AtomicBool::new(false);
let mut dom = VirtualDom::new(|| {
let mut signal = use_signal(|| 0);
let memo = use_memo(move || dbg!(signal() < 2));
if generation() == 0 {
assert!(memo());
signal += 1;
} else {
// It should be fine to hold the write and read the memo at the same time
let mut write = signal.write();
println!("Memo: {:?}", memo());
assert!(memo());
*write = 2;
drop(write);
assert!(!memo());
PASSED.store(true, std::sync::atomic::Ordering::SeqCst);
}
rsx! {
div {}
}
});
dom.rebuild_in_place();
dom.mark_dirty(ScopeId::APP);
dom.render_immediate(&mut NoOpMutations);
assert!(PASSED.load(Ordering::SeqCst));
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/tests/create.rs | packages/signals/tests/create.rs | #![allow(unused, non_upper_case_globals, non_snake_case)]
use dioxus::prelude::*;
use dioxus_core::{generation, ElementId, NoOpMutations};
use dioxus_signals::*;
#[test]
fn create_signals_global() {
let mut dom = VirtualDom::new(|| {
rsx! {
for _ in 0..10 {
Child {}
}
}
});
fn Child() -> Element {
let signal = create_without_cx();
rsx! {
"{signal}"
}
}
dom.rebuild_in_place();
fn create_without_cx() -> Signal<String> {
Signal::new("hello world".to_string())
}
}
#[test]
fn deref_signal() {
let mut dom = VirtualDom::new(|| {
rsx! {
for _ in 0..10 {
Child {}
}
}
});
fn Child() -> Element {
let signal = Signal::new("hello world".to_string());
// You can call signals like functions to get a Ref of their value.
assert_eq!(&*signal(), "hello world");
rsx! {
"hello world"
}
}
dom.rebuild_in_place();
}
#[test]
fn drop_signals() {
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
static SIGNAL_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
let mut dom = VirtualDom::new(|| {
let generation = generation();
let count = if generation % 2 == 0 { 10 } else { 0 };
rsx! {
for _ in 0..count {
Child {}
}
}
});
fn Child() -> Element {
struct TracksDrops;
impl Drop for TracksDrops {
fn drop(&mut self) {
SIGNAL_DROP_COUNT.fetch_add(1, Ordering::Relaxed);
}
}
use_signal(|| TracksDrops);
rsx! {
""
}
}
dom.rebuild_in_place();
dom.mark_dirty(ScopeId::APP);
dom.render_immediate(&mut NoOpMutations);
assert_eq!(SIGNAL_DROP_COUNT.load(Ordering::Relaxed), 10);
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/docs/hoist/error.rs | packages/signals/docs/hoist/error.rs | #[component]
fn Counters() -> Element {
let counts = use_signal(Vec::new);
let mut children = use_signal(|| 0);
rsx! {
button { onclick: move |_| children += 1, "Add child" }
button { onclick: move |_| children -= 1, "Remove child" }
// A signal from a child is read or written to in a parent scope
"{counts:?}"
for _ in 0..children() {
Counter {
counts
}
}
}
}
#[component]
fn Counter(mut counts: Signal<Vec<Signal<i32>>>) -> Element {
let mut signal_owned_by_child = use_signal(|| 0);
// Moving the signal up to the parent may cause issues if you read the signal after the child scope is dropped
use_hook(|| counts.push(signal_owned_by_child));
rsx! {
button {
onclick: move |_| signal_owned_by_child += 1,
"{signal_owned_by_child}"
}
}
}
| rust | Apache-2.0 | ec8f31dece5c75371177bf080bab46dff54ffd0e | 2026-01-04T15:32:28.012891Z | false |
DioxusLabs/dioxus | https://github.com/DioxusLabs/dioxus/blob/ec8f31dece5c75371177bf080bab46dff54ffd0e/packages/signals/docs/hoist/fixed_list.rs | packages/signals/docs/hoist/fixed_list.rs | #[component]
fn Counters() -> Element {
let mut counts = use_signal(Vec::new);
rsx! {
button { onclick: move |_| counts.write().push(0), "Add child" }
button {
onclick: move |_| {
counts.write().pop();
},
"Remove child"
}
"{counts:?}"
// Instead of passing up a signal, we can just write to the signal that lives in the parent
for index in 0..counts.len() {
Counter {
index,
counts
}
}
}
}
#[component]
fn Counter(index: usize, mut counts: Signal<Vec<i32>>) -> Element {
rsx! {
button {
onclick: move |_| counts.write()[index] += 1,
"{counts.read()[index]}"
}
}
}
| 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.