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 |
|---|---|---|---|---|---|---|---|---|
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/signal/arc_trigger.rs | reactive_graph/src/signal/arc_trigger.rs | use super::subscriber_traits::AsSubscriberSet;
use crate::{
graph::{ReactiveNode, SubscriberSet},
traits::{DefinedAt, IsDisposed, Notify, Track},
};
use std::{
fmt::{Debug, Formatter, Result},
panic::Location,
sync::{Arc, RwLock},
};
/// A trigger is a data-less signal with the sole purpose of notifying other reactive code of a change.
///
/// This can be useful for when using external data not stored in signals, for example.
pub struct ArcTrigger {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) inner: Arc<RwLock<SubscriberSet>>,
}
impl ArcTrigger {
/// Creates a new trigger.
#[track_caller]
pub fn new() -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: Default::default(),
}
}
}
impl Default for ArcTrigger {
fn default() -> Self {
Self::new()
}
}
impl Clone for ArcTrigger {
#[track_caller]
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
inner: Arc::clone(&self.inner),
}
}
}
impl Debug for ArcTrigger {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("ArcTrigger").finish()
}
}
impl IsDisposed for ArcTrigger {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl AsSubscriberSet for ArcTrigger {
type Output = Arc<RwLock<SubscriberSet>>;
#[inline(always)]
fn as_subscriber_set(&self) -> Option<Self::Output> {
Some(Arc::clone(&self.inner))
}
}
impl Notify for Vec<ArcTrigger> {
fn notify(&self) {
for trigger in self {
trigger.notify();
}
}
}
impl Track for Vec<ArcTrigger> {
fn track(&self) {
for trigger in self {
trigger.track();
}
}
}
impl DefinedAt for ArcTrigger {
#[inline(always)]
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
impl Notify for ArcTrigger {
fn notify(&self) {
self.inner.mark_dirty();
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/signal/rw.rs | reactive_graph/src/signal/rw.rs | use super::{
guards::{Plain, ReadGuard},
subscriber_traits::AsSubscriberSet,
ArcReadSignal, ArcRwSignal, ArcWriteSignal, ReadSignal, WriteSignal,
};
use crate::{
graph::{ReactiveNode, SubscriberSet},
owner::{ArenaItem, FromLocal, LocalStorage, Storage, SyncStorage},
signal::guards::{UntrackedWriteGuard, WriteGuard},
traits::{
DefinedAt, Dispose, IntoInner, IsDisposed, Notify, ReadUntracked,
UntrackableGuard, Write,
},
unwrap_signal,
};
use core::fmt::Debug;
use guardian::ArcRwLockWriteGuardian;
use std::{
hash::Hash,
panic::Location,
sync::{Arc, RwLock},
};
/// An arena-allocated signal that can be read from or written to.
///
/// A signal is a piece of data that may change over time, and notifies other
/// code when it has changed. This is the atomic unit of reactivity, which begins all other
/// processes of reactive updates.
///
/// This is an arena-allocated signal, which is `Copy` and is disposed when its reactive
/// [`Owner`](crate::owner::Owner) cleans up. For a reference-counted signal that lives
/// as long as a reference to it is alive, see [`ArcRwSignal`].
///
/// ## Core Trait Implementations
///
/// ### Reading the Value
/// - [`.get()`](crate::traits::Get) clones the current value of the signal.
/// If you call it within an effect, it will cause that effect to subscribe
/// to the signal, and to re-run whenever the value of the signal changes.
/// - [`.get_untracked()`](crate::traits::GetUntracked) clones the value of
/// the signal without reactively tracking it.
/// - [`.read()`](crate::traits::Read) returns a guard that allows accessing the
/// value of the signal by reference. If you call it within an effect, it will
/// cause that effect to subscribe to the signal, and to re-run whenever the
/// value of the signal changes.
/// - [`.read_untracked()`](crate::traits::ReadUntracked) gives access to the
/// current value of the signal without reactively tracking it.
/// - [`.with()`](crate::traits::With) allows you to reactively access the signal’s
/// value without cloning by applying a callback function.
/// - [`.with_untracked()`](crate::traits::WithUntracked) allows you to access
/// the signal’s value by applying a callback function without reactively
/// tracking it.
/// - [`.to_stream()`](crate::traits::ToStream) converts the signal to an `async`
/// stream of values.
///
/// ### Updating the Value
/// - [`.set()`](crate::traits::Set) sets the signal to a new value.
/// - [`.update()`](crate::traits::Update) updates the value of the signal by
/// applying a closure that takes a mutable reference.
/// - [`.write()`](crate::traits::Write) returns a guard through which the signal
/// can be mutated, and which notifies subscribers when it is dropped.
///
/// > Each of these has a related `_untracked()` method, which updates the signal
/// > without notifying subscribers. Untracked updates are not desirable in most
/// > cases, as they cause “tearing” between the signal’s value and its observed
/// > value. If you want a non-reactive container, used [`ArenaItem`] instead.
///
/// ## Examples
///
/// ```
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let count = ArcRwSignal::new(0);
///
/// // ✅ calling the getter clones and returns the value
/// // this can be `count()` on nightly
/// assert_eq!(count.get(), 0);
///
/// // ✅ calling the setter sets the value
/// // this can be `set_count(1)` on nightly
/// count.set(1);
/// assert_eq!(count.get(), 1);
///
/// // ❌ you could call the getter within the setter
/// // set_count.set(count.get() + 1);
///
/// // ✅ however it's more efficient to use .update() and mutate the value in place
/// count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count.get(), 2);
///
/// // ✅ you can create "derived signals" with a Fn() -> T interface
/// let double_count = {
/// // clone before moving into the closure because we use it below
/// let count = count.clone();
/// move || count.get() * 2
/// };
/// count.set(0);
/// assert_eq!(double_count(), 0);
/// count.set(1);
/// assert_eq!(double_count(), 2);
/// ```
pub struct RwSignal<T, S = SyncStorage> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: ArenaItem<ArcRwSignal<T>, S>,
}
impl<T, S> Dispose for RwSignal<T, S> {
fn dispose(self) {
self.inner.dispose()
}
}
impl<T> RwSignal<T>
where
T: Send + Sync + 'static,
{
/// Creates a new signal, taking the initial value as its argument.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
#[track_caller]
pub fn new(value: T) -> Self {
Self::new_with_storage(value)
}
}
impl<T, S> RwSignal<T, S>
where
T: 'static,
S: Storage<ArcRwSignal<T>>,
{
/// Creates a new signal with the given arena storage method.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
#[track_caller]
pub fn new_with_storage(value: T) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcRwSignal::new(value)),
}
}
}
impl<T> RwSignal<T, LocalStorage>
where
T: 'static,
{
/// Creates a new signal, taking the initial value as its argument. Unlike [`RwSignal::new`],
/// this pins the value to the current thread. Accessing it from any other thread will panic.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
#[track_caller]
pub fn new_local(value: T) -> Self {
Self::new_with_storage(value)
}
}
impl<T, S> RwSignal<T, S>
where
T: 'static,
S: Storage<ArcRwSignal<T>> + Storage<ArcReadSignal<T>>,
{
/// Returns a read-only handle to the signal.
#[inline(always)]
#[track_caller]
pub fn read_only(&self) -> ReadSignal<T, S> {
ReadSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(
self.inner
.try_get_value()
.map(|inner| inner.read_only())
.unwrap_or_else(unwrap_signal!(self)),
),
}
}
}
impl<T, S> RwSignal<T, S>
where
T: 'static,
S: Storage<ArcRwSignal<T>> + Storage<ArcWriteSignal<T>>,
{
/// Returns a write-only handle to the signal.
#[inline(always)]
#[track_caller]
pub fn write_only(&self) -> WriteSignal<T, S> {
WriteSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(
self.inner
.try_get_value()
.map(|inner| inner.write_only())
.unwrap_or_else(unwrap_signal!(self)),
),
}
}
}
impl<T, S> RwSignal<T, S>
where
T: 'static,
S: Storage<ArcRwSignal<T>>
+ Storage<ArcWriteSignal<T>>
+ Storage<ArcReadSignal<T>>,
{
/// Splits the signal into its readable and writable halves.
#[track_caller]
#[inline(always)]
pub fn split(&self) -> (ReadSignal<T, S>, WriteSignal<T, S>) {
(self.read_only(), self.write_only())
}
/// Reunites the two halves of a signal. Returns `None` if the two signals
/// provided were not created from the same signal.
#[track_caller]
pub fn unite(
read: ReadSignal<T, S>,
write: WriteSignal<T, S>,
) -> Option<Self> {
match (read.inner.try_get_value(), write.inner.try_get_value()) {
(Some(read), Some(write)) => {
if Arc::ptr_eq(&read.inner, &write.inner) {
Some(Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcRwSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::clone(&read.value),
inner: Arc::clone(&read.inner),
}),
})
} else {
None
}
}
_ => None,
}
}
}
impl<T, S> Copy for RwSignal<T, S> {}
impl<T, S> Clone for RwSignal<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Debug for RwSignal<T, S>
where
S: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RwSignal")
.field("type", &std::any::type_name::<T>())
.field("store", &self.inner)
.finish()
}
}
impl<T, S> Default for RwSignal<T, S>
where
T: Default + 'static,
S: Storage<ArcRwSignal<T>>,
{
#[track_caller]
fn default() -> Self {
Self::new_with_storage(T::default())
}
}
impl<T, S> PartialEq for RwSignal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, S> Eq for RwSignal<T, S> {}
impl<T, S> Hash for RwSignal<T, S> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.hash(state);
}
}
impl<T, S> DefinedAt for RwSignal<T, S> {
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
impl<T: 'static, S> IsDisposed for RwSignal<T, S> {
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<T, S> IntoInner for RwSignal<T, S>
where
S: Storage<ArcRwSignal<T>>,
{
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
self.inner.into_inner()?.into_inner()
}
}
impl<T, S> AsSubscriberSet for RwSignal<T, S>
where
S: Storage<ArcRwSignal<T>>,
{
type Output = Arc<RwLock<SubscriberSet>>;
fn as_subscriber_set(&self) -> Option<Self::Output> {
self.inner
.try_with_value(|inner| inner.as_subscriber_set())
.flatten()
}
}
impl<T, S> ReadUntracked for RwSignal<T, S>
where
T: 'static,
S: Storage<ArcRwSignal<T>>,
{
type Value = ReadGuard<T, Plain<T>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.inner
.try_get_value()
.map(|inner| inner.read_untracked())
}
}
impl<T, S> Notify for RwSignal<T, S>
where
S: Storage<ArcRwSignal<T>>,
{
fn notify(&self) {
self.mark_dirty();
}
}
impl<T, S> Write for RwSignal<T, S>
where
T: 'static,
S: Storage<ArcRwSignal<T>>,
{
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
let guard = self.inner.try_with_value(|n| {
ArcRwLockWriteGuardian::take(Arc::clone(&n.value)).ok()
})??;
Some(WriteGuard::new(*self, guard))
}
#[allow(refining_impl_trait)]
fn try_write_untracked(&self) -> Option<UntrackedWriteGuard<Self::Value>> {
self.inner
.try_with_value(|n| n.try_write_untracked())
.flatten()
}
}
impl<T> From<ArcRwSignal<T>> for RwSignal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcRwSignal<T>) -> Self {
RwSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<'a, T> From<&'a ArcRwSignal<T>> for RwSignal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: &'a ArcRwSignal<T>) -> Self {
value.clone().into()
}
}
impl<T> FromLocal<ArcRwSignal<T>> for RwSignal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from_local(value: ArcRwSignal<T>) -> Self {
RwSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T, S> From<RwSignal<T, S>> for ArcRwSignal<T>
where
T: 'static,
S: Storage<ArcRwSignal<T>>,
{
#[track_caller]
fn from(value: RwSignal<T, S>) -> Self {
value
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(value))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/inner.rs | reactive_graph/src/computed/inner.rs | use crate::{
graph::{
AnySource, AnySubscriber, Observer, ReactiveNode, ReactiveNodeState,
Source, SourceSet, Subscriber, SubscriberSet, WithObserver,
},
owner::{Owner, Storage, StorageAccess},
};
use or_poisoned::OrPoisoned;
use std::{
fmt::Debug,
sync::{Arc, RwLock, RwLockWriteGuard},
};
pub struct MemoInner<T, S>
where
S: Storage<T>,
{
/// Must always be acquired *after* the reactivity lock
pub(crate) value: Arc<RwLock<Option<S::Wrapped>>>,
#[allow(clippy::type_complexity)]
pub(crate) fun: Arc<dyn Fn(Option<T>) -> (T, bool) + Send + Sync>,
pub(crate) owner: Owner,
pub(crate) reactivity: RwLock<MemoInnerReactivity>,
}
pub(crate) struct MemoInnerReactivity {
pub(crate) state: ReactiveNodeState,
pub(crate) sources: SourceSet,
pub(crate) subscribers: SubscriberSet,
pub(crate) any_subscriber: AnySubscriber,
}
impl<T, S> Debug for MemoInner<T, S>
where
S: Storage<T>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MemoInner").finish_non_exhaustive()
}
}
impl<T: 'static, S> MemoInner<T, S>
where
S: Storage<T>,
{
#[allow(clippy::type_complexity)]
pub fn new(
fun: Arc<dyn Fn(Option<T>) -> (T, bool) + Send + Sync>,
any_subscriber: AnySubscriber,
) -> Self {
Self {
value: Arc::new(RwLock::new(None)),
fun,
owner: Owner::new(),
reactivity: RwLock::new(MemoInnerReactivity {
state: ReactiveNodeState::Dirty,
sources: Default::default(),
subscribers: SubscriberSet::new(),
any_subscriber,
}),
}
}
}
impl<T: 'static, S> ReactiveNode for MemoInner<T, S>
where
S: Storage<T>,
{
fn mark_dirty(&self) {
self.reactivity.write().or_poisoned().state = ReactiveNodeState::Dirty;
self.mark_subscribers_check();
}
fn mark_check(&self) {
/// codegen optimisation:
fn inner(reactivity: &RwLock<MemoInnerReactivity>) {
{
let mut lock = reactivity.write().or_poisoned();
if lock.state != ReactiveNodeState::Dirty {
lock.state = ReactiveNodeState::Check;
}
}
for sub in
(&reactivity.read().or_poisoned().subscribers).into_iter()
{
sub.mark_check();
}
}
inner(&self.reactivity);
}
fn mark_subscribers_check(&self) {
let lock = self.reactivity.read().or_poisoned();
for sub in (&lock.subscribers).into_iter() {
sub.mark_check();
}
}
fn update_if_necessary(&self) -> bool {
/// codegen optimisation:
fn needs_update(reactivity: &RwLock<MemoInnerReactivity>) -> bool {
let (state, sources) = {
let inner = reactivity.read().or_poisoned();
(inner.state, inner.sources.clone())
};
match state {
ReactiveNodeState::Clean => false,
ReactiveNodeState::Dirty => true,
ReactiveNodeState::Check => {
(&sources).into_iter().any(|source| {
source.update_if_necessary()
|| reactivity.read().or_poisoned().state
== ReactiveNodeState::Dirty
})
}
}
}
if needs_update(&self.reactivity) {
// No deadlock risk, because we only hold the value lock.
let value = self.value.write().or_poisoned().take();
/// codegen optimisation:
fn inner_1(
reactivity: &RwLock<MemoInnerReactivity>,
) -> AnySubscriber {
let any_subscriber =
reactivity.read().or_poisoned().any_subscriber.clone();
any_subscriber.clear_sources(&any_subscriber);
any_subscriber
}
let any_subscriber = inner_1(&self.reactivity);
let (new_value, changed) = self.owner.with_cleanup(|| {
any_subscriber.with_observer(|| {
(self.fun)(value.map(StorageAccess::into_taken))
})
});
// Two locks are acquired, so order matters.
let reactivity_lock = self.reactivity.write().or_poisoned();
{
// Safety: Can block endlessly if the user is has a ReadGuard on the value
let mut value_lock = self.value.write().or_poisoned();
*value_lock = Some(S::wrap(new_value));
}
/// codegen optimisation:
fn inner_2(
changed: bool,
mut reactivity_lock: RwLockWriteGuard<'_, MemoInnerReactivity>,
) {
reactivity_lock.state = ReactiveNodeState::Clean;
if changed {
let subs = reactivity_lock.subscribers.clone();
drop(reactivity_lock);
for sub in subs {
// don't trigger reruns of effects/memos
// basically: if one of the observers has triggered this memo to
// run, it doesn't need to be re-triggered because of this change
if !Observer::is(&sub) {
sub.mark_dirty();
}
}
} else {
drop(reactivity_lock);
}
}
inner_2(changed, reactivity_lock);
changed
} else {
/// codegen optimisation:
fn inner(reactivity: &RwLock<MemoInnerReactivity>) -> bool {
let mut lock = reactivity.write().or_poisoned();
lock.state = ReactiveNodeState::Clean;
false
}
inner(&self.reactivity)
}
}
}
impl<T: 'static, S> Source for MemoInner<T, S>
where
S: Storage<T>,
{
fn add_subscriber(&self, subscriber: AnySubscriber) {
let mut lock = self.reactivity.write().or_poisoned();
lock.subscribers.subscribe(subscriber);
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
self.reactivity
.write()
.or_poisoned()
.subscribers
.unsubscribe(subscriber);
}
fn clear_subscribers(&self) {
self.reactivity.write().or_poisoned().subscribers.take();
}
}
impl<T: 'static, S> Subscriber for MemoInner<T, S>
where
S: Storage<T>,
{
fn add_source(&self, source: AnySource) {
self.reactivity.write().or_poisoned().sources.insert(source);
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
self.reactivity
.write()
.or_poisoned()
.sources
.clear_sources(subscriber);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/arc_memo.rs | reactive_graph/src/computed/arc_memo.rs | use super::inner::MemoInner;
use crate::{
graph::{
AnySource, AnySubscriber, ReactiveNode, Source, Subscriber,
ToAnySource, ToAnySubscriber,
},
owner::{Storage, StorageAccess, SyncStorage},
signal::{
guards::{Mapped, Plain, ReadGuard},
ArcReadSignal, ArcRwSignal,
},
traits::{DefinedAt, Get, IsDisposed, ReadUntracked},
};
use core::fmt::Debug;
use std::{
hash::Hash,
panic::Location,
sync::{Arc, Weak},
};
/// An efficient derived reactive value based on other reactive values.
///
/// This is a reference-counted memo, which is `Clone` but not `Copy`.
/// For arena-allocated `Copy` memos, use [`Memo`](super::Memo).
///
/// Unlike a "derived signal," a memo comes with two guarantees:
/// 1. The memo will only run *once* per change, no matter how many times you
/// access its value.
/// 2. The memo will only notify its dependents if the value of the computation changes.
///
/// This makes a memo the perfect tool for expensive computations.
///
/// Memos have a certain overhead compared to derived signals. In most cases, you should
/// create a derived signal. But if the derivation calculation is expensive, you should
/// create a memo.
///
/// As with an [`Effect`](crate::effect::Effect), the argument to the memo function is the previous value,
/// i.e., the current value of the memo, which will be `None` for the initial calculation.
///
/// ## Examples
/// ```
/// # use reactive_graph::prelude::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::computed::*;
/// # use reactive_graph::signal::signal;
/// # fn really_expensive_computation(value: i32) -> i32 { value };
/// let (value, set_value) = signal(0);
///
/// // 🆗 we could create a derived signal with a simple function
/// let double_value = move || value.get() * 2;
/// set_value.set(2);
/// assert_eq!(double_value(), 4);
///
/// // but imagine the computation is really expensive
/// let expensive = move || really_expensive_computation(value.get()); // lazy: doesn't run until called
/// // 🆗 run #1: calls `really_expensive_computation` the first time
/// println!("expensive = {}", expensive());
/// // ❌ run #2: this calls `really_expensive_computation` a second time!
/// let some_value = expensive();
///
/// // instead, we create a memo
/// // 🆗 run #1: the calculation runs once immediately
/// let memoized = ArcMemo::new(move |_| really_expensive_computation(value.get()));
/// // 🆗 reads the current value of the memo
/// // can be `memoized()` on nightly
/// println!("memoized = {}", memoized.get());
/// // ✅ reads the current value **without re-running the calculation**
/// let some_value = memoized.get();
/// ```
///
/// ## Core Trait Implementations
/// - [`.get()`](crate::traits::Get) clones the current value of the memo.
/// If you call it within an effect, it will cause that effect to subscribe
/// to the memo, and to re-run whenever the value of the memo changes.
/// - [`.get_untracked()`](crate::traits::GetUntracked) clones the value of
/// the memo without reactively tracking it.
/// - [`.read()`](crate::traits::Read) returns a guard that allows accessing the
/// value of the memo by reference. If you call it within an effect, it will
/// cause that effect to subscribe to the memo, and to re-run whenever the
/// value of the memo changes.
/// - [`.read_untracked()`](crate::traits::ReadUntracked) gives access to the
/// current value of the memo without reactively tracking it.
/// - [`.with()`](crate::traits::With) allows you to reactively access the memo’s
/// value without cloning by applying a callback function.
/// - [`.with_untracked()`](crate::traits::WithUntracked) allows you to access
/// the memo’s value by applying a callback function without reactively
/// tracking it.
/// - [`.to_stream()`](crate::traits::ToStream) converts the memo to an `async`
/// stream of values.
/// - [`::from_stream()`](crate::traits::FromStream) converts an `async` stream
/// of values into a memo containing the latest value.
pub struct ArcMemo<T, S = SyncStorage>
where
S: Storage<T>,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: Arc<MemoInner<T, S>>,
}
impl<T: 'static> ArcMemo<T, SyncStorage>
where
SyncStorage: Storage<T>,
{
/// Creates a new memo by passing a function that computes the value.
///
/// This is lazy: the function will not be called until the memo's value is read for the first
/// time.
#[track_caller]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn new(fun: impl Fn(Option<&T>) -> T + Send + Sync + 'static) -> Self
where
T: PartialEq,
{
Self::new_with_compare(fun, |lhs, rhs| lhs.as_ref() != rhs.as_ref())
}
/// Creates a new memo by passing a function that computes the value, and a comparison function
/// that takes the previous value and the new value and returns `true` if the value has
/// changed.
///
/// This is lazy: the function will not be called until the memo's value is read for the first
/// time.
#[track_caller]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn new_with_compare(
fun: impl Fn(Option<&T>) -> T + Send + Sync + 'static,
changed: fn(Option<&T>, Option<&T>) -> bool,
) -> Self {
Self::new_owning(move |prev: Option<T>| {
let new_value = fun(prev.as_ref());
let changed = changed(prev.as_ref(), Some(&new_value));
(new_value, changed)
})
}
/// Creates a new memo by passing a function that computes the value.
///
/// Unlike [`ArcMemo::new`](), this receives ownership of the previous value. As a result, it
/// must return both the new value and a `bool` that is `true` if the value has changed.
///
/// This is lazy: the function will not be called until the memo's value is read for the first
/// time.
#[track_caller]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn new_owning(
fun: impl Fn(Option<T>) -> (T, bool) + Send + Sync + 'static,
) -> Self {
let inner = Arc::new_cyclic(|weak| {
let subscriber = AnySubscriber(
weak.as_ptr() as usize,
Weak::clone(weak) as Weak<dyn Subscriber + Send + Sync>,
);
MemoInner::new(Arc::new(fun), subscriber)
});
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner,
}
}
}
impl<T, S> Clone for ArcMemo<T, S>
where
S: Storage<T>,
{
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
inner: Arc::clone(&self.inner),
}
}
}
impl<T, S> DefinedAt for ArcMemo<T, S>
where
S: Storage<T>,
{
#[inline(always)]
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
impl<T, S> Debug for ArcMemo<T, S>
where
S: Storage<T>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArcMemo")
.field("type", &std::any::type_name::<T>())
.field("data", &Arc::as_ptr(&self.inner))
.finish()
}
}
impl<T, S> PartialEq for ArcMemo<T, S>
where
S: Storage<T>,
{
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
impl<T, S> Eq for ArcMemo<T, S> where S: Storage<T> {}
impl<T, S> Hash for ArcMemo<T, S>
where
S: Storage<T>,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(&Arc::as_ptr(&self.inner), state);
}
}
impl<T: 'static, S> ReactiveNode for ArcMemo<T, S>
where
S: Storage<T>,
{
fn mark_dirty(&self) {
self.inner.mark_dirty();
}
fn mark_check(&self) {
self.inner.mark_check();
}
fn mark_subscribers_check(&self) {
self.inner.mark_subscribers_check();
}
fn update_if_necessary(&self) -> bool {
self.inner.update_if_necessary()
}
}
impl<T: 'static, S> IsDisposed for ArcMemo<T, S>
where
S: Storage<T>,
{
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T: 'static, S> ToAnySource for ArcMemo<T, S>
where
S: Storage<T>,
{
fn to_any_source(&self) -> AnySource {
AnySource(
Arc::as_ptr(&self.inner) as usize,
Arc::downgrade(&self.inner) as Weak<dyn Source + Send + Sync>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
self.defined_at,
)
}
}
impl<T: 'static, S> Source for ArcMemo<T, S>
where
S: Storage<T>,
{
fn add_subscriber(&self, subscriber: AnySubscriber) {
self.inner.add_subscriber(subscriber);
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
self.inner.remove_subscriber(subscriber);
}
fn clear_subscribers(&self) {
self.inner.clear_subscribers();
}
}
impl<T: 'static, S> ToAnySubscriber for ArcMemo<T, S>
where
S: Storage<T>,
{
fn to_any_subscriber(&self) -> AnySubscriber {
AnySubscriber(
Arc::as_ptr(&self.inner) as usize,
Arc::downgrade(&self.inner) as Weak<dyn Subscriber + Send + Sync>,
)
}
}
impl<T: 'static, S> Subscriber for ArcMemo<T, S>
where
S: Storage<T>,
{
fn add_source(&self, source: AnySource) {
self.inner.add_source(source);
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
self.inner.clear_sources(subscriber);
}
}
impl<T: 'static, S> ReadUntracked for ArcMemo<T, S>
where
S: Storage<T>,
{
type Value = ReadGuard<T, Mapped<Plain<Option<S::Wrapped>>, T>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.update_if_necessary();
Mapped::try_new(Arc::clone(&self.inner.value), |t| {
// safe to unwrap here because update_if_necessary
// guarantees the value is Some
t.as_ref().unwrap().as_borrowed()
})
.map(ReadGuard::new)
}
}
impl<T> From<ArcReadSignal<T>> for ArcMemo<T, SyncStorage>
where
T: Clone + PartialEq + Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcReadSignal<T>) -> Self {
ArcMemo::new(move |_| value.get())
}
}
impl<T> From<ArcRwSignal<T>> for ArcMemo<T, SyncStorage>
where
T: Clone + PartialEq + Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcRwSignal<T>) -> Self {
ArcMemo::new(move |_| value.get())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/selector.rs | reactive_graph/src/computed/selector.rs | use crate::{
effect::RenderEffect,
signal::ArcRwSignal,
traits::{Track, Update},
};
use or_poisoned::OrPoisoned;
use rustc_hash::FxHashMap;
use std::{
hash::Hash,
sync::{Arc, RwLock},
};
/// A conditional signal that only notifies subscribers when a change
/// in the source signal’s value changes whether the given function is true.
///
/// **You probably don’t need this,** but it can be a very useful optimization
/// in certain situations (e.g., “set the class `selected` if `selected() == this_row_index`)
/// because it reduces them from `O(n)` to `O(1)`.
///
/// ```
/// # use reactive_graph::computed::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::effect::Effect;
/// # use reactive_graph::owner::StoredValue; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # tokio_test::block_on(async move {
/// # tokio::task::LocalSet::new().run_until(async move {
/// # any_spawner::Executor::init_tokio(); let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
/// let a = RwSignal::new(0);
/// let is_selected = Selector::new(move || a.get());
/// let total_notifications = StoredValue::new(0);
/// Effect::new_isomorphic({
/// let is_selected = is_selected.clone();
/// move |_| {
/// if is_selected.selected(&5) {
/// total_notifications.update_value(|n| *n += 1);
/// }
/// }
/// });
///
/// assert_eq!(is_selected.selected(&5), false);
/// assert_eq!(total_notifications.get_value(), 0);
/// a.set(5);
/// # any_spawner::Executor::tick().await;
///
/// assert_eq!(is_selected.selected(&5), true);
/// assert_eq!(total_notifications.get_value(), 1);
/// a.set(5);
/// # any_spawner::Executor::tick().await;
///
/// assert_eq!(is_selected.selected(&5), true);
/// assert_eq!(total_notifications.get_value(), 1);
/// a.set(4);
///
/// # any_spawner::Executor::tick().await;
/// assert_eq!(is_selected.selected(&5), false);
/// # }).await;
/// # });
/// ```
#[derive(Clone)]
pub struct Selector<T>
where
T: PartialEq + Eq + Clone + Hash + 'static,
{
subs: Arc<RwLock<FxHashMap<T, ArcRwSignal<bool>>>>,
v: Arc<RwLock<Option<T>>>,
#[allow(clippy::type_complexity)]
f: Arc<dyn Fn(&T, &T) -> bool + Send + Sync>,
// owning the effect keeps it alive, to keep updating the selector
#[allow(dead_code)]
effect: Arc<RenderEffect<T>>,
}
impl<T> Selector<T>
where
T: PartialEq + Send + Sync + Eq + Clone + Hash + 'static,
{
/// Creates a new selector that compares values using [`PartialEq`].
pub fn new(source: impl Fn() -> T + Send + Sync + Clone + 'static) -> Self {
Self::new_with_fn(source, PartialEq::eq)
}
/// Creates a new selector that compares values by returning `true` from a comparator function
/// if the values are the same.
pub fn new_with_fn(
source: impl Fn() -> T + Clone + Send + Sync + 'static,
f: impl Fn(&T, &T) -> bool + Send + Sync + Clone + 'static,
) -> Self {
let subs: Arc<RwLock<FxHashMap<T, ArcRwSignal<bool>>>> =
Default::default();
let v: Arc<RwLock<Option<T>>> = Default::default();
let f = Arc::new(f) as Arc<dyn Fn(&T, &T) -> bool + Send + Sync>;
let effect = Arc::new(RenderEffect::new_isomorphic({
let subs = Arc::clone(&subs);
let f = Arc::clone(&f);
let v = Arc::clone(&v);
move |prev: Option<T>| {
let next_value = source();
*v.write().or_poisoned() = Some(next_value.clone());
if prev.as_ref() != Some(&next_value) {
for (key, signal) in &*subs.read().or_poisoned() {
if f(key, &next_value)
|| (prev.is_some()
&& f(key, prev.as_ref().unwrap()))
{
signal.update(|n| *n = true);
}
}
}
next_value
}
}));
Selector { subs, v, f, effect }
}
/// Reactively checks whether the given key is selected.
pub fn selected(&self, key: &T) -> bool {
let read = {
let sub = self.subs.read().or_poisoned().get(key).cloned();
sub.unwrap_or_else(|| {
self.subs
.write()
.or_poisoned()
.entry(key.clone())
.or_insert_with(|| ArcRwSignal::new(false))
.clone()
})
};
read.track();
(self.f)(key, self.v.read().or_poisoned().as_ref().unwrap())
}
/// Removes the listener for the given key.
pub fn remove(&self, key: &T) {
let mut subs = self.subs.write().or_poisoned();
subs.remove(key);
}
/// Clears the listeners for all keys.
pub fn clear(&self) {
let mut subs = self.subs.write().or_poisoned();
subs.clear();
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/memo.rs | reactive_graph/src/computed/memo.rs | use super::ArcMemo;
use crate::{
owner::{ArenaItem, FromLocal, LocalStorage, Storage, SyncStorage},
signal::{
guards::{Mapped, Plain, ReadGuard},
ArcReadSignal,
},
traits::{DefinedAt, Dispose, Get, ReadUntracked, Track},
unwrap_signal,
};
use std::{fmt::Debug, hash::Hash, panic::Location};
/// A memo is an efficient derived reactive value based on other reactive values.
///
/// Unlike a "derived signal," a memo comes with two guarantees:
/// 1. The memo will only run *once* per change, no matter how many times you
/// access its value.
/// 2. The memo will only notify its dependents if the value of the computation changes.
///
/// This makes a memo the perfect tool for expensive computations.
///
/// Memos have a certain overhead compared to derived signals. In most cases, you should
/// create a derived signal. But if the derivation calculation is expensive, you should
/// create a memo.
///
/// Memos are lazy: they do not run at all until they are read for the first time, and they will
/// not re-run the calculation when a source signal changes until they are read again.
///
/// This is an arena-allocated type, which is `Copy` and is disposed when its reactive
/// [`Owner`](crate::owner::Owner) cleans up. For a reference-counted signal that lives as
/// as long as a reference to it is alive, see [`ArcMemo`].
///
/// ```
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::computed::Memo;
/// # use reactive_graph::effect::Effect;
/// # use reactive_graph::signal::signal;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio(); let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # tokio::task::LocalSet::new().run_until(async {
/// # fn really_expensive_computation(value: i32) -> i32 { value };
/// let (value, set_value) = signal(0);
///
/// // 🆗 we could create a derived signal with a simple function
/// let double_value = move || value.get() * 2;
/// set_value.set(2);
/// assert_eq!(double_value(), 4);
///
/// // but imagine the computation is really expensive
/// let expensive = move || really_expensive_computation(value.get()); // lazy: doesn't run until called
/// Effect::new(move |_| {
/// // 🆗 run #1: calls `really_expensive_computation` the first time
/// println!("expensive = {}", expensive());
/// });
/// Effect::new(move |_| {
/// // ❌ run #2: this calls `really_expensive_computation` a second time!
/// let value = expensive();
/// // do something else...
/// });
///
/// // instead, we create a memo
/// // 🆗 run #1: the calculation runs once immediately
/// let memoized = Memo::new(move |_| really_expensive_computation(value.get()));
/// Effect::new(move |_| {
/// // 🆗 reads the current value of the memo
/// // can be `memoized()` on nightly
/// println!("memoized = {}", memoized.get());
/// });
/// Effect::new(move |_| {
/// // ✅ reads the current value **without re-running the calculation**
/// let value = memoized.get();
/// // do something else...
/// });
/// # });
/// # });
/// ```
///
/// ## Core Trait Implementations
/// - [`.get()`](crate::traits::Get) clones the current value of the memo.
/// If you call it within an effect, it will cause that effect to subscribe
/// to the memo, and to re-run whenever the value of the memo changes.
/// - [`.get_untracked()`](crate::traits::GetUntracked) clones the value of
/// the memo without reactively tracking it.
/// - [`.read()`](crate::traits::Read) returns a guard that allows accessing the
/// value of the memo by reference. If you call it within an effect, it will
/// cause that effect to subscribe to the memo, and to re-run whenever the
/// value of the memo changes.
/// - [`.read_untracked()`](crate::traits::ReadUntracked) gives access to the
/// current value of the memo without reactively tracking it.
/// - [`.with()`](crate::traits::With) allows you to reactively access the memo’s
/// value without cloning by applying a callback function.
/// - [`.with_untracked()`](crate::traits::WithUntracked) allows you to access
/// the memo’s value by applying a callback function without reactively
/// tracking it.
/// - [`.to_stream()`](crate::traits::ToStream) converts the memo to an `async`
/// stream of values.
/// - [`::from_stream()`](crate::traits::FromStream) converts an `async` stream
/// of values into a memo containing the latest value.
pub struct Memo<T, S = SyncStorage>
where
S: Storage<T>,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: ArenaItem<ArcMemo<T, S>, S>,
}
impl<T, S> Dispose for Memo<T, S>
where
S: Storage<T>,
{
fn dispose(self) {
self.inner.dispose()
}
}
impl<T> From<ArcMemo<T, SyncStorage>> for Memo<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcMemo<T, SyncStorage>) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T> FromLocal<ArcMemo<T, LocalStorage>> for Memo<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from_local(value: ArcMemo<T, LocalStorage>) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T> Memo<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "debug", skip_all)
)]
/// Creates a new memoized, computed reactive value.
///
/// As with an [`Effect`](crate::effect::Effect), the argument to the memo function is the previous value,
/// i.e., the current value of the memo, which will be `None` for the initial calculation.
/// ```
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::computed::Memo;
/// # use reactive_graph::effect::Effect;
/// # use reactive_graph::signal::signal;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio(); let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # fn really_expensive_computation(value: i32) -> i32 { value };
/// let (value, set_value) = signal(0);
///
/// // the memo will reactively update whenever `value` changes
/// let memoized =
/// Memo::new(move |_| really_expensive_computation(value.get()));
/// # });
/// ```
pub fn new(fun: impl Fn(Option<&T>) -> T + Send + Sync + 'static) -> Self
where
T: PartialEq,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcMemo::new(fun)),
}
}
#[track_caller]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
/// Creates a new memo with a custom comparison function. By default, memos simply use
/// [`PartialEq`] to compare the previous value to the new value. Passing a custom comparator
/// allows you to compare the old and new values using any criteria.
///
/// `changed` should be a function that returns `true` if the new value is different from the
/// old value.
pub fn new_with_compare(
fun: impl Fn(Option<&T>) -> T + Send + Sync + 'static,
changed: fn(Option<&T>, Option<&T>) -> bool,
) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcMemo::new_with_compare(
fun, changed,
)),
}
}
/// Creates a new memo by passing a function that computes the value.
///
/// Unlike [`Memo::new`](), this receives ownership of the previous value. As a result, it
/// must return both the new value and a `bool` that is `true` if the value has changed.
///
/// This is lazy: the function will not be called until the memo's value is read for the first
/// time.
#[track_caller]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", skip_all)
)]
pub fn new_owning(
fun: impl Fn(Option<T>) -> (T, bool) + Send + Sync + 'static,
) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcMemo::new_owning(fun)),
}
}
}
impl<T, S> Copy for Memo<T, S> where S: Storage<T> {}
impl<T, S> Clone for Memo<T, S>
where
S: Storage<T>,
{
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Debug for Memo<T, S>
where
S: Debug + Storage<T>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Memo")
.field("type", &std::any::type_name::<T>())
.field("store", &self.inner)
.finish()
}
}
impl<T, S> PartialEq for Memo<T, S>
where
S: Storage<T>,
{
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, S> Eq for Memo<T, S> where S: Storage<T> {}
impl<T, S> Hash for Memo<T, S>
where
S: Storage<T>,
{
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.hash(state);
}
}
impl<T, S> DefinedAt for Memo<T, S>
where
S: Storage<T>,
{
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
impl<T, S> Track for Memo<T, S>
where
T: 'static,
S: Storage<ArcMemo<T, S>> + Storage<T>,
ArcMemo<T, S>: Track,
{
#[track_caller]
fn track(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.track();
}
}
}
impl<T, S> ReadUntracked for Memo<T, S>
where
T: 'static,
S: Storage<ArcMemo<T, S>> + Storage<T>,
{
type Value =
ReadGuard<T, Mapped<Plain<Option<<S as Storage<T>>::Wrapped>>, T>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.inner
.try_get_value()
.map(|inner| inner.read_untracked())
}
}
impl<T, S> From<Memo<T, S>> for ArcMemo<T, S>
where
T: 'static,
S: Storage<ArcMemo<T, S>> + Storage<T>,
{
#[track_caller]
fn from(value: Memo<T, S>) -> Self {
value
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(value))
}
}
impl<T> From<ArcReadSignal<T>> for Memo<T>
where
T: Clone + PartialEq + Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcReadSignal<T>) -> Self {
Memo::new(move |_| value.get())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/async_derived/arc_async_derived.rs | reactive_graph/src/computed/async_derived/arc_async_derived.rs | use super::{
inner::{ArcAsyncDerivedInner, AsyncDerivedState},
AsyncDerivedReadyFuture, ScopedFuture,
};
#[cfg(feature = "sandboxed-arenas")]
use crate::owner::Sandboxed;
use crate::{
channel::channel,
computed::suspense::SuspenseContext,
diagnostics::SpecialNonReactiveFuture,
graph::{
AnySource, AnySubscriber, ReactiveNode, Source, SourceSet, Subscriber,
SubscriberSet, ToAnySource, ToAnySubscriber, WithObserver,
},
owner::{use_context, Owner},
send_wrapper_ext::SendOption,
signal::{
guards::{AsyncPlain, Mapped, MappedMut, ReadGuard, WriteGuard},
ArcTrigger,
},
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
transition::AsyncTransition,
};
use async_lock::RwLock as AsyncRwLock;
use core::fmt::Debug;
use futures::{channel::oneshot, FutureExt, StreamExt};
use or_poisoned::OrPoisoned;
use std::{
future::Future,
mem,
ops::{Deref, DerefMut},
panic::Location,
sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock, Weak,
},
task::Waker,
};
/// A reactive value that is derived by running an asynchronous computation in response to changes
/// in its sources.
///
/// When one of its dependencies changes, this will re-run its async computation, then notify other
/// values that depend on it that it has changed.
///
/// This is a reference-counted type, which is `Clone` but not `Copy`.
/// For arena-allocated `Copy` memos, use [`AsyncDerived`](super::AsyncDerived).
///
/// ## Examples
/// ```rust
/// # use reactive_graph::computed::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::prelude::*;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio(); let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
///
/// let signal1 = RwSignal::new(0);
/// let signal2 = RwSignal::new(0);
/// let derived = ArcAsyncDerived::new(move || async move {
/// // reactive values can be tracked anywhere in the `async` block
/// let value1 = signal1.get();
/// tokio::time::sleep(std::time::Duration::from_millis(25)).await;
/// let value2 = signal2.get();
///
/// value1 + value2
/// });
///
/// // the value can be accessed synchronously as `Option<T>`
/// assert_eq!(derived.get(), None);
/// // we can also .await the value, i.e., convert it into a Future
/// assert_eq!(derived.clone().await, 0);
/// assert_eq!(derived.get(), Some(0));
///
/// signal1.set(1);
/// // while the new value is still pending, the signal holds the old value
/// tokio::time::sleep(std::time::Duration::from_millis(5)).await;
/// assert_eq!(derived.get(), Some(0));
///
/// // setting multiple dependencies will hold until the latest change is ready
/// signal2.set(1);
/// assert_eq!(derived.await, 2);
/// # });
/// ```
///
/// ## Core Trait Implementations
/// - [`.get()`](crate::traits::Get) clones the current value as an `Option<T>`.
/// If you call it within an effect, it will cause that effect to subscribe
/// to the memo, and to re-run whenever the value of the memo changes.
/// - [`.get_untracked()`](crate::traits::GetUntracked) clones the value of
/// without reactively tracking it.
/// - [`.read()`](crate::traits::Read) returns a guard that allows accessing the
/// value by reference. If you call it within an effect, it will
/// cause that effect to subscribe to the memo, and to re-run whenever the
/// value changes.
/// - [`.read_untracked()`](crate::traits::ReadUntracked) gives access to the
/// current value without reactively tracking it.
/// - [`.with()`](crate::traits::With) allows you to reactively access the
/// value without cloning by applying a callback function.
/// - [`.with_untracked()`](crate::traits::WithUntracked) allows you to access
/// the value by applying a callback function without reactively
/// tracking it.
/// - [`IntoFuture`](std::future::Future) allows you to create a [`Future`] that resolves
/// when this resource is done loading.
pub struct ArcAsyncDerived<T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
// the current state of this signal
pub(crate) value: Arc<AsyncRwLock<SendOption<T>>>,
// holds wakers generated when you .await this
pub(crate) wakers: Arc<RwLock<Vec<Waker>>>,
pub(crate) inner: Arc<RwLock<ArcAsyncDerivedInner>>,
pub(crate) loading: Arc<AtomicBool>,
}
#[allow(dead_code)]
pub(crate) trait BlockingLock<T> {
fn blocking_read_arc(self: &Arc<Self>)
-> async_lock::RwLockReadGuardArc<T>;
fn blocking_write_arc(
self: &Arc<Self>,
) -> async_lock::RwLockWriteGuardArc<T>;
fn blocking_read(&self) -> async_lock::RwLockReadGuard<'_, T>;
fn blocking_write(&self) -> async_lock::RwLockWriteGuard<'_, T>;
}
impl<T> BlockingLock<T> for AsyncRwLock<T> {
fn blocking_read_arc(
self: &Arc<Self>,
) -> async_lock::RwLockReadGuardArc<T> {
#[cfg(not(target_family = "wasm"))]
{
self.read_arc_blocking()
}
#[cfg(target_family = "wasm")]
{
self.read_arc().now_or_never().unwrap()
}
}
fn blocking_write_arc(
self: &Arc<Self>,
) -> async_lock::RwLockWriteGuardArc<T> {
#[cfg(not(target_family = "wasm"))]
{
self.write_arc_blocking()
}
#[cfg(target_family = "wasm")]
{
self.write_arc().now_or_never().unwrap()
}
}
fn blocking_read(&self) -> async_lock::RwLockReadGuard<'_, T> {
#[cfg(not(target_family = "wasm"))]
{
self.read_blocking()
}
#[cfg(target_family = "wasm")]
{
self.read().now_or_never().unwrap()
}
}
fn blocking_write(&self) -> async_lock::RwLockWriteGuard<'_, T> {
#[cfg(not(target_family = "wasm"))]
{
self.write_blocking()
}
#[cfg(target_family = "wasm")]
{
self.write().now_or_never().unwrap()
}
}
}
impl<T> Clone for ArcAsyncDerived<T> {
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
value: Arc::clone(&self.value),
wakers: Arc::clone(&self.wakers),
inner: Arc::clone(&self.inner),
loading: Arc::clone(&self.loading),
}
}
}
impl<T> Debug for ArcAsyncDerived<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("ArcAsyncDerived");
#[cfg(any(debug_assertions, leptos_debuginfo))]
f.field("defined_at", &self.defined_at);
f.finish_non_exhaustive()
}
}
impl<T> DefinedAt for ArcAsyncDerived<T> {
#[inline(always)]
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
// This helps create a derived async signal.
// It needs to be implemented as a macro because it needs to be flexible over
// whether `fun` returns a `Future` that is `Send`. Doing it as a function would,
// as far as I can tell, require repeating most of the function body.
macro_rules! spawn_derived {
($spawner:expr, $initial:ident, $fun:ident, $should_spawn:literal, $force_spawn:literal, $should_track:literal, $source:expr) => {{
let (notifier, mut rx) = channel();
let is_ready = $initial.is_some() && !$force_spawn;
let owner = Owner::new();
let inner = Arc::new(RwLock::new(ArcAsyncDerivedInner {
owner: owner.clone(),
notifier,
sources: SourceSet::new(),
subscribers: SubscriberSet::new(),
state: AsyncDerivedState::Clean,
version: 0,
suspenses: Vec::new(),
pending_suspenses: Vec::new()
}));
let value = Arc::new(AsyncRwLock::new($initial));
let wakers = Arc::new(RwLock::new(Vec::new()));
let this = ArcAsyncDerived {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::clone(&value),
wakers,
inner: Arc::clone(&inner),
loading: Arc::new(AtomicBool::new(!is_ready)),
};
let any_subscriber = this.to_any_subscriber();
let initial_fut = if $should_track {
owner.with_cleanup(|| {
any_subscriber
.with_observer(|| ScopedFuture::new($fun()))
})
} else {
owner.with_cleanup(|| {
any_subscriber
.with_observer_untracked(|| ScopedFuture::new($fun()))
})
};
#[cfg(feature = "sandboxed-arenas")]
let initial_fut = Sandboxed::new(initial_fut);
let mut initial_fut = Box::pin(initial_fut);
let (was_ready, mut initial_fut) = {
if is_ready {
(true, None)
} else {
// if we don't already know that it's ready, we need to poll once, initially
// so that the correct value is set synchronously
let initial = initial_fut.as_mut().now_or_never();
match initial {
None => {
inner.write().or_poisoned().notifier.notify();
(false, Some(initial_fut))
}
Some(orig_value) => {
let mut guard = this.inner.write().or_poisoned();
guard.state = AsyncDerivedState::Clean;
*value.blocking_write() = orig_value;
this.loading.store(false, Ordering::Relaxed);
(true, None)
}
}
}
};
let mut first_run = {
let (ready_tx, ready_rx) = oneshot::channel();
if !was_ready {
AsyncTransition::register(ready_rx);
}
Some(ready_tx)
};
if was_ready {
first_run.take();
}
if let Some(source) = $source {
any_subscriber.with_observer(|| source.track());
}
if $should_spawn {
$spawner({
let value = Arc::downgrade(&this.value);
let inner = Arc::downgrade(&this.inner);
let wakers = Arc::downgrade(&this.wakers);
let loading = Arc::downgrade(&this.loading);
let fut = async move {
// if the AsyncDerived has *already* been marked dirty (i.e., one of its
// sources has changed after creation), we should throw out the Future
// we already created, because its values might be stale
let already_dirty = inner.upgrade()
.as_ref()
.and_then(|inner| inner.read().ok())
.map(|inner| inner.state == AsyncDerivedState::Dirty)
.unwrap_or(false);
if already_dirty {
initial_fut.take();
}
while rx.next().await.is_some() {
let update_if_necessary = !owner.paused() && if $should_track {
any_subscriber
.with_observer(|| any_subscriber.update_if_necessary())
} else {
any_subscriber
.with_observer_untracked(|| any_subscriber.update_if_necessary())
};
if update_if_necessary || first_run.is_some() {
match (value.upgrade(), inner.upgrade(), wakers.upgrade(), loading.upgrade()) {
(Some(value), Some(inner), Some(wakers), Some(loading)) => {
// generate new Future
let owner = inner.read().or_poisoned().owner.clone();
let fut = initial_fut.take().unwrap_or_else(|| {
let fut = if $should_track {
owner.with_cleanup(|| {
any_subscriber
.with_observer(|| ScopedFuture::new($fun()))
})
} else {
owner.with_cleanup(|| {
any_subscriber
.with_observer_untracked(|| ScopedFuture::new($fun()))
})
};
#[cfg(feature = "sandboxed-arenas")]
let fut = Sandboxed::new(fut);
Box::pin(fut)
});
// register with global transition listener, if any
let ready_tx = first_run.take().unwrap_or_else(|| {
let (ready_tx, ready_rx) = oneshot::channel();
if !was_ready {
AsyncTransition::register(ready_rx);
}
ready_tx
});
// generate and assign new value
loading.store(true, Ordering::Relaxed);
let this_version = {
let mut guard = inner.write().or_poisoned();
guard.version += 1;
let version = guard.version;
let suspense_ids = mem::take(&mut guard.suspenses)
.into_iter()
.map(|sc| sc.task_id())
.collect::<Vec<_>>();
guard.pending_suspenses.extend(suspense_ids);
version
};
let new_value = fut.await;
let latest_version = {
let mut guard = inner.write().or_poisoned();
drop(mem::take(&mut guard.pending_suspenses));
guard.version
};
if latest_version == this_version {
Self::set_inner_value(new_value, value, wakers, inner, loading, Some(ready_tx)).await;
}
}
_ => break,
}
}
}
};
#[cfg(feature = "sandboxed-arenas")]
let fut = Sandboxed::new(fut);
fut
});
}
(this, is_ready)
}};
}
impl<T: 'static> ArcAsyncDerived<T> {
async fn set_inner_value(
new_value: SendOption<T>,
value: Arc<AsyncRwLock<SendOption<T>>>,
wakers: Arc<RwLock<Vec<Waker>>>,
inner: Arc<RwLock<ArcAsyncDerivedInner>>,
loading: Arc<AtomicBool>,
ready_tx: Option<oneshot::Sender<()>>,
) {
*value.write().await.deref_mut() = new_value;
Self::notify_subs(&wakers, &inner, &loading, ready_tx);
}
fn notify_subs(
wakers: &Arc<RwLock<Vec<Waker>>>,
inner: &Arc<RwLock<ArcAsyncDerivedInner>>,
loading: &Arc<AtomicBool>,
ready_tx: Option<oneshot::Sender<()>>,
) {
loading.store(false, Ordering::Relaxed);
let prev_state = mem::replace(
&mut inner.write().or_poisoned().state,
AsyncDerivedState::Notifying,
);
if let Some(ready_tx) = ready_tx {
// if it's an Err, that just means the Receiver was dropped
// we don't particularly care about that: the point is to notify if
// it still exists, but we don't need to know if Suspense is no
// longer listening
_ = ready_tx.send(());
}
// notify reactive subscribers that we're not loading any more
for sub in (&inner.read().or_poisoned().subscribers).into_iter() {
sub.mark_dirty();
}
// notify async .awaiters
for waker in mem::take(&mut *wakers.write().or_poisoned()) {
waker.wake();
}
// if this was marked dirty before notifications began, this means it
// had been notified while loading; marking it clean will cause it not to
// run on the next tick of the async loop, so here it should be left dirty
inner.write().or_poisoned().state = prev_state;
}
}
impl<T: 'static> ArcAsyncDerived<T> {
/// Creates a new async derived computation.
///
/// This runs eagerly: i.e., calls `fun` once when created and immediately spawns the `Future`
/// as a new task.
#[track_caller]
pub fn new<Fut>(fun: impl Fn() -> Fut + Send + Sync + 'static) -> Self
where
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
Self::new_with_initial(None, fun)
}
/// Creates a new async derived computation with an initial value as a fallback, and begins running the
/// `Future` eagerly to get the actual first value.
#[track_caller]
pub fn new_with_initial<Fut>(
initial_value: Option<T>,
fun: impl Fn() -> Fut + Send + Sync + 'static,
) -> Self
where
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
let fun = move || {
let fut = fun();
let fut = async move { SendOption::new(Some(fut.await)) };
#[cfg(feature = "sandboxed-arenas")]
let fut = Sandboxed::new(fut);
fut
};
let initial_value = SendOption::new(initial_value);
let (this, _) = spawn_derived!(
crate::spawn,
initial_value,
fun,
true,
true,
true,
None::<ArcTrigger>
);
this
}
/// Creates a new async derived computation with an initial value, and does not spawn a task
/// initially.
///
/// This is mostly used with manual dependency tracking, for primitives built on top of this
/// where you do not want to run the run the `Future` unnecessarily.
#[doc(hidden)]
#[track_caller]
pub fn new_with_manual_dependencies<Fut, S>(
initial_value: Option<T>,
fun: impl Fn() -> Fut + Send + Sync + 'static,
source: &S,
) -> Self
where
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
S: Track,
{
let fun = move || {
let fut = fun();
let fut =
ScopedFuture::new_untracked_with_diagnostics(async move {
SendOption::new(Some(fut.await))
});
#[cfg(feature = "sandboxed-arenas")]
let fut = Sandboxed::new(fut);
fut
};
let initial_value = SendOption::new(initial_value);
let (this, _) = spawn_derived!(
crate::spawn,
initial_value,
fun,
true,
false,
false,
Some(source)
);
this
}
/// Creates a new async derived computation that will be guaranteed to run on the current
/// thread.
///
/// This runs eagerly: i.e., calls `fun` once when created and immediately spawns the `Future`
/// as a new task.
#[track_caller]
pub fn new_unsync<Fut>(fun: impl Fn() -> Fut + 'static) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
Self::new_unsync_with_initial(None, fun)
}
/// Creates a new async derived computation with an initial value as a fallback, and begins running the
/// `Future` eagerly to get the actual first value.
#[track_caller]
pub fn new_unsync_with_initial<Fut>(
initial_value: Option<T>,
fun: impl Fn() -> Fut + 'static,
) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
let fun = move || {
let fut = fun();
let fut = async move { SendOption::new_local(Some(fut.await)) };
#[cfg(feature = "sandboxed-arenas")]
let fut = Sandboxed::new(fut);
fut
};
let initial_value = SendOption::new_local(initial_value);
let (this, _) = spawn_derived!(
crate::spawn_local,
initial_value,
fun,
true,
true,
true,
None::<ArcTrigger>
);
this
}
/// Returns a `Future` that is ready when this resource has next finished loading.
pub fn ready(&self) -> AsyncDerivedReadyFuture {
AsyncDerivedReadyFuture::new(
self.to_any_source(),
&self.loading,
&self.wakers,
)
}
}
impl<T: 'static> ArcAsyncDerived<T> {
#[doc(hidden)]
#[track_caller]
pub fn new_mock<Fut>(fun: impl Fn() -> Fut + 'static) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
let initial = SendOption::new_local(None::<T>);
let fun = move || {
let fut = fun();
let fut = async move { SendOption::new_local(Some(fut.await)) };
#[cfg(feature = "sandboxed-arenas")]
let fut = Sandboxed::new(fut);
fut
};
let (this, _) = spawn_derived!(
crate::spawn_local,
initial,
fun,
false,
false,
true,
None::<ArcTrigger>
);
this
}
}
impl<T: 'static> ReadUntracked for ArcAsyncDerived<T> {
type Value =
ReadGuard<Option<T>, Mapped<AsyncPlain<SendOption<T>>, Option<T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
if let Some(suspense_context) = use_context::<SuspenseContext>() {
// create a handle to register it with suspense
let handle = suspense_context.task_id();
// check if the task is *already* ready
let mut ready =
Box::pin(SpecialNonReactiveFuture::new(self.ready()));
match ready.as_mut().now_or_never() {
Some(_) => {
// if it's already ready, drop the handle immediately
// this will immediately notify the suspense context that it's complete
drop(handle);
}
None => {
// otherwise, spawn a task to wait for it to be ready, then drop the handle,
// which will notify the suspense
crate::spawn(async move {
ready.await;
drop(handle);
});
}
}
// register the suspense context with our list of them, to be notified later if this re-runs
self.inner
.write()
.or_poisoned()
.suspenses
.push(suspense_context);
}
AsyncPlain::try_new(&self.value).map(|plain| {
ReadGuard::new(Mapped::new_with_guard(plain, |v| v.deref()))
})
}
}
impl<T: 'static> Notify for ArcAsyncDerived<T> {
fn notify(&self) {
Self::notify_subs(&self.wakers, &self.inner, &self.loading, None);
}
}
impl<T: 'static> Write for ArcAsyncDerived<T> {
type Value = Option<T>;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
// increment the version, such that a rerun triggered previously does not overwrite this
// new value
let mut guard = self.inner.write().or_poisoned();
guard.version += 1;
// tell any suspenses to stop waiting for this
drop(mem::take(&mut guard.pending_suspenses));
Some(MappedMut::new(
WriteGuard::new(self.clone(), self.value.blocking_write()),
|v| v.deref(),
|v| v.deref_mut(),
))
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
// increment the version, such that a rerun triggered previously does not overwrite this
// new value
let mut guard = self.inner.write().or_poisoned();
guard.version += 1;
// tell any suspenses to stop waiting for this
drop(mem::take(&mut guard.pending_suspenses));
Some(MappedMut::new(
self.value.blocking_write(),
|v| v.deref(),
|v| v.deref_mut(),
))
}
}
impl<T: 'static> IsDisposed for ArcAsyncDerived<T> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T: 'static> ToAnySource for ArcAsyncDerived<T> {
fn to_any_source(&self) -> AnySource {
AnySource(
Arc::as_ptr(&self.inner) as usize,
Arc::downgrade(&self.inner) as Weak<dyn Source + Send + Sync>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
self.defined_at,
)
}
}
impl<T: 'static> ToAnySubscriber for ArcAsyncDerived<T> {
fn to_any_subscriber(&self) -> AnySubscriber {
AnySubscriber(
Arc::as_ptr(&self.inner) as usize,
Arc::downgrade(&self.inner) as Weak<dyn Subscriber + Send + Sync>,
)
}
}
impl<T> Source for ArcAsyncDerived<T> {
fn add_subscriber(&self, subscriber: AnySubscriber) {
self.inner.add_subscriber(subscriber);
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
self.inner.remove_subscriber(subscriber);
}
fn clear_subscribers(&self) {
self.inner.clear_subscribers();
}
}
impl<T> ReactiveNode for ArcAsyncDerived<T> {
fn mark_dirty(&self) {
self.inner.mark_dirty();
}
fn mark_check(&self) {
self.inner.mark_check();
}
fn mark_subscribers_check(&self) {
self.inner.mark_subscribers_check();
}
fn update_if_necessary(&self) -> bool {
self.inner.update_if_necessary()
}
}
impl<T> Subscriber for ArcAsyncDerived<T> {
fn add_source(&self, source: AnySource) {
self.inner.add_source(source);
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
self.inner.clear_sources(subscriber);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/async_derived/inner.rs | reactive_graph/src/computed/async_derived/inner.rs | use super::suspense::TaskHandle;
use crate::{
channel::Sender,
computed::suspense::SuspenseContext,
graph::{
AnySource, AnySubscriber, ReactiveNode, Source, SourceSet, Subscriber,
SubscriberSet,
},
owner::Owner,
};
use or_poisoned::OrPoisoned;
use std::sync::RwLock;
pub(crate) struct ArcAsyncDerivedInner {
pub owner: Owner,
// holds subscribers so the dependency can be cleared when this needs to rerun
pub sources: SourceSet,
// tracks reactive subscribers so they can be notified
// when the new async value is ready
pub subscribers: SubscriberSet,
// when a source changes, notifying this will cause the async work to rerun
pub notifier: Sender,
pub state: AsyncDerivedState,
pub version: usize,
pub suspenses: Vec<SuspenseContext>,
pub pending_suspenses: Vec<TaskHandle>,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum AsyncDerivedState {
Clean,
Dirty,
Notifying,
}
impl ReactiveNode for RwLock<ArcAsyncDerivedInner> {
fn mark_dirty(&self) {
let mut lock = self.write().or_poisoned();
if lock.state != AsyncDerivedState::Notifying {
lock.state = AsyncDerivedState::Dirty;
lock.notifier.notify();
}
}
fn mark_check(&self) {
let mut lock = self.write().or_poisoned();
if lock.state != AsyncDerivedState::Notifying {
lock.notifier.notify();
}
}
fn mark_subscribers_check(&self) {
let lock = self.read().or_poisoned();
for sub in (&lock.subscribers).into_iter() {
sub.mark_check();
}
}
fn update_if_necessary(&self) -> bool {
let mut guard = self.write().or_poisoned();
let (is_dirty, sources) = (
guard.state == AsyncDerivedState::Dirty,
(guard.state != AsyncDerivedState::Notifying)
.then(|| guard.sources.clone()),
);
if is_dirty {
guard.state = AsyncDerivedState::Clean;
return true;
}
drop(guard);
for source in sources.into_iter().flatten() {
if source.update_if_necessary() {
return true;
}
}
false
}
}
impl Source for RwLock<ArcAsyncDerivedInner> {
fn add_subscriber(&self, subscriber: AnySubscriber) {
self.write().or_poisoned().subscribers.subscribe(subscriber);
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
self.write()
.or_poisoned()
.subscribers
.unsubscribe(subscriber);
}
fn clear_subscribers(&self) {
self.write().or_poisoned().subscribers.take();
}
}
impl Subscriber for RwLock<ArcAsyncDerivedInner> {
fn add_source(&self, source: AnySource) {
self.write().or_poisoned().sources.insert(source);
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
self.write().or_poisoned().sources.clear_sources(subscriber);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/async_derived/async_derived.rs | reactive_graph/src/computed/async_derived/async_derived.rs | use super::{ArcAsyncDerived, AsyncDerivedReadyFuture, BlockingLock};
use crate::{
graph::{
AnySource, AnySubscriber, ReactiveNode, Source, Subscriber,
ToAnySource, ToAnySubscriber,
},
owner::{ArenaItem, FromLocal, LocalStorage, Storage, SyncStorage},
send_wrapper_ext::SendOption,
signal::guards::{AsyncPlain, Mapped, MappedMut, ReadGuard, WriteGuard},
traits::{
DefinedAt, Dispose, IsDisposed, Notify, ReadUntracked,
UntrackableGuard, Write,
},
unwrap_signal,
};
use core::fmt::Debug;
use or_poisoned::OrPoisoned;
use std::{
future::Future,
mem,
ops::{Deref, DerefMut},
panic::Location,
};
/// A reactive value that is derived by running an asynchronous computation in response to changes
/// in its sources.
///
/// When one of its dependencies changes, this will re-run its async computation, then notify other
/// values that depend on it that it has changed.
///
/// This is an arena-allocated type, which is `Copy` and is disposed when its reactive
/// [`Owner`](crate::owner::Owner) cleans up. For a reference-counted signal that lives as
/// as long as a reference to it is alive, see [`ArcAsyncDerived`].
///
/// ## Examples
/// ```rust
/// # use reactive_graph::computed::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::prelude::*;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio(); let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
///
/// let signal1 = RwSignal::new(0);
/// let signal2 = RwSignal::new(0);
/// let derived = AsyncDerived::new(move || async move {
/// // reactive values can be tracked anywhere in the `async` block
/// let value1 = signal1.get();
/// tokio::time::sleep(std::time::Duration::from_millis(25)).await;
/// let value2 = signal2.get();
///
/// value1 + value2
/// });
///
/// // the value can be accessed synchronously as `Option<T>`
/// assert_eq!(derived.get(), None);
/// // we can also .await the value, i.e., convert it into a Future
/// assert_eq!(derived.await, 0);
/// assert_eq!(derived.get(), Some(0));
///
/// signal1.set(1);
/// // while the new value is still pending, the signal holds the old value
/// tokio::time::sleep(std::time::Duration::from_millis(5)).await;
/// assert_eq!(derived.get(), Some(0));
///
/// // setting multiple dependencies will hold until the latest change is ready
/// signal2.set(1);
/// assert_eq!(derived.await, 2);
/// # });
/// ```
///
/// ## Core Trait Implementations
/// - [`.get()`](crate::traits::Get) clones the current value as an `Option<T>`.
/// If you call it within an effect, it will cause that effect to subscribe
/// to the memo, and to re-run whenever the value of the memo changes.
/// - [`.get_untracked()`](crate::traits::GetUntracked) clones the value of
/// without reactively tracking it.
/// - [`.read()`](crate::traits::Read) returns a guard that allows accessing the
/// value by reference. If you call it within an effect, it will
/// cause that effect to subscribe to the memo, and to re-run whenever the
/// value changes.
/// - [`.read_untracked()`](crate::traits::ReadUntracked) gives access to the
/// current value without reactively tracking it.
/// - [`.with()`](crate::traits::With) allows you to reactively access the
/// value without cloning by applying a callback function.
/// - [`.with_untracked()`](crate::traits::WithUntracked) allows you to access
/// the value by applying a callback function without reactively
/// tracking it.
/// - [`IntoFuture`](std::future::Future) allows you to create a [`Future`] that resolves
/// when this resource is done loading.
pub struct AsyncDerived<T, S = SyncStorage> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
pub(crate) inner: ArenaItem<ArcAsyncDerived<T>, S>,
}
impl<T, S> Dispose for AsyncDerived<T, S> {
fn dispose(self) {
self.inner.dispose()
}
}
impl<T, S> From<ArcAsyncDerived<T>> for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn from(value: ArcAsyncDerived<T>) -> Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
let defined_at = value.defined_at;
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at,
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T, S> From<AsyncDerived<T, S>> for ArcAsyncDerived<T>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
#[track_caller]
fn from(value: AsyncDerived<T, S>) -> Self {
value
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(value))
}
}
impl<T> FromLocal<ArcAsyncDerived<T>> for AsyncDerived<T, LocalStorage>
where
T: 'static,
{
fn from_local(value: ArcAsyncDerived<T>) -> Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
let defined_at = value.defined_at;
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at,
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T> AsyncDerived<T>
where
T: 'static,
{
/// Creates a new async derived computation.
///
/// This runs eagerly: i.e., calls `fun` once when created and immediately spawns the `Future`
/// as a new task.
#[track_caller]
pub fn new<Fut>(fun: impl Fn() -> Fut + Send + Sync + 'static) -> Self
where
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcAsyncDerived::new(fun)),
}
}
/// Creates a new async derived computation with an initial value.
///
/// If the initial value is `Some(_)`, the task will not be run initially.
pub fn new_with_initial<Fut>(
initial_value: Option<T>,
fun: impl Fn() -> Fut + Send + Sync + 'static,
) -> Self
where
T: Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(
ArcAsyncDerived::new_with_initial(initial_value, fun),
),
}
}
}
impl<T> AsyncDerived<T> {
#[doc(hidden)]
pub fn new_mock<Fut>(fun: impl Fn() -> Fut + 'static) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcAsyncDerived::new_mock(fun)),
}
}
/// Same as [`AsyncDerived::new_unsync`] except it produces AsyncDerived<T> instead of AsyncDerived<T, LocalStorage>.
/// The internal value will still be wrapped in a [`send_wrapper::SendWrapper`].
pub fn new_unsync_threadsafe_storage<Fut>(
fun: impl Fn() -> Fut + 'static,
) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcAsyncDerived::new_unsync(
fun,
)),
}
}
}
impl<T> AsyncDerived<T, LocalStorage>
where
T: 'static,
{
/// Creates a new async derived computation that will be guaranteed to run on the current
/// thread.
///
/// This runs eagerly: i.e., calls `fun` once when created and immediately spawns the `Future`
/// as a new task.
pub fn new_unsync<Fut>(fun: impl Fn() -> Fut + 'static) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcAsyncDerived::new_unsync(
fun,
)),
}
}
/// Creates a new async derived computation with an initial value. Async work will be
/// guaranteed to run only on the current thread.
///
/// If the initial value is `Some(_)`, the task will not be run initially.
pub fn new_unsync_with_initial<Fut>(
initial_value: Option<T>,
fun: impl Fn() -> Fut + 'static,
) -> Self
where
T: 'static,
Fut: Future<Output = T> + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(
ArcAsyncDerived::new_unsync_with_initial(initial_value, fun),
),
}
}
}
impl<T, S> AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
/// Returns a `Future` that is ready when this resource has next finished loading.
#[track_caller]
pub fn ready(&self) -> AsyncDerivedReadyFuture {
let this = self
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(self));
this.ready()
}
}
impl<T, S> Copy for AsyncDerived<T, S> {}
impl<T, S> Clone for AsyncDerived<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Debug for AsyncDerived<T, S>
where
S: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AsyncDerived")
.field("type", &std::any::type_name::<T>())
.field("store", &self.inner)
.finish()
}
}
impl<T, S> DefinedAt for AsyncDerived<T, S> {
#[inline(always)]
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.defined_at)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
impl<T, S> ReadUntracked for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
type Value =
ReadGuard<Option<T>, Mapped<AsyncPlain<SendOption<T>>, Option<T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.inner
.try_get_value()
.map(|inner| inner.read_untracked())
}
}
impl<T, S> Notify for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn notify(&self) {
self.inner.try_with_value(|inner| inner.notify());
}
}
impl<T, S> Write for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
type Value = Option<T>;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
let guard = self
.inner
.try_with_value(|n| n.value.blocking_write_arc())?;
self.inner.try_with_value(|n| {
let mut guard = n.inner.write().or_poisoned();
// increment the version, such that a rerun triggered previously does not overwrite this
// new value
guard.version += 1;
// tell any suspenses to stop waiting for this
drop(mem::take(&mut guard.pending_suspenses));
});
Some(MappedMut::new(
WriteGuard::new(*self, guard),
|v| v.deref(),
|v| v.deref_mut(),
))
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.inner.try_with_value(|n| {
let mut guard = n.inner.write().or_poisoned();
// increment the version, such that a rerun triggered previously does not overwrite this
// new value
guard.version += 1;
// tell any suspenses to stop waiting for this
drop(mem::take(&mut guard.pending_suspenses));
});
self.inner
.try_with_value(|n| n.value.blocking_write_arc())
.map(|inner| {
MappedMut::new(inner, |v| v.deref(), |v| v.deref_mut())
})
}
}
impl<T, S> IsDisposed for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<T, S> ToAnySource for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn to_any_source(&self) -> AnySource {
self.inner
.try_get_value()
.map(|inner| inner.to_any_source())
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T, S> ToAnySubscriber for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn to_any_subscriber(&self) -> AnySubscriber {
self.inner
.try_get_value()
.map(|inner| inner.to_any_subscriber())
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T, S> Source for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn add_subscriber(&self, subscriber: AnySubscriber) {
if let Some(inner) = self.inner.try_get_value() {
inner.add_subscriber(subscriber);
}
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
if let Some(inner) = self.inner.try_get_value() {
inner.remove_subscriber(subscriber);
}
}
fn clear_subscribers(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.clear_subscribers();
}
}
}
impl<T, S> ReactiveNode for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn mark_dirty(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.mark_dirty();
}
}
fn mark_check(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.mark_check();
}
}
fn mark_subscribers_check(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.mark_subscribers_check();
}
}
fn update_if_necessary(&self) -> bool {
if let Some(inner) = self.inner.try_get_value() {
inner.update_if_necessary()
} else {
false
}
}
}
impl<T, S> Subscriber for AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
fn add_source(&self, source: AnySource) {
if let Some(inner) = self.inner.try_get_value() {
inner.add_source(source);
}
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
if let Some(inner) = self.inner.try_get_value() {
inner.clear_sources(subscriber);
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/async_derived/mod.rs | reactive_graph/src/computed/async_derived/mod.rs | mod arc_async_derived;
pub use arc_async_derived::*;
#[allow(clippy::module_inception)] // not a pub mod, who cares?
mod async_derived;
mod future_impls;
mod inner;
use crate::{
graph::{AnySubscriber, Observer, WithObserver},
owner::Owner,
};
pub use async_derived::*;
pub use future_impls::*;
use futures::Future;
use pin_project_lite::pin_project;
use std::{
pin::Pin,
task::{Context, Poll},
};
pin_project! {
/// A [`Future`] wrapper that sets the [`Owner`] and [`Observer`] before polling the inner
/// `Future`.
#[derive(Clone)]
#[allow(missing_docs)]
pub struct ScopedFuture<Fut> {
pub owner: Owner,
pub observer: Option<AnySubscriber>,
#[pin]
pub fut: Fut,
}
}
impl<Fut> ScopedFuture<Fut> {
/// Wraps the given `Future` by taking the current [`Owner`] and [`Observer`] and re-setting
/// them as the active owner and observer every time the inner `Future` is polled.
pub fn new(fut: Fut) -> Self {
let owner = Owner::current().unwrap_or_default();
let observer = Observer::get();
Self {
owner,
observer,
fut,
}
}
/// Wraps the given `Future` by taking the current [`Owner`] re-setting it as the
/// active owner every time the inner `Future` is polled. Always untracks, i.e., clears
/// the active [`Observer`] when polled.
pub fn new_untracked(fut: Fut) -> Self {
let owner = Owner::current().unwrap_or_default();
Self {
owner,
observer: None,
fut,
}
}
#[doc(hidden)]
#[track_caller]
pub fn new_untracked_with_diagnostics(
fut: Fut,
) -> ScopedFutureUntrackedWithDiagnostics<Fut> {
let owner = Owner::current().unwrap_or_default();
ScopedFutureUntrackedWithDiagnostics {
owner,
observer: None,
fut,
}
}
}
impl<Fut: Future> Future for ScopedFuture<Fut> {
type Output = Fut::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
this.owner.with(|| {
#[cfg(debug_assertions)]
let _maybe_guard = if this.observer.is_none() {
Some(crate::diagnostics::SpecialNonReactiveZone::enter())
} else {
None
};
this.observer.with_observer(|| this.fut.poll(cx))
})
}
}
pin_project! {
/// A [`Future`] wrapper that sets the [`Owner`] and [`Observer`] before polling the inner
/// `Future`, output of [`ScopedFuture::new_untracked_with_diagnostics`].
///
/// In leptos 0.9 this will be replaced with `ScopedFuture` itself.
#[derive(Clone)]
pub struct ScopedFutureUntrackedWithDiagnostics<Fut> {
owner: Owner,
observer: Option<AnySubscriber>,
#[pin]
fut: Fut,
}
}
impl<Fut: Future> Future for ScopedFutureUntrackedWithDiagnostics<Fut> {
type Output = Fut::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
this.owner
.with(|| this.observer.with_observer(|| this.fut.poll(cx)))
}
}
/// Utilities used to track whether asynchronous computeds are currently loading.
pub mod suspense {
use crate::{
signal::ArcRwSignal,
traits::{Update, Write},
};
use futures::channel::oneshot::Sender;
use or_poisoned::OrPoisoned;
use slotmap::{DefaultKey, SlotMap};
use std::sync::{Arc, Mutex};
/// Sends a one-time notification that the resource being read from is "local only," i.e.,
/// that it will only run on the client, not the server.
#[derive(Clone, Debug)]
pub struct LocalResourceNotifier(Arc<Mutex<Option<Sender<()>>>>);
impl LocalResourceNotifier {
/// Send the notification. If the inner channel has already been used, this does nothing.
pub fn notify(&mut self) {
if let Some(tx) = self.0.lock().or_poisoned().take() {
tx.send(()).unwrap();
}
}
}
impl From<Sender<()>> for LocalResourceNotifier {
fn from(value: Sender<()>) -> Self {
Self(Arc::new(Mutex::new(Some(value))))
}
}
/// Tracks the collection of active async tasks.
#[derive(Clone, Debug)]
pub struct SuspenseContext {
/// The set of active tasks.
pub tasks: ArcRwSignal<SlotMap<DefaultKey, ()>>,
}
impl SuspenseContext {
/// Generates a unique task ID.
pub fn task_id(&self) -> TaskHandle {
let key = self.tasks.write().insert(());
TaskHandle {
tasks: self.tasks.clone(),
key,
}
}
}
/// A unique identifier that removes itself from the set of tasks when it is dropped.
#[derive(Debug)]
pub struct TaskHandle {
tasks: ArcRwSignal<SlotMap<DefaultKey, ()>>,
key: DefaultKey,
}
impl Drop for TaskHandle {
fn drop(&mut self) {
self.tasks.update(|tasks| {
tasks.remove(self.key);
});
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/computed/async_derived/future_impls.rs | reactive_graph/src/computed/async_derived/future_impls.rs | use super::{inner::ArcAsyncDerivedInner, ArcAsyncDerived, AsyncDerived};
use crate::{
computed::suspense::SuspenseContext,
diagnostics::SpecialNonReactiveZone,
graph::{AnySource, ToAnySource},
owner::{use_context, Storage},
send_wrapper_ext::SendOption,
signal::guards::{AsyncPlain, Mapped, ReadGuard},
traits::{DefinedAt, Track},
unwrap_signal,
};
use futures::pin_mut;
use or_poisoned::OrPoisoned;
use std::{
future::{Future, IntoFuture},
pin::Pin,
sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock,
},
task::{Context, Poll, Waker},
};
/// A read guard that holds access to an async derived resource.
///
/// Implements [`Deref`](std::ops::Deref) to access the inner value. This should not be held longer
/// than it is needed, as it prevents updates to the inner value.
pub type AsyncDerivedGuard<T> =
ReadGuard<T, Mapped<AsyncPlain<SendOption<T>>, T>>;
/// A [`Future`] that is ready when an [`ArcAsyncDerived`] is finished loading or reloading,
/// but does not contain its value.
pub struct AsyncDerivedReadyFuture {
pub(crate) source: AnySource,
pub(crate) loading: Arc<AtomicBool>,
pub(crate) wakers: Arc<RwLock<Vec<Waker>>>,
}
impl AsyncDerivedReadyFuture {
/// Creates a new [`Future`] that will be ready when the given resource is ready.
pub fn new(
source: AnySource,
loading: &Arc<AtomicBool>,
wakers: &Arc<RwLock<Vec<Waker>>>,
) -> Self {
AsyncDerivedReadyFuture {
source,
loading: Arc::clone(loading),
wakers: Arc::clone(wakers),
}
}
}
impl Future for AsyncDerivedReadyFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[cfg(debug_assertions)]
let _guard = SpecialNonReactiveZone::enter();
let waker = cx.waker();
self.source.track();
if self.loading.load(Ordering::Relaxed) {
self.wakers.write().or_poisoned().push(waker.clone());
Poll::Pending
} else {
Poll::Ready(())
}
}
}
impl<T> IntoFuture for ArcAsyncDerived<T>
where
T: Clone + 'static,
{
type Output = T;
type IntoFuture = AsyncDerivedFuture<T>;
fn into_future(self) -> Self::IntoFuture {
AsyncDerivedFuture {
source: self.to_any_source(),
value: Arc::clone(&self.value),
loading: Arc::clone(&self.loading),
wakers: Arc::clone(&self.wakers),
inner: Arc::clone(&self.inner),
}
}
}
impl<T, S> IntoFuture for AsyncDerived<T, S>
where
T: Clone + 'static,
S: Storage<ArcAsyncDerived<T>>,
{
type Output = T;
type IntoFuture = AsyncDerivedFuture<T>;
#[track_caller]
fn into_future(self) -> Self::IntoFuture {
let this = self
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(self));
this.into_future()
}
}
/// A [`Future`] that is ready when an [`ArcAsyncDerived`] is finished loading or reloading,
/// and contains its value. `.await`ing this clones the value `T`.
pub struct AsyncDerivedFuture<T> {
source: AnySource,
value: Arc<async_lock::RwLock<SendOption<T>>>,
loading: Arc<AtomicBool>,
wakers: Arc<RwLock<Vec<Waker>>>,
inner: Arc<RwLock<ArcAsyncDerivedInner>>,
}
impl<T> Future for AsyncDerivedFuture<T>
where
T: Clone + 'static,
{
type Output = T;
#[track_caller]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[cfg(debug_assertions)]
let _guard = SpecialNonReactiveZone::enter();
let waker = cx.waker();
self.source.track();
let value = self.value.read_arc();
if let Some(suspense_context) = use_context::<SuspenseContext>() {
self.inner
.write()
.or_poisoned()
.suspenses
.push(suspense_context);
}
pin_mut!(value);
match (self.loading.load(Ordering::Relaxed), value.poll(cx)) {
(true, _) => {
self.wakers.write().or_poisoned().push(waker.clone());
Poll::Pending
}
(_, Poll::Pending) => Poll::Pending,
(_, Poll::Ready(guard)) => {
Poll::Ready(guard.as_ref().unwrap().clone())
}
}
}
}
impl<T: 'static> ArcAsyncDerived<T> {
/// Returns a `Future` that resolves when the computation is finished, and accesses the inner
/// value by reference rather than by cloning it.
#[track_caller]
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
AsyncDerivedRefFuture {
source: self.to_any_source(),
value: Arc::clone(&self.value),
loading: Arc::clone(&self.loading),
wakers: Arc::clone(&self.wakers),
}
}
}
impl<T, S> AsyncDerived<T, S>
where
T: 'static,
S: Storage<ArcAsyncDerived<T>>,
{
/// Returns a `Future` that resolves when the computation is finished, and accesses the inner
/// value by reference rather than by cloning it.
#[track_caller]
pub fn by_ref(&self) -> AsyncDerivedRefFuture<T> {
let this = self
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(self));
this.by_ref()
}
}
/// A [`Future`] that is ready when an [`ArcAsyncDerived`] is finished loading or reloading,
/// and yields an [`AsyncDerivedGuard`] that dereferences to its value.
pub struct AsyncDerivedRefFuture<T> {
source: AnySource,
value: Arc<async_lock::RwLock<SendOption<T>>>,
loading: Arc<AtomicBool>,
wakers: Arc<RwLock<Vec<Waker>>>,
}
impl<T> Future for AsyncDerivedRefFuture<T>
where
T: 'static,
{
type Output = AsyncDerivedGuard<T>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[cfg(debug_assertions)]
let _guard = SpecialNonReactiveZone::enter();
let waker = cx.waker();
self.source.track();
let value = self.value.read_arc();
pin_mut!(value);
match (self.loading.load(Ordering::Relaxed), value.poll(cx)) {
(true, _) => {
self.wakers.write().or_poisoned().push(waker.clone());
Poll::Pending
}
(_, Poll::Pending) => Poll::Pending,
(_, Poll::Ready(guard)) => Poll::Ready(ReadGuard::new(
Mapped::new_with_guard(AsyncPlain { guard }, |guard| {
guard.as_ref().unwrap()
}),
)),
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/tests/effect.rs | reactive_graph/tests/effect.rs | #[cfg(feature = "effects")]
pub mod imports {
pub use any_spawner::Executor;
pub use reactive_graph::{
effect::{Effect, RenderEffect},
owner::Owner,
prelude::*,
signal::RwSignal,
};
pub use std::{
mem,
sync::{Arc, RwLock},
};
pub use tokio::task;
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn render_effect_runs() {
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let b = Arc::new(RwLock::new(String::new()));
// we forget it so it continues running
// if it's dropped, it will stop listening
mem::forget(RenderEffect::new({
let b = b.clone();
move |_| {
let formatted = format!("Value is {}", a.get());
*b.write().unwrap() = formatted;
}
}));
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "Value is -1");
println!("setting to 1");
a.set(1);
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "Value is 1");
})
.await;
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn effect_runs() {
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let b = Arc::new(RwLock::new(String::new()));
Effect::new({
let b = b.clone();
move || {
let formatted = format!("Value is {}", a.get());
*b.write().unwrap() = formatted;
}
});
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "Value is -1");
println!("setting to 1");
a.set(1);
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "Value is 1");
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn dynamic_dependencies() {
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let first = RwSignal::new("Greg");
let last = RwSignal::new("Johnston");
let use_last = RwSignal::new(true);
let combined_count = Arc::new(RwLock::new(0));
mem::forget(RenderEffect::new({
let combined_count = Arc::clone(&combined_count);
move |_| {
*combined_count.write().unwrap() += 1;
if use_last.get() {
println!("{} {}", first.get(), last.get());
} else {
println!("{}", first.get());
}
}
}));
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 1);
println!("\nsetting `first` to Bob");
first.set("Bob");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 2);
println!("\nsetting `last` to Bob");
last.set("Thompson");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 3);
println!("\nsetting `use_last` to false");
use_last.set(false);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `last` to Jones");
last.set("Jones");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `last` to Jones");
last.set("Smith");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `last` to Stevens");
last.set("Stevens");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `use_last` to true");
use_last.set(true);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 5);
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn recursive_effect_runs_recursively() {
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let s = RwSignal::new(0);
let logged_values = Arc::new(RwLock::new(Vec::new()));
mem::forget(RenderEffect::new({
let logged_values = Arc::clone(&logged_values);
move |_| {
let a = s.get();
println!("a = {a}");
logged_values.write().unwrap().push(a);
if a == 0 {
return;
}
s.set(0);
}
}));
s.set(1);
Executor::tick().await;
s.set(2);
Executor::tick().await;
s.set(3);
Executor::tick().await;
assert_eq!(0, s.get_untracked());
assert_eq!(&*logged_values.read().unwrap(), &[0, 1, 0, 2, 0, 3, 0]);
})
.await;
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn paused_effect_pauses() {
use imports::*;
use reactive_graph::owner::StoredValue;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let runs = StoredValue::new(0);
let owner = StoredValue::new(None);
Effect::new({
move || {
*owner.write_value() = Owner::current();
let _ = a.get();
*runs.write_value() += 1;
}
});
Executor::tick().await;
assert_eq!(runs.get_value(), 1);
println!("setting to 1");
a.set(1);
Executor::tick().await;
assert_eq!(runs.get_value(), 2);
println!("pausing");
owner.get_value().unwrap().pause();
println!("setting to 2");
a.set(2);
Executor::tick().await;
assert_eq!(runs.get_value(), 2);
println!("resuming");
owner.get_value().unwrap().resume();
println!("setting to 3");
a.set(3);
Executor::tick().await;
println!("checking value");
assert_eq!(runs.get_value(), 3);
})
.await
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/tests/effect_immediate.rs | reactive_graph/tests/effect_immediate.rs | #[cfg(feature = "effects")]
pub mod imports {
pub use any_spawner::Executor;
pub use reactive_graph::{
effect::ImmediateEffect, owner::Owner, prelude::*, signal::RwSignal,
};
pub use std::sync::{Arc, RwLock};
pub use tokio::task;
}
#[cfg(feature = "effects")]
#[test]
fn effect_runs() {
use imports::*;
let owner = Owner::new();
owner.set();
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let b = Arc::new(RwLock::new(String::new()));
let _guard = ImmediateEffect::new({
let b = b.clone();
move || {
let formatted = format!("Value is {}", a.get());
*b.write().unwrap() = formatted;
}
});
assert_eq!(b.read().unwrap().as_str(), "Value is -1");
println!("setting to 1");
a.set(1);
assert_eq!(b.read().unwrap().as_str(), "Value is 1");
}
#[cfg(feature = "effects")]
#[test]
fn dynamic_dependencies() {
use imports::*;
let owner = Owner::new();
owner.set();
let first = RwSignal::new("Greg");
let last = RwSignal::new("Johnston");
let use_last = RwSignal::new(true);
let combined_count = Arc::new(RwLock::new(0));
let _guard = ImmediateEffect::new({
let combined_count = Arc::clone(&combined_count);
move || {
*combined_count.write().unwrap() += 1;
if use_last.get() {
println!("{} {}", first.get(), last.get());
} else {
println!("{}", first.get());
}
}
});
assert_eq!(*combined_count.read().unwrap(), 1);
println!("\nsetting `first` to Bob");
first.set("Bob");
assert_eq!(*combined_count.read().unwrap(), 2);
println!("\nsetting `last` to Bob");
last.set("Thompson");
assert_eq!(*combined_count.read().unwrap(), 3);
println!("\nsetting `use_last` to false");
use_last.set(false);
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `last` to Jones");
last.set("Jones");
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `last` to Jones");
last.set("Smith");
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `last` to Stevens");
last.set("Stevens");
assert_eq!(*combined_count.read().unwrap(), 4);
println!("\nsetting `use_last` to true");
use_last.set(true);
assert_eq!(*combined_count.read().unwrap(), 5);
}
#[cfg(feature = "effects")]
#[test]
fn recursive_effect_runs_recursively() {
use imports::*;
let owner = Owner::new();
owner.set();
let s = RwSignal::new(0);
let logged_values = Arc::new(RwLock::new(Vec::new()));
let _guard = ImmediateEffect::new({
let logged_values = Arc::clone(&logged_values);
move || {
let a = s.get();
println!("a = {a}");
logged_values.write().unwrap().push(a);
if a == 0 {
return;
}
s.set(0);
}
});
s.set(1);
s.set(2);
s.set(3);
assert_eq!(0, s.get_untracked());
assert_eq!(&*logged_values.read().unwrap(), &[0, 1, 0, 2, 0, 3, 0]);
}
#[cfg(feature = "effects")]
#[test]
fn paused_effect_pauses() {
use imports::*;
use reactive_graph::owner::StoredValue;
let owner = Owner::new();
owner.set();
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let runs = StoredValue::new(0);
let owner = StoredValue::new(None);
let _guard = ImmediateEffect::new({
move || {
*owner.write_value() = Owner::current();
let _ = a.get();
*runs.write_value() += 1;
}
});
assert_eq!(runs.get_value(), 1);
println!("setting to 1");
a.set(1);
assert_eq!(runs.get_value(), 2);
println!("pausing");
owner.get_value().unwrap().pause();
println!("setting to 2");
a.set(2);
assert_eq!(runs.get_value(), 2);
println!("resuming");
owner.get_value().unwrap().resume();
println!("setting to 3");
a.set(3);
println!("checking value");
assert_eq!(runs.get_value(), 3);
}
#[cfg(feature = "effects")]
#[test]
#[ignore = "Parallel signal access can panic."]
fn threaded_chaos_effect() {
use imports::*;
use reactive_graph::owner::StoredValue;
const SIGNAL_COUNT: usize = 5;
const THREAD_COUNT: usize = 10;
let owner = Owner::new();
owner.set();
let signals = vec![RwSignal::new(0); SIGNAL_COUNT];
let runs = StoredValue::new(0);
let _guard = ImmediateEffect::new({
let signals = signals.clone();
move || {
*runs.write_value() += 1;
let mut values = vec![];
for s in &signals {
let v = s.get();
values.push(v);
if v != 0 {
s.set(v - 1);
}
}
println!("{values:?}");
}
});
std::thread::scope(|s| {
for _ in 0..THREAD_COUNT {
let signals = signals.clone();
s.spawn(move || {
for s in &signals {
s.set(1);
}
});
}
});
assert_eq!(runs.get_value(), 1 + THREAD_COUNT * SIGNAL_COUNT);
let values: Vec<_> = signals.iter().map(|s| s.get_untracked()).collect();
println!("FINAL: {values:?}");
}
#[cfg(feature = "effects")]
#[test]
fn test_batch() {
use imports::*;
use reactive_graph::{effect::batch, owner::StoredValue};
let owner = Owner::new();
owner.set();
let a = RwSignal::new(0);
let b = RwSignal::new(0);
let values = StoredValue::new(Vec::new());
ImmediateEffect::new_scoped(move || {
println!("{} = {}", a.get(), b.get());
values.write_value().push((a.get(), b.get()));
});
a.set(1);
b.set(1);
batch(move || {
a.set(2);
b.set(2);
batch(move || {
a.set(3);
b.set(3);
});
});
assert_eq!(values.get_value(), vec![(0, 0), (1, 0), (1, 1), (3, 3)]);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/tests/signal.rs | reactive_graph/tests/signal.rs | use reactive_graph::{
owner::Owner,
signal::{arc_signal, signal, ArcRwSignal, RwSignal},
traits::{
Dispose, Get, GetUntracked, IntoInner, Read, Set, Update,
UpdateUntracked, With, WithUntracked, Write,
},
};
#[test]
fn create_arc_rw_signal() {
let a = ArcRwSignal::new(0);
assert_eq!(a.read(), 0);
assert_eq!(a.get(), 0);
assert_eq!(a.get_untracked(), 0);
assert_eq!(a.with_untracked(|n| n + 1), 1);
assert_eq!(a.with(|n| n + 1), 1);
assert_eq!(format!("{}", a.read()), "0");
}
#[test]
fn update_arc_rw_signal() {
let a = ArcRwSignal::new(0);
*a.write() += 1;
assert_eq!(a.get(), 1);
a.update(|n| *n += 1);
assert_eq!(a.get(), 2);
a.update_untracked(|n| *n += 1);
assert_eq!(a.get(), 3);
a.set(4);
assert_eq!(a.get(), 4);
}
#[test]
fn create_arc_signal() {
let (a, _) = arc_signal(0);
assert_eq!(a.read(), 0);
assert_eq!(a.get(), 0);
assert_eq!(a.with_untracked(|n| n + 1), 1);
assert_eq!(a.with(|n| n + 1), 1);
}
#[test]
fn update_arc_signal() {
let (a, set_a) = arc_signal(0);
*set_a.write() += 1;
assert_eq!(a.get(), 1);
set_a.update(|n| *n += 1);
assert_eq!(a.get(), 2);
set_a.update_untracked(|n| *n += 1);
assert_eq!(a.get(), 3);
set_a.set(4);
assert_eq!(a.get(), 4);
}
#[test]
fn create_rw_signal() {
let owner = Owner::new();
owner.set();
let a = RwSignal::new(0);
assert_eq!(a.read(), 0);
assert_eq!(a.get(), 0);
assert_eq!(a.with_untracked(|n| n + 1), 1);
assert_eq!(a.with(|n| n + 1), 1);
}
#[test]
fn update_rw_signal() {
let owner = Owner::new();
owner.set();
let a = RwSignal::new(1);
assert_eq!(a.read(), 1);
assert_eq!(a.get(), 1);
a.update(|n| *n += 1);
assert_eq!(a.get(), 2);
a.update_untracked(|n| *n += 1);
assert_eq!(a.get(), 3);
a.set(4);
assert_eq!(a.get(), 4);
}
#[test]
fn create_signal() {
let owner = Owner::new();
owner.set();
let (a, _) = signal(0);
assert_eq!(a.read(), 0);
assert_eq!(a.get(), 0);
assert_eq!(a.get_untracked(), 0);
assert_eq!(a.with_untracked(|n| n + 1), 1);
assert_eq!(a.with(|n| n + 1), 1);
}
#[test]
fn update_signal() {
let owner = Owner::new();
owner.set();
let (a, set_a) = signal(1);
assert_eq!(a.get(), 1);
set_a.update(|n| *n += 1);
assert_eq!(a.get(), 2);
set_a.update_untracked(|n| *n += 1);
assert_eq!(a.get(), 3);
set_a.set(4);
assert_eq!(a.get(), 4);
}
#[test]
fn into_inner_signal() {
let owner = Owner::new();
owner.set();
let rw_signal = RwSignal::new(1);
assert_eq!(rw_signal.get(), 1);
assert_eq!(rw_signal.into_inner(), Some(1));
}
#[test]
fn into_inner_arc_signal() {
let owner = Owner::new();
owner.set();
let (a, b) = arc_signal(2);
assert_eq!(a.get(), 2);
std::mem::drop(b);
assert_eq!(a.into_inner(), Some(2));
}
#[test]
fn into_inner_non_arc_signal() {
let owner = Owner::new();
owner.set();
let (a, b) = signal(2);
assert_eq!(a.get(), 2);
b.dispose();
assert_eq!(a.into_inner(), Some(2));
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/tests/watch.rs | reactive_graph/tests/watch.rs | #[cfg(feature = "effects")]
use any_spawner::Executor;
#[cfg(feature = "effects")]
use reactive_graph::owner::Owner;
#[cfg(feature = "effects")]
use reactive_graph::{effect::Effect, prelude::*, signal::RwSignal};
#[cfg(feature = "effects")]
use std::sync::{Arc, RwLock};
#[cfg(feature = "effects")]
use tokio::task;
#[cfg(feature = "effects")]
#[tokio::test]
async fn watch_runs() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let b = Arc::new(RwLock::new(String::new()));
let effect = Effect::watch(
move || a.get(),
{
let b = b.clone();
move |a, prev_a, prev_ret| {
let formatted = format!(
"Value is {a}; Prev is {prev_a:?}; Prev return is \
{prev_ret:?}"
);
*b.write().unwrap() = formatted;
a + 10
}
},
false,
);
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "");
a.set(1);
Executor::tick().await;
assert_eq!(
b.read().unwrap().as_str(),
"Value is 1; Prev is Some(-1); Prev return is None"
);
a.set(2);
Executor::tick().await;
assert_eq!(
b.read().unwrap().as_str(),
"Value is 2; Prev is Some(1); Prev return is Some(11)"
);
effect.stop();
*b.write().unwrap() = "nothing happened".to_string();
a.set(3);
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "nothing happened");
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn watch_runs_immediately() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let b = Arc::new(RwLock::new(String::new()));
Effect::watch(
move || a.get(),
{
let b = b.clone();
move |a, prev_a, prev_ret| {
let formatted = format!(
"Value is {a}; Prev is {prev_a:?}; Prev return is \
{prev_ret:?}"
);
*b.write().unwrap() = formatted;
a + 10
}
},
true,
);
Executor::tick().await;
assert_eq!(
b.read().unwrap().as_str(),
"Value is -1; Prev is None; Prev return is None"
);
a.set(1);
Executor::tick().await;
assert_eq!(
b.read().unwrap().as_str(),
"Value is 1; Prev is Some(-1); Prev return is Some(9)"
);
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn watch_ignores_callback() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let a = RwSignal::new(-1);
let b = RwSignal::new(0);
// simulate an arbitrary side effect
let s = Arc::new(RwLock::new(String::new()));
Effect::watch(
move || a.get(),
{
let s = s.clone();
move |a, _, _| {
let formatted =
format!("Value a is {a}; Value b is {}", b.get());
*s.write().unwrap() = formatted;
a + 10
}
},
false,
);
Executor::tick().await;
a.set(1);
Executor::tick().await;
assert_eq!(
s.read().unwrap().as_str(),
"Value a is 1; Value b is 0"
);
*s.write().unwrap() = "nothing happened".to_string();
b.set(10);
Executor::tick().await;
assert_eq!(s.read().unwrap().as_str(), "nothing happened");
a.set(2);
Executor::tick().await;
assert_eq!(
s.read().unwrap().as_str(),
"Value a is 2; Value b is 10"
);
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn deprecated_watch_runs() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let a = RwSignal::new(-1);
// simulate an arbitrary side effect
let b = Arc::new(RwLock::new(String::new()));
#[allow(deprecated)]
let effect = reactive_graph::effect::watch(
move || a.get(),
{
let b = b.clone();
move |a, prev_a, prev_ret| {
let formatted = format!(
"Value is {a}; Prev is {prev_a:?}; Prev return is \
{prev_ret:?}"
);
*b.write().unwrap() = formatted;
a + 10
}
},
false,
);
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "");
a.set(1);
Executor::tick().await;
assert_eq!(
b.read().unwrap().as_str(),
"Value is 1; Prev is Some(-1); Prev return is None"
);
a.set(2);
Executor::tick().await;
assert_eq!(
b.read().unwrap().as_str(),
"Value is 2; Prev is Some(1); Prev return is Some(11)"
);
effect();
*b.write().unwrap() = "nothing happened".to_string();
a.set(3);
Executor::tick().await;
assert_eq!(b.read().unwrap().as_str(), "nothing happened");
})
.await
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/tests/async_derived.rs | reactive_graph/tests/async_derived.rs | use any_spawner::Executor;
use reactive_graph::{
computed::{ArcAsyncDerived, AsyncDerived},
owner::Owner,
signal::RwSignal,
traits::{Get, Read, Set, With, WithUntracked},
};
use std::future::pending;
#[tokio::test]
async fn arc_async_derived_calculates_eagerly() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let value = ArcAsyncDerived::new(|| async {
Executor::tick().await;
42
});
assert_eq!(value.clone().await, 42);
}
#[tokio::test]
async fn arc_async_derived_tracks_signal_change() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let signal = RwSignal::new(10);
let value = ArcAsyncDerived::new(move || async move {
Executor::tick().await;
signal.get()
});
assert_eq!(value.clone().await, 10);
signal.set(30);
Executor::tick().await;
assert_eq!(value.clone().await, 30);
signal.set(50);
Executor::tick().await;
assert_eq!(value.clone().await, 50);
}
#[tokio::test]
async fn async_derived_calculates_eagerly() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let value = AsyncDerived::new(|| async {
Executor::tick().await;
42
});
assert_eq!(value.await, 42);
}
#[tokio::test]
async fn async_derived_tracks_signal_change() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let signal = RwSignal::new(10);
let value = AsyncDerived::new(move || async move {
Executor::tick().await;
signal.get()
});
assert_eq!(value.await, 10);
signal.set(30);
Executor::tick().await;
assert_eq!(value.await, 30);
signal.set(50);
Executor::tick().await;
assert_eq!(value.await, 50);
}
#[tokio::test]
async fn read_signal_traits_on_arc() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let value = ArcAsyncDerived::new(pending::<()>);
assert_eq!(value.read(), None);
assert_eq!(value.with_untracked(|n| *n), None);
assert_eq!(value.with(|n| *n), None);
assert_eq!(value.get(), None);
}
#[tokio::test]
async fn read_signal_traits_on_arena() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let value = AsyncDerived::new(pending::<()>);
println!("{:?}", value.read());
assert_eq!(value.read(), None);
assert_eq!(value.with_untracked(|n| *n), None);
assert_eq!(value.with(|n| *n), None);
assert_eq!(value.get(), None);
}
#[tokio::test]
async fn async_derived_with_initial() {
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let signal1 = RwSignal::new(0);
let signal2 = RwSignal::new(0);
let derived =
ArcAsyncDerived::new_with_initial(Some(5), move || async move {
// reactive values can be tracked anywhere in the `async` block
let value1 = signal1.get();
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
let value2 = signal2.get();
value1 + value2
});
// the value can be accessed synchronously as `Option<T>`
assert_eq!(derived.get(), Some(5));
// we can also .await the value, i.e., convert it into a Future
assert_eq!(derived.clone().await, 0);
assert_eq!(derived.get(), Some(0));
signal1.set(1);
// while the new value is still pending, the signal holds the old value
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
assert_eq!(derived.get(), Some(0));
// setting multiple dependencies will hold until the latest change is ready
signal2.set(1);
assert_eq!(derived.await, 2);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/tests/cleanup.rs | reactive_graph/tests/cleanup.rs | use reactive_graph::{
computed::Memo,
owner::{on_cleanup, Owner},
signal::{RwSignal, Trigger},
traits::{Dispose, GetUntracked, Track},
};
use std::sync::Arc;
#[test]
fn cleanup_on_dispose() {
let owner = Owner::new();
owner.set();
struct ExecuteOnDrop(Option<Box<dyn FnOnce() + Send + Sync>>);
impl ExecuteOnDrop {
fn new(f: impl FnOnce() + Send + Sync + 'static) -> Self {
Self(Some(Box::new(f)))
}
}
impl Drop for ExecuteOnDrop {
fn drop(&mut self) {
self.0.take().unwrap()();
}
}
let trigger = Trigger::new();
println!("STARTING");
let memo = Memo::new(move |_| {
trigger.track();
// An example of why you might want to do this is that
// when something goes out of reactive scope you want it to be cleaned up.
// The cleaning up might have side effects, and those side effects might cause
// re-renders where new `on_cleanup` are registered.
let on_drop = ExecuteOnDrop::new(|| {
on_cleanup(|| println!("Nested cleanup in progress."))
});
on_cleanup(move || {
println!("Cleanup in progress.");
drop(on_drop)
});
});
println!("Memo 1: {memo:?}");
memo.get_untracked(); // First cleanup registered.
memo.dispose(); // Cleanup not run here.
println!("Cleanup should have been executed.");
let memo = Memo::new(move |_| {
// New cleanup registered. It'll panic here.
on_cleanup(move || println!("Test passed."));
});
println!("Memo 2: {memo:?}");
println!("^ Note how the memos have the same key (different versions).");
memo.get_untracked(); // First cleanup registered.
println!("Test passed.");
memo.dispose();
}
#[test]
fn leak_on_dispose() {
let owner = Owner::new();
owner.set();
let trigger = Trigger::new();
let value = Arc::new(());
let weak = Arc::downgrade(&value);
let memo = Memo::new(move |_| {
trigger.track();
RwSignal::new(value.clone());
});
memo.get_untracked();
memo.dispose();
assert!(weak.upgrade().is_none()); // Should have been dropped.
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/tests/memo.rs | reactive_graph/tests/memo.rs | use reactive_graph::{
computed::{ArcMemo, Memo},
owner::Owner,
prelude::*,
signal::RwSignal,
wrappers::read::Signal,
};
use std::{
rc::Rc,
sync::{Arc, RwLock},
};
#[cfg(feature = "effects")]
pub mod imports {
pub use any_spawner::Executor;
pub use reactive_graph::{
computed::{ArcMemo, Memo},
effect::{Effect, RenderEffect},
prelude::*,
signal::RwSignal,
wrappers::read::Signal,
};
pub use std::{
mem,
rc::Rc,
sync::{Arc, RwLock},
};
pub use tokio::task;
}
#[test]
fn memo_calculates_value() {
let owner = Owner::new();
owner.set();
let a = RwSignal::new(1);
let b = RwSignal::new(2);
let c = RwSignal::new(3);
let d = Memo::new(move |_| a.get() + b.get() + c.get());
assert_eq!(d.read(), 6);
assert_eq!(d.with_untracked(|n| *n), 6);
assert_eq!(d.with(|n| *n), 6);
assert_eq!(d.get_untracked(), 6);
}
#[test]
fn arc_memo_readable() {
let owner = Owner::new();
owner.set();
let a = RwSignal::new(1);
let b = RwSignal::new(2);
let c = RwSignal::new(3);
let d = ArcMemo::new(move |_| a.get() + b.get() + c.get());
assert_eq!(d.read(), 6);
}
#[test]
fn memo_doesnt_repeat_calculation_per_get() {
let owner = Owner::new();
owner.set();
let calculations = Arc::new(RwLock::new(0));
let a = RwSignal::new(1);
let b = RwSignal::new(2);
let c = RwSignal::new(3);
let d = Memo::new({
let calculations = Arc::clone(&calculations);
move |_| {
*calculations.write().unwrap() += 1;
a.get() + b.get() + c.get()
}
});
assert_eq!(d.get_untracked(), 6);
assert_eq!(d.get_untracked(), 6);
assert_eq!(d.get_untracked(), 6);
assert_eq!(*calculations.read().unwrap(), 1);
println!("\n\n**setting to 0**");
a.set(0);
assert_eq!(d.get_untracked(), 5);
assert_eq!(*calculations.read().unwrap(), 2);
}
#[test]
fn nested_memos() {
let owner = Owner::new();
owner.set();
let a = RwSignal::new(0); // 1
let b = RwSignal::new(0); // 2
let c = Memo::new(move |_| {
println!("calculating C");
a.get() + b.get()
}); // 3
let d = Memo::new(move |_| {
println!("calculating D");
c.get() * 2
}); // 4
let e = Memo::new(move |_| {
println!("calculating E");
d.get() + 1
}); // 5
assert_eq!(e.get_untracked(), 1);
assert_eq!(d.get_untracked(), 0);
assert_eq!(c.get_untracked(), 0);
println!("\n\nFirst Set\n\n");
a.set(5);
assert_eq!(c.get_untracked(), 5);
assert_eq!(d.get_untracked(), 10);
assert_eq!(e.get_untracked(), 11);
println!("\n\nSecond Set\n\n");
b.set(1);
assert_eq!(e.get_untracked(), 13);
assert_eq!(d.get_untracked(), 12);
assert_eq!(c.get_untracked(), 6);
}
#[test]
fn memo_runs_only_when_inputs_change() {
let owner = Owner::new();
owner.set();
let call_count = Arc::new(RwLock::new(0));
let a = RwSignal::new(0);
let b = RwSignal::new(0);
let c = RwSignal::new(0);
// pretend that this is some kind of expensive computation and we need to access its its value often
// we could do this with a derived signal, but that would re-run the computation
// memos should only run when their inputs actually change: this is the only point
let c = Memo::new({
let call_count = call_count.clone();
move |_| {
let mut call_count = call_count.write().unwrap();
*call_count += 1;
a.get() + b.get() + c.get()
}
});
// initially the memo has not been called at all, because it's lazy
assert_eq!(*call_count.read().unwrap(), 0);
// here we access the value a bunch of times
assert_eq!(c.get_untracked(), 0);
assert_eq!(c.get_untracked(), 0);
assert_eq!(c.get_untracked(), 0);
assert_eq!(c.get_untracked(), 0);
assert_eq!(c.get_untracked(), 0);
// we've still only called the memo calculation once
assert_eq!(*call_count.read().unwrap(), 1);
// and we only call it again when an input changes
a.set(1);
assert_eq!(c.get_untracked(), 1);
assert_eq!(*call_count.read().unwrap(), 2);
}
#[test]
fn diamond_problem() {
let owner = Owner::new();
owner.set();
let name = RwSignal::new("Greg Johnston".to_string());
let first = Memo::new(move |_| {
println!("calculating first");
name.get().split_whitespace().next().unwrap().to_string()
});
let last = Memo::new(move |_| {
println!("calculating last");
name.get().split_whitespace().nth(1).unwrap().to_string()
});
let combined_count = Arc::new(RwLock::new(0));
let combined = Memo::new({
let combined_count = Arc::clone(&combined_count);
move |_| {
println!("calculating combined");
let mut combined_count = combined_count.write().unwrap();
*combined_count += 1;
format!("{} {}", first.get(), last.get())
}
});
assert_eq!(first.get_untracked(), "Greg");
assert_eq!(last.get_untracked(), "Johnston");
name.set("Will Smith".to_string());
assert_eq!(first.get_untracked(), "Will");
assert_eq!(last.get_untracked(), "Smith");
assert_eq!(combined.get_untracked(), "Will Smith");
// should not have run the memo logic twice, even
// though both paths have been updated
assert_eq!(*combined_count.read().unwrap(), 1);
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn dynamic_dependencies() {
let owner = Owner::new();
owner.set();
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let first = RwSignal::new("Greg");
let last = RwSignal::new("Johnston");
let use_last = RwSignal::new(true);
let name = Memo::new(move |_| {
if use_last.get() {
format!("{} {}", first.get(), last.get())
} else {
first.get().to_string()
}
});
let combined_count = Arc::new(RwLock::new(0));
// we forget it so it continues running
// if it's dropped, it will stop listening
println!("[Initial]");
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |_| {
println!("Effect running.");
_ = name.get();
*combined_count.write().unwrap() += 1;
}
});
Executor::tick().await;
println!("[After 1 tick]");
assert_eq!(*combined_count.read().unwrap(), 1);
println!("[Set 'Bob']");
first.set("Bob");
Executor::tick().await;
assert_eq!(name.get_untracked(), "Bob Johnston");
assert_eq!(*combined_count.read().unwrap(), 2);
println!("[Set 'Thompson']");
last.set("Thompson");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 3);
use_last.set(false);
Executor::tick().await;
assert_eq!(name.get_untracked(), "Bob");
assert_eq!(*combined_count.read().unwrap(), 4);
assert_eq!(*combined_count.read().unwrap(), 4);
last.set("Jones");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 4);
last.set("Smith");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 4);
last.set("Stevens");
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 4);
use_last.set(true);
Executor::tick().await;
assert_eq!(name.get_untracked(), "Bob Stevens");
assert_eq!(*combined_count.read().unwrap(), 5);
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn render_effect_doesnt_rerun_if_memo_didnt_change() {
let owner = Owner::new();
owner.set();
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let count = RwSignal::new(1);
let even = Memo::new(move |_| *count.read() % 2 == 0);
let combined_count = Arc::new(RwLock::new(0));
println!("[Initial]");
mem::forget(RenderEffect::new({
let combined_count = Arc::clone(&combined_count);
move |_| {
println!("INSIDE RENDEREFFECT");
*combined_count.write().unwrap() += 1;
println!("even = {}", even.get());
}
}));
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 1);
println!("[done]\n");
println!("\n[Set Signal to 2]");
count.set(2);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 2);
println!("[done]\n");
println!("\n[Set Signal to 4]");
count.set(4);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 2);
println!("[done]\n");
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn effect_doesnt_rerun_if_memo_didnt_change() {
let owner = Owner::new();
owner.set();
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let count = RwSignal::new(1);
let even = Memo::new(move |_| *count.read() % 2 == 0);
let combined_count = Arc::new(RwLock::new(0));
Effect::new({
let combined_count = Arc::clone(&combined_count);
move |_| {
*combined_count.write().unwrap() += 1;
println!("even = {}", even.get());
}
});
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 1);
count.set(2);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 2);
count.set(4);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 2);
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn effect_depending_on_signal_and_memo_doesnt_rerun_unnecessarily() {
let owner = Owner::new();
owner.set();
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let other_signal = RwSignal::new(false);
let count = RwSignal::new(1);
let even = Memo::new(move |_| *count.read() % 2 == 0);
let combined_count = Arc::new(RwLock::new(0));
Effect::new({
let combined_count = Arc::clone(&combined_count);
move |_| {
*combined_count.write().unwrap() += 1;
println!(
"even = {}\nother_signal = {}",
even.get(),
other_signal.get()
);
}
});
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 1);
count.set(2);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 2);
count.set(4);
Executor::tick().await;
assert_eq!(*combined_count.read().unwrap(), 2);
})
.await
}
#[test]
fn unsync_derived_signal_and_memo() {
let owner = Owner::new();
owner.set();
let a = RwSignal::new_local(Rc::new(1));
let b = RwSignal::new(2);
let c = RwSignal::new(3);
let d = Memo::new(move |_| *a.get() + b.get() + c.get());
let e = Rc::new(0);
let f = Signal::derive_local(move || d.get() + *e);
assert_eq!(d.read(), 6);
assert_eq!(d.with_untracked(|n| *n), 6);
assert_eq!(d.with(|n| *n), 6);
assert_eq!(d.get_untracked(), 6);
// derived signal also works
assert_eq!(f.with_untracked(|n| *n), 6);
assert_eq!(f.with(|n| *n), 6);
assert_eq!(f.get_untracked(), 6);
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn test_memo_multiple_read_guards() {
// regression test for https://github.com/leptos-rs/leptos/issues/3158
let owner = Owner::new();
owner.set();
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let memo = Memo::<i32>::new_with_compare(|_| 42, |_, _| true);
Effect::new(move |_| {
let guard_a = memo.read();
let guard_b = memo.read();
assert_eq!(guard_a, 42);
assert_eq!(guard_b, 42);
});
Executor::tick().await;
})
.await
}
#[cfg(feature = "effects")]
#[tokio::test]
async fn test_memo_read_guard_held() {
// regression test for https://github.com/leptos-rs/leptos/issues/3252
let owner = Owner::new();
owner.set();
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
task::LocalSet::new()
.run_until(async {
let source = RwSignal::new(0);
let directly_derived =
Memo::new_with_compare(move |_| source.get(), |_, _| true);
let indirect = Memo::new_with_compare(
move |_| directly_derived.get(),
|_, _| true,
);
Effect::new(move |_| {
let direct_value = directly_derived.read();
let indirect_value = indirect.get();
assert_eq!(direct_value, indirect_value);
});
Executor::tick().await;
source.set(1);
Executor::tick().await;
source.set(2);
Executor::tick().await;
})
.await
}
#[test]
fn memo_updates_even_if_not_read_until_later() {
#![allow(clippy::bool_assert_comparison)]
let owner = Owner::new();
owner.set();
// regression test for https://github.com/leptos-rs/leptos/issues/3339
let input = RwSignal::new(0);
let first_memo = Memo::new(move |_| input.get() == 1);
let second_memo = Memo::new(move |_| first_memo.get());
assert_eq!(input.get(), 0);
assert_eq!(first_memo.get(), false);
println!("update to 1");
input.set(1);
assert_eq!(input.get(), 1);
println!("read memo 1");
assert_eq!(first_memo.get(), true);
println!("read memo 2");
assert_eq!(second_memo.get(), true);
// this time, we don't read the memo
println!("\nupdate to 2");
input.set(2);
assert_eq!(input.get(), 2);
println!("read memo 1");
assert_eq!(first_memo.get(), false);
println!("\nupdate to 3");
input.set(3);
assert_eq!(input.get(), 3);
println!("read memo 1");
assert_eq!(first_memo.get(), false);
println!("read memo 2");
assert_eq!(second_memo.get(), false);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/const_str_slice_concat/src/lib.rs | const_str_slice_concat/src/lib.rs | #![no_std]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Utilities for const concatenation of string slices.
pub(crate) const MAX_TEMPLATE_SIZE: usize = 4096;
/// Converts a zero-terminated buffer of bytes into a UTF-8 string.
pub const fn str_from_buffer(buf: &[u8; MAX_TEMPLATE_SIZE]) -> &str {
match core::ffi::CStr::from_bytes_until_nul(buf) {
Ok(cstr) => match cstr.to_str() {
Ok(str) => str,
Err(_) => panic!("TEMPLATE FAILURE"),
},
Err(_) => panic!("TEMPLATE FAILURE"),
}
}
/// Concatenates any number of static strings into a single array.
// credit to Rainer Stropek, "Constant fun," Rust Linz, June 2022
pub const fn const_concat(
strs: &'static [&'static str],
) -> [u8; MAX_TEMPLATE_SIZE] {
let mut buffer = [0; MAX_TEMPLATE_SIZE];
let mut position = 0;
let mut remaining = strs;
while let [current, tail @ ..] = remaining {
let x = current.as_bytes();
let mut i = 0;
// have it iterate over bytes manually, because, again,
// no mutable references in const fns
while i < x.len() {
buffer[position] = x[i];
position += 1;
i += 1;
}
remaining = tail;
}
buffer
}
/// Converts a zero-terminated buffer of bytes into a UTF-8 string with the given prefix.
pub const fn const_concat_with_prefix(
strs: &'static [&'static str],
prefix: &'static str,
suffix: &'static str,
) -> [u8; MAX_TEMPLATE_SIZE] {
let mut buffer = [0; MAX_TEMPLATE_SIZE];
let mut position = 0;
let mut remaining = strs;
while let [current, tail @ ..] = remaining {
let x = current.as_bytes();
let mut i = 0;
// have it iterate over bytes manually, because, again,
// no mutable references in const fns
while i < x.len() {
buffer[position] = x[i];
position += 1;
i += 1;
}
remaining = tail;
}
if buffer[0] == 0 {
buffer
} else {
let mut new_buf = [0; MAX_TEMPLATE_SIZE];
let prefix = prefix.as_bytes();
let suffix = suffix.as_bytes();
let mut position = 0;
let mut i = 0;
while i < prefix.len() {
new_buf[position] = prefix[i];
position += 1;
i += 1;
}
i = 0;
while i < buffer.len() {
if buffer[i] == 0 {
break;
}
new_buf[position] = buffer[i];
position += 1;
i += 1;
}
i = 0;
while i < suffix.len() {
new_buf[position] = suffix[i];
position += 1;
i += 1;
}
new_buf
}
}
/// Converts any number of strings into a UTF-8 string, separated by the given string.
pub const fn const_concat_with_separator(
strs: &[&str],
separator: &'static str,
) -> [u8; MAX_TEMPLATE_SIZE] {
let mut buffer = [0; MAX_TEMPLATE_SIZE];
let mut position = 0;
let mut remaining = strs;
while let [current, tail @ ..] = remaining {
let x = current.as_bytes();
let mut i = 0;
// have it iterate over bytes manually, because, again,
// no mutable references in const fns
while i < x.len() {
buffer[position] = x[i];
position += 1;
i += 1;
}
if !x.is_empty() {
let mut position = 0;
let separator = separator.as_bytes();
while i < separator.len() {
buffer[position] = separator[i];
position += 1;
i += 1;
}
}
remaining = tail;
}
buffer
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_config/src/errors.rs | leptos_config/src/errors.rs | use std::{net::AddrParseError, num::ParseIntError, str::ParseBoolError};
use thiserror::Error;
#[derive(Debug, Error, Clone)]
pub enum LeptosConfigError {
#[error("Cargo.toml not found in package root")]
ConfigNotFound,
#[error("package.metadata.leptos section missing from Cargo.toml")]
ConfigSectionNotFound,
#[error("Failed to get Leptos Environment. Did you set LEPTOS_ENV?")]
EnvError,
#[error("Config Error: {0}")]
ConfigError(String),
#[error("Config Error: {0}")]
EnvVarError(String),
}
impl From<config::ConfigError> for LeptosConfigError {
fn from(e: config::ConfigError) -> Self {
Self::ConfigError(e.to_string())
}
}
impl From<ParseIntError> for LeptosConfigError {
fn from(e: ParseIntError) -> Self {
Self::ConfigError(e.to_string())
}
}
impl From<AddrParseError> for LeptosConfigError {
fn from(e: AddrParseError) -> Self {
Self::ConfigError(e.to_string())
}
}
impl From<ParseBoolError> for LeptosConfigError {
fn from(e: ParseBoolError) -> Self {
Self::ConfigError(e.to_string())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_config/src/lib.rs | leptos_config/src/lib.rs | #![forbid(unsafe_code)]
pub mod errors;
use crate::errors::LeptosConfigError;
use config::{Case, Config, File, FileFormat};
use regex::Regex;
use std::{
env::VarError, fs, net::SocketAddr, path::Path, str::FromStr, sync::Arc,
};
use typed_builder::TypedBuilder;
/// A Struct to allow us to parse LeptosOptions from the file. Not really needed, most interactions should
/// occur with LeptosOptions
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct ConfFile {
pub leptos_options: LeptosOptions,
}
/// This struct serves as a convenient place to store details used for configuring Leptos.
/// It's used in our actix and axum integrations to generate the
/// correct path for WASM, JS, and Websockets, as well as other configuration tasks.
/// It shares keys with cargo-leptos, to allow for easy interoperability
#[derive(TypedBuilder, Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
#[non_exhaustive]
pub struct LeptosOptions {
/// The name of the WASM and JS files generated by wasm-bindgen.
///
/// This should match the name that will be output when building your application.
///
/// You can easily set this using `env!("CARGO_CRATE_NAME")`.
#[builder(setter(into))]
pub output_name: Arc<str>,
/// The path of the all the files generated by cargo-leptos. This defaults to '.' for convenience when integrating with other
/// tools.
#[builder(setter(into), default=default_site_root())]
#[serde(default = "default_site_root")]
pub site_root: Arc<str>,
/// The path of the WASM and JS files generated by wasm-bindgen from the root of your app
/// By default, wasm-bindgen puts them in `pkg`.
#[builder(setter(into), default=default_site_pkg_dir())]
#[serde(default = "default_site_pkg_dir")]
pub site_pkg_dir: Arc<str>,
/// Used to configure the running environment of Leptos. Can be used to load dev constants and keys v prod, or change
/// things based on the deployment environment
/// I recommend passing in the result of `env::var("LEPTOS_ENV")`
#[builder(setter(into), default=default_env())]
#[serde(default = "default_env")]
pub env: Env,
/// Provides a way to control the address leptos is served from.
/// Using an env variable here would allow you to run the same code in dev and prod
/// Defaults to `127.0.0.1:3000`
#[builder(setter(into), default=default_site_addr())]
#[serde(default = "default_site_addr")]
pub site_addr: SocketAddr,
/// The port the Websocket watcher listens on. Should match the `reload_port` in cargo-leptos(if using).
/// Defaults to `3001`
#[builder(default = default_reload_port())]
#[serde(default = "default_reload_port")]
pub reload_port: u32,
/// The port the Websocket watcher listens on when on the client, e.g., when behind a reverse proxy.
/// Defaults to match reload_port
#[builder(default)]
#[serde(default)]
pub reload_external_port: Option<u32>,
/// The protocol the Websocket watcher uses on the client: `ws` in most cases, `wss` when behind a reverse https proxy.
/// Defaults to `ws`
#[builder(default)]
#[serde(default)]
pub reload_ws_protocol: ReloadWSProtocol,
/// The path of a custom 404 Not Found page to display when statically serving content, defaults to `site_root/404.html`
#[builder(default = default_not_found_path())]
#[serde(default = "default_not_found_path")]
pub not_found_path: Arc<str>,
/// The file name of the hash text file generated by cargo-leptos. Defaults to `hash.txt`.
#[builder(default = default_hash_file_name())]
#[serde(default = "default_hash_file_name")]
pub hash_file: Arc<str>,
/// If true, hashes will be generated for all files in the site_root and added to their file names.
/// Defaults to `false`.
#[builder(default = default_hash_files())]
#[serde(default = "default_hash_files")]
pub hash_files: bool,
/// The default prefix to use for server functions when generating API routes. Can be
/// overridden for individual functions using `#[server(prefix = "...")]` as usual.
///
/// This is useful to override the default prefix (`/api`) for all server functions without
/// needing to manually specify via `#[server(prefix = "...")]` on every server function.
#[builder(default, setter(strip_option))]
#[serde(default)]
pub server_fn_prefix: Option<String>,
/// Whether to disable appending the server functions' hashes to the end of their API names.
///
/// This is useful when an app's client side needs a stable server API. For example, shipping
/// the CSR WASM binary in a Tauri app. Tauri app releases are dependent on each platform's
/// distribution method (e.g., the Apple App Store or the Google Play Store), which typically
/// are much slower than the frequency at which a website can be updated. In addition, it's
/// common for users to not have the latest app version installed. In these cases, the CSR WASM
/// app would need to be able to continue calling the backend server function API, so the API
/// path needs to be consistent and not have a hash appended.
///
/// Note that the hash suffixes is intended as a way to ensure duplicate API routes are created.
/// Without the hash, server functions will need to have unique names to avoid creating
/// duplicate routes. Axum will throw an error if a duplicate route is added to the router, but
/// Actix will not.
#[builder(default)]
#[serde(default)]
pub disable_server_fn_hash: bool,
/// Include the module path of the server function in the API route. This is an alternative
/// strategy to prevent duplicate server function API routes (the default strategy is to add
/// a hash to the end of the route). Each element of the module path will be separated by a `/`.
/// For example, a server function with a fully qualified name of `parent::child::server_fn`
/// would have an API route of `/api/parent/child/server_fn` (possibly with a
/// different prefix and a hash suffix depending on the values of the other server fn configs).
#[builder(default)]
#[serde(default)]
pub server_fn_mod_path: bool,
}
impl LeptosOptions {
fn try_from_env() -> Result<Self, LeptosConfigError> {
let output_name = env_w_default(
"LEPTOS_OUTPUT_NAME",
std::option_env!("LEPTOS_OUTPUT_NAME",).unwrap_or_default(),
)?;
if output_name.is_empty() {
eprintln!(
"It looks like you're trying to compile Leptos without the \
LEPTOS_OUTPUT_NAME environment variable being set. There are \
two options\n 1. cargo-leptos is not being used, but \
get_configuration() is being passed None. This needs to be \
changed to Some(\"Cargo.toml\")\n 2. You are compiling \
Leptos without LEPTOS_OUTPUT_NAME being set with \
cargo-leptos. This shouldn't be possible!"
);
}
Ok(LeptosOptions {
output_name: output_name.into(),
site_root: env_w_default("LEPTOS_SITE_ROOT", "target/site")?.into(),
site_pkg_dir: env_w_default("LEPTOS_SITE_PKG_DIR", "pkg")?.into(),
env: env_from_str(env_w_default("LEPTOS_ENV", "DEV")?.as_str())?,
site_addr: env_w_default("LEPTOS_SITE_ADDR", "127.0.0.1:3000")?
.parse()?,
reload_port: env_w_default("LEPTOS_RELOAD_PORT", "3001")?
.parse()?,
reload_external_port: match env_wo_default(
"LEPTOS_RELOAD_EXTERNAL_PORT",
)? {
Some(val) => Some(val.parse()?),
None => None,
},
reload_ws_protocol: ws_from_str(
env_w_default("LEPTOS_RELOAD_WS_PROTOCOL", "ws")?.as_str(),
)?,
not_found_path: env_w_default("LEPTOS_NOT_FOUND_PATH", "/404")?
.into(),
hash_file: env_w_default("LEPTOS_HASH_FILE_NAME", "hash.txt")?
.into(),
hash_files: env_w_default("LEPTOS_HASH_FILES", "false")?.parse()?,
server_fn_prefix: env_wo_default("SERVER_FN_PREFIX")?,
disable_server_fn_hash: env_wo_default("DISABLE_SERVER_FN_HASH")?
.is_some(),
server_fn_mod_path: env_wo_default("SERVER_FN_MOD_PATH")?.is_some(),
})
}
}
fn default_site_root() -> Arc<str> {
".".into()
}
fn default_site_pkg_dir() -> Arc<str> {
"pkg".into()
}
fn default_env() -> Env {
Env::DEV
}
fn default_site_addr() -> SocketAddr {
SocketAddr::from(([127, 0, 0, 1], 3000))
}
fn default_reload_port() -> u32 {
3001
}
fn default_not_found_path() -> Arc<str> {
"/404".into()
}
fn default_hash_file_name() -> Arc<str> {
"hash.txt".into()
}
fn default_hash_files() -> bool {
false
}
fn env_wo_default(key: &str) -> Result<Option<String>, LeptosConfigError> {
match std::env::var(key) {
Ok(val) => Ok(Some(val)),
Err(VarError::NotPresent) => Ok(None),
Err(e) => Err(LeptosConfigError::EnvVarError(format!("{key}: {e}"))),
}
}
fn env_w_default(
key: &str,
default: &str,
) -> Result<String, LeptosConfigError> {
match std::env::var(key) {
Ok(val) => Ok(val),
Err(VarError::NotPresent) => Ok(default.to_string()),
Err(e) => Err(LeptosConfigError::EnvVarError(format!("{key}: {e}"))),
}
}
/// An enum that can be used to define the environment Leptos is running in.
/// Setting this to the `PROD` variant will not include the WebSocket code for `cargo-leptos` watch mode.
/// Defaults to `DEV`.
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Default,
)]
pub enum Env {
PROD,
#[default]
DEV,
}
fn env_from_str(input: &str) -> Result<Env, LeptosConfigError> {
let sanitized = input.to_lowercase();
match sanitized.as_ref() {
"dev" | "development" => Ok(Env::DEV),
"prod" | "production" => Ok(Env::PROD),
_ => Err(LeptosConfigError::EnvVarError(format!(
"{input} is not a supported environment. Use either `dev` or \
`production`.",
))),
}
}
impl FromStr for Env {
type Err = ();
fn from_str(input: &str) -> Result<Self, Self::Err> {
env_from_str(input).or_else(|_| Ok(Self::default()))
}
}
impl From<&str> for Env {
fn from(str: &str) -> Self {
env_from_str(str).unwrap_or_else(|err| panic!("{}", err))
}
}
impl From<&Result<String, VarError>> for Env {
fn from(input: &Result<String, VarError>) -> Self {
match input {
Ok(str) => {
env_from_str(str).unwrap_or_else(|err| panic!("{}", err))
}
Err(_) => Self::default(),
}
}
}
impl TryFrom<String> for Env {
type Error = LeptosConfigError;
fn try_from(s: String) -> Result<Self, Self::Error> {
env_from_str(s.as_str())
}
}
/// An enum that can be used to define the websocket protocol Leptos uses for hotreloading
/// Defaults to `ws`.
#[derive(
Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, Default,
)]
pub enum ReloadWSProtocol {
#[default]
WS,
WSS,
}
fn ws_from_str(input: &str) -> Result<ReloadWSProtocol, LeptosConfigError> {
let sanitized = input.to_lowercase();
match sanitized.as_ref() {
"ws" | "WS" => Ok(ReloadWSProtocol::WS),
"wss" | "WSS" => Ok(ReloadWSProtocol::WSS),
_ => Err(LeptosConfigError::EnvVarError(format!(
"{input} is not a supported websocket protocol. Use only `ws` or \
`wss`.",
))),
}
}
impl FromStr for ReloadWSProtocol {
type Err = ();
fn from_str(input: &str) -> Result<Self, Self::Err> {
ws_from_str(input).or_else(|_| Ok(Self::default()))
}
}
impl From<&str> for ReloadWSProtocol {
fn from(str: &str) -> Self {
ws_from_str(str).unwrap_or_else(|err| panic!("{}", err))
}
}
impl From<&Result<String, VarError>> for ReloadWSProtocol {
fn from(input: &Result<String, VarError>) -> Self {
match input {
Ok(str) => ws_from_str(str).unwrap_or_else(|err| panic!("{}", err)),
Err(_) => Self::default(),
}
}
}
impl TryFrom<String> for ReloadWSProtocol {
type Error = LeptosConfigError;
fn try_from(s: String) -> Result<Self, Self::Error> {
ws_from_str(s.as_str())
}
}
/// Loads [LeptosOptions] from a Cargo.toml text content with layered overrides.
/// If an env var is specified, like `LEPTOS_ENV`, it will override a setting in the file.
pub fn get_config_from_str(
text: &str,
) -> Result<LeptosOptions, LeptosConfigError> {
let re: Regex = Regex::new(r"(?m)^\[package.metadata.leptos\]").unwrap();
let re_workspace: Regex =
Regex::new(r"(?m)^\[\[workspace.metadata.leptos\]\]").unwrap();
let metadata_name;
let start;
match re.find(text) {
Some(found) => {
metadata_name = "[package.metadata.leptos]";
start = found.start();
}
None => match re_workspace.find(text) {
Some(found) => {
metadata_name = "[[workspace.metadata.leptos]]";
start = found.start();
}
None => return Err(LeptosConfigError::ConfigSectionNotFound),
},
};
// so that serde error messages have right line number
let newlines = text[..start].matches('\n').count();
let input = "\n".repeat(newlines) + &text[start..];
// so the settings will be interpreted as root level settings
let toml = input.replace(metadata_name, "");
let settings = Config::builder()
// Read the "default" configuration file
.add_source(File::from_str(&toml, FileFormat::Toml))
// Layer on the environment-specific values.
// Add in settings from environment variables (with a prefix of LEPTOS)
// E.g. `LEPTOS_RELOAD_PORT=5001 would set `LeptosOptions.reload_port`
.add_source(
config::Environment::with_prefix("LEPTOS")
.convert_case(Case::Kebab),
)
.build()?;
settings
.try_deserialize()
.map_err(|e| LeptosConfigError::ConfigError(e.to_string()))
}
/// Loads [LeptosOptions] from a Cargo.toml with layered overrides. If an env var is specified, like `LEPTOS_ENV`,
/// it will override a setting in the file. It takes in an optional path to a Cargo.toml file. If None is provided,
/// you'll need to set the options as environment variables or rely on the defaults. This is the preferred
/// approach for cargo-leptos. If Some("./Cargo.toml") is provided, Leptos will read in the settings itself. This
/// option currently does not allow dashes in file or folder names, as all dashes become underscores
pub fn get_configuration(
path: Option<&str>,
) -> Result<ConfFile, LeptosConfigError> {
if let Some(path) = path {
get_config_from_file(path)
} else {
get_config_from_env()
}
}
/// Loads [LeptosOptions] from a Cargo.toml with layered overrides. Leptos will read in the settings itself. This
/// option currently does not allow dashes in file or folder names, as all dashes become underscores
pub fn get_config_from_file<P: AsRef<Path>>(
path: P,
) -> Result<ConfFile, LeptosConfigError> {
let text = fs::read_to_string(path)
.map_err(|_| LeptosConfigError::ConfigNotFound)?;
let leptos_options = get_config_from_str(&text)?;
Ok(ConfFile { leptos_options })
}
/// Loads [LeptosOptions] from environment variables or rely on the defaults
pub fn get_config_from_env() -> Result<ConfFile, LeptosConfigError> {
Ok(ConfFile {
leptos_options: LeptosOptions::try_from_env()?,
})
}
#[path = "tests.rs"]
#[cfg(test)]
mod tests;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_config/src/tests.rs | leptos_config/src/tests.rs | use crate::{
env_from_str, env_w_default, env_wo_default, ws_from_str, Env,
LeptosOptions, ReloadWSProtocol,
};
use std::{net::SocketAddr, str::FromStr};
#[test]
fn env_from_str_test() {
assert!(matches!(env_from_str("dev").unwrap(), Env::DEV));
assert!(matches!(env_from_str("development").unwrap(), Env::DEV));
assert!(matches!(env_from_str("DEV").unwrap(), Env::DEV));
assert!(matches!(env_from_str("DEVELOPMENT").unwrap(), Env::DEV));
assert!(matches!(env_from_str("prod").unwrap(), Env::PROD));
assert!(matches!(env_from_str("production").unwrap(), Env::PROD));
assert!(matches!(env_from_str("PROD").unwrap(), Env::PROD));
assert!(matches!(env_from_str("PRODUCTION").unwrap(), Env::PROD));
assert!(env_from_str("TEST").is_err());
assert!(env_from_str("?").is_err());
}
#[test]
fn ws_from_str_test() {
assert!(matches!(ws_from_str("ws").unwrap(), ReloadWSProtocol::WS));
assert!(matches!(ws_from_str("WS").unwrap(), ReloadWSProtocol::WS));
assert!(matches!(ws_from_str("wss").unwrap(), ReloadWSProtocol::WSS));
assert!(matches!(ws_from_str("WSS").unwrap(), ReloadWSProtocol::WSS));
assert!(ws_from_str("TEST").is_err());
assert!(ws_from_str("?").is_err());
}
#[test]
fn env_w_default_test() {
temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
assert_eq!(
env_w_default("LEPTOS_CONFIG_ENV_TEST", "default").unwrap(),
String::from("custom")
);
});
temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
assert_eq!(
env_w_default("LEPTOS_CONFIG_ENV_TEST", "default").unwrap(),
String::from("default")
);
});
}
#[test]
fn env_wo_default_test() {
temp_env::with_var("LEPTOS_CONFIG_ENV_TEST", Some("custom"), || {
assert_eq!(
env_wo_default("LEPTOS_CONFIG_ENV_TEST").unwrap(),
Some(String::from("custom"))
);
});
temp_env::with_var_unset("LEPTOS_CONFIG_ENV_TEST", || {
assert_eq!(env_wo_default("LEPTOS_CONFIG_ENV_TEST").unwrap(), None);
});
}
#[test]
fn try_from_env_test() {
// Test config values from environment variables
let config = temp_env::with_vars(
[
("LEPTOS_OUTPUT_NAME", Some("app_test")),
("LEPTOS_SITE_ROOT", Some("my_target/site")),
("LEPTOS_SITE_PKG_DIR", Some("my_pkg")),
("LEPTOS_SITE_ADDR", Some("0.0.0.0:80")),
("LEPTOS_RELOAD_PORT", Some("8080")),
("LEPTOS_RELOAD_EXTERNAL_PORT", Some("8080")),
("LEPTOS_ENV", Some("PROD")),
("LEPTOS_RELOAD_WS_PROTOCOL", Some("WSS")),
],
|| LeptosOptions::try_from_env().unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app_test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
);
assert_eq!(config.reload_port, 8080);
assert_eq!(config.reload_external_port, Some(8080));
assert_eq!(config.env, Env::PROD);
assert_eq!(config.reload_ws_protocol, ReloadWSProtocol::WSS)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_config/tests/config.rs | leptos_config/tests/config.rs | use leptos_config::{
get_config_from_file, get_config_from_str, get_configuration, Env,
LeptosOptions,
};
use std::{fs::File, io::Write, net::SocketAddr, path::Path, str::FromStr};
use tempfile::NamedTempFile;
#[test]
fn env_default() {
assert!(matches!(Env::default(), Env::DEV));
}
const CARGO_TOML_CONTENT_OK: &str = r#"\
[package.metadata.leptos]
output-name = "app-test"
site-root = "my_target/site"
site-pkg-dir = "my_pkg"
site-addr = "0.0.0.0:80"
reload-port = "8080"
reload-external-port = "8080"
env = "PROD"
"#;
const CARGO_TOML_CONTENT_ERR: &str = r#"\
[package.metadata.leptos]
- invalid toml -
"#;
#[tokio::test]
async fn get_configuration_from_file_ok() {
let cargo_tmp = NamedTempFile::new().unwrap();
{
let mut output = File::create(&cargo_tmp).unwrap();
write!(output, "{CARGO_TOML_CONTENT_OK}").unwrap();
}
let path: &Path = cargo_tmp.as_ref();
let path_s = path.to_string_lossy().to_string();
let config = temp_env::async_with_vars(
[
("LEPTOS_OUTPUT_NAME", None::<&str>),
("LEPTOS_SITE_ROOT", None::<&str>),
("LEPTOS_SITE_PKG_DIR", None::<&str>),
("LEPTOS_SITE_ADDR", None::<&str>),
("LEPTOS_RELOAD_PORT", None::<&str>),
("LEPTOS_RELOAD_EXTERNAL_PORT", None::<&str>),
],
async { get_configuration(Some(&path_s)).unwrap().leptos_options },
)
.await;
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
);
assert_eq!(config.reload_port, 8080);
assert_eq!(config.reload_external_port, Some(8080));
}
#[tokio::test]
async fn get_configuration_from_invalid_file() {
let cargo_tmp = NamedTempFile::new().unwrap();
{
let mut output = File::create(&cargo_tmp).unwrap();
write!(output, "{CARGO_TOML_CONTENT_ERR}").unwrap();
}
let path: &Path = cargo_tmp.as_ref();
let path_s = path.to_string_lossy().to_string();
assert!(get_configuration(Some(&path_s)).is_err());
}
#[tokio::test]
async fn get_configuration_from_empty_file() {
let cargo_tmp = NamedTempFile::new().unwrap();
{
let mut output = File::create(&cargo_tmp).unwrap();
write!(output, "").unwrap();
}
let path: &Path = cargo_tmp.as_ref();
let path_s = path.to_string_lossy().to_string();
assert!(get_configuration(Some(&path_s)).is_err());
}
#[tokio::test]
async fn get_config_from_file_ok() {
let cargo_tmp = NamedTempFile::new().unwrap();
{
let mut output = File::create(&cargo_tmp).unwrap();
write!(output, "{CARGO_TOML_CONTENT_OK}").unwrap();
}
let config = temp_env::async_with_vars(
[
("LEPTOS_OUTPUT_NAME", None::<&str>),
("LEPTOS_SITE_ROOT", None::<&str>),
("LEPTOS_SITE_PKG_DIR", None::<&str>),
("LEPTOS_SITE_ADDR", None::<&str>),
("LEPTOS_RELOAD_PORT", None::<&str>),
("LEPTOS_RELOAD_EXTERNAL_PORT", None::<&str>),
],
async { get_config_from_file(&cargo_tmp).unwrap().leptos_options },
)
.await;
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
);
assert_eq!(config.reload_port, 8080);
assert_eq!(config.reload_external_port, Some(8080));
}
#[tokio::test]
async fn get_config_from_file_invalid() {
let cargo_tmp = NamedTempFile::new().unwrap();
{
let mut output = File::create(&cargo_tmp).unwrap();
write!(output, "{CARGO_TOML_CONTENT_ERR}").unwrap();
}
assert!(get_config_from_file(&cargo_tmp).is_err());
}
#[tokio::test]
async fn get_config_from_file_empty() {
let cargo_tmp = NamedTempFile::new().unwrap();
{
let mut output = File::create(&cargo_tmp).unwrap();
write!(output, "").unwrap();
}
assert!(get_config_from_file(&cargo_tmp).is_err());
}
#[test]
fn get_config_from_str_content() {
let config = temp_env::with_vars_unset(
[
"LEPTOS_OUTPUT_NAME",
"LEPTOS_SITE_ROOT",
"LEPTOS_SITE_PKG_DIR",
"LEPTOS_SITE_ADDR",
"LEPTOS_RELOAD_PORT",
"LEPTOS_RELOAD_EXTERNAL_PORT",
],
|| get_config_from_str(CARGO_TOML_CONTENT_OK).unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
);
assert_eq!(config.reload_port, 8080);
assert_eq!(config.reload_external_port, Some(8080));
}
#[tokio::test]
async fn get_config_from_env() {
// Test config values from environment variables
let config = temp_env::async_with_vars(
[
("LEPTOS_OUTPUT_NAME", Some("app-test")),
("LEPTOS_SITE_ROOT", Some("my_target/site")),
("LEPTOS_SITE_PKG_DIR", Some("my_pkg")),
("LEPTOS_SITE_ADDR", Some("0.0.0.0:80")),
("LEPTOS_RELOAD_PORT", Some("8080")),
("LEPTOS_RELOAD_EXTERNAL_PORT", Some("8080")),
],
async { get_configuration(None).unwrap().leptos_options },
)
.await;
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
);
assert_eq!(config.reload_port, 8080);
assert_eq!(config.reload_external_port, Some(8080));
// Test default config values
let config = temp_env::async_with_vars(
[
("LEPTOS_OUTPUT_NAME", None::<&str>),
("LEPTOS_SITE_ROOT", None::<&str>),
("LEPTOS_SITE_PKG_DIR", None::<&str>),
("LEPTOS_SITE_ADDR", None::<&str>),
("LEPTOS_RELOAD_PORT", None::<&str>),
("LEPTOS_RELOAD_EXTERNAL_PORT", None::<&str>),
],
async { get_configuration(None).unwrap().leptos_options },
)
.await;
assert_eq!(config.site_root.as_ref(), "target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("127.0.0.1:3000").unwrap()
);
assert_eq!(config.reload_port, 3001);
assert_eq!(config.reload_external_port, None);
}
#[test]
fn leptos_options_builder_default() {
let conf = LeptosOptions::builder().output_name("app-test").build();
assert_eq!(conf.output_name.as_ref(), "app-test");
assert!(matches!(conf.env, Env::DEV));
assert_eq!(conf.site_pkg_dir.as_ref(), "pkg");
assert_eq!(conf.site_root.as_ref(), ".");
assert_eq!(
conf.site_addr,
SocketAddr::from_str("127.0.0.1:3000").unwrap()
);
assert_eq!(conf.reload_port, 3001);
assert_eq!(conf.reload_external_port, None);
}
#[test]
fn environment_variable_override() {
// first check without variables set
let config = temp_env::with_vars_unset(
[
"LEPTOS_OUTPUT_NAME",
"LEPTOS_SITE_ROOT",
"LEPTOS_SITE_PKG_DIR",
"LEPTOS_SITE_ADDR",
"LEPTOS_RELOAD_PORT",
"LEPTOS_RELOAD_EXTERNAL_PORT",
],
|| get_config_from_str(CARGO_TOML_CONTENT_OK).unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app-test");
assert_eq!(config.site_root.as_ref(), "my_target/site");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:80").unwrap()
);
assert_eq!(config.reload_port, 8080);
assert_eq!(config.reload_external_port, Some(8080));
// check the override
let config = temp_env::with_vars(
[
("LEPTOS_OUTPUT_NAME", Some("app-test2")),
("LEPTOS_SITE_ROOT", Some("my_target/site2")),
("LEPTOS_SITE_PKG_DIR", Some("my_pkg2")),
("LEPTOS_SITE_ADDR", Some("0.0.0.0:82")),
("LEPTOS_RELOAD_PORT", Some("8082")),
("LEPTOS_RELOAD_EXTERNAL_PORT", Some("8082")),
],
|| get_config_from_str(CARGO_TOML_CONTENT_OK).unwrap(),
);
assert_eq!(config.output_name.as_ref(), "app-test2");
assert_eq!(config.site_root.as_ref(), "my_target/site2");
assert_eq!(config.site_pkg_dir.as_ref(), "my_pkg2");
assert_eq!(
config.site_addr,
SocketAddr::from_str("0.0.0.0:82").unwrap()
);
assert_eq!(config.reload_port, 8082);
assert_eq!(config.reload_external_port, Some(8082));
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/src/lib.rs | leptos_dom/src/lib.rs | #![deny(missing_docs)]
#![forbid(unsafe_code)]
//! DOM helpers for Leptos.
pub mod helpers;
#[doc(hidden)]
pub mod macro_helpers;
/// Utilities for simple isomorphic logging to the console or terminal.
pub mod logging;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/src/helpers.rs | leptos_dom/src/helpers.rs | //! A variety of DOM utility functions.
use or_poisoned::OrPoisoned;
#[cfg(debug_assertions)]
use reactive_graph::diagnostics::SpecialNonReactiveZone;
use reactive_graph::owner::Owner;
use send_wrapper::SendWrapper;
use std::time::Duration;
use tachys::html::event::EventDescriptor;
#[cfg(feature = "tracing")]
use tracing::instrument;
use wasm_bindgen::{prelude::Closure, JsCast, JsValue, UnwrapThrowExt};
thread_local! {
pub(crate) static WINDOW: web_sys::Window = web_sys::window().unwrap_throw();
pub(crate) static DOCUMENT: web_sys::Document = web_sys::window().unwrap_throw().document().unwrap_throw();
}
/// Returns the [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window).
///
/// This is cached as a thread-local variable, so calling `window()` multiple times
/// requires only one call out to JavaScript.
pub fn window() -> web_sys::Window {
WINDOW.with(Clone::clone)
}
/// Returns the [`Document`](https://developer.mozilla.org/en-US/docs/Web/API/Document).
///
/// This is cached as a thread-local variable, so calling `document()` multiple times
/// requires only one call out to JavaScript.
pub fn document() -> web_sys::Document {
DOCUMENT.with(Clone::clone)
}
/// Sets a property on a DOM element.
pub fn set_property(
el: &web_sys::Element,
prop_name: &str,
value: &Option<JsValue>,
) {
let key = JsValue::from_str(prop_name);
match value {
Some(value) => _ = js_sys::Reflect::set(el, &key, value),
None => _ = js_sys::Reflect::delete_property(el, &key),
};
}
/// Gets the value of a property set on a DOM element.
#[doc(hidden)]
pub fn get_property(
el: &web_sys::Element,
prop_name: &str,
) -> Result<JsValue, JsValue> {
let key = JsValue::from_str(prop_name);
js_sys::Reflect::get(el, &key)
}
/// Returns the current [`window.location`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location).
pub fn location() -> web_sys::Location {
window().location()
}
/// Current [`window.location.hash`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location)
/// without the beginning #.
pub fn location_hash() -> Option<String> {
if is_server() {
None
} else {
location()
.hash()
.ok()
.map(|hash| match hash.chars().next() {
Some('#') => hash[1..].to_string(),
_ => hash,
})
}
}
/// Current [`window.location.pathname`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location).
pub fn location_pathname() -> Option<String> {
location().pathname().ok()
}
/// Helper function to extract [`Event.target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target)
/// from any event.
pub fn event_target<T>(event: &web_sys::Event) -> T
where
T: JsCast,
{
event.target().unwrap_throw().unchecked_into::<T>()
}
/// Helper function to extract `event.target.value` from an event.
///
/// This is useful in the `on:input` or `on:change` listeners for an `<input>` element.
pub fn event_target_value<T>(event: &T) -> String
where
T: JsCast,
{
event
.unchecked_ref::<web_sys::Event>()
.target()
.unwrap_throw()
.unchecked_into::<web_sys::HtmlInputElement>()
.value()
}
/// Helper function to extract `event.target.checked` from an event.
///
/// This is useful in the `on:change` listeners for an `<input type="checkbox">` element.
pub fn event_target_checked(ev: &web_sys::Event) -> bool {
ev.target()
.unwrap()
.unchecked_into::<web_sys::HtmlInputElement>()
.checked()
}
/// Handle that is generated by [request_animation_frame_with_handle] and can
/// be used to cancel the animation frame request.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct AnimationFrameRequestHandle(i32);
impl AnimationFrameRequestHandle {
/// Cancels the animation frame request to which this refers.
/// See [`cancelAnimationFrame()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame)
pub fn cancel(&self) {
_ = window().cancel_animation_frame(self.0);
}
}
/// Runs the given function between the next repaint using
/// [`Window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame).
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_animation_frame(cb: impl FnOnce() + 'static) {
_ = request_animation_frame_with_handle(cb);
}
// Closure::once_into_js only frees the callback when it's actually
// called, so this instead uses into_js_value, which can be freed by
// the host JS engine's GC if it supports weak references (which all
// modern browser engines do). The way this works is that the provided
// callback's captured data is dropped immediately after being called,
// as before, but it leaves behind a small stub closure rust-side that
// will be freed "eventually" by the JS GC. If the function is never
// called (e.g., it's a cancelled timeout or animation frame callback)
// then it will also be freed eventually.
fn closure_once(cb: impl FnOnce() + 'static) -> JsValue {
let mut wrapped_cb: Option<Box<dyn FnOnce()>> = Some(Box::new(cb));
let closure = Closure::new(move || {
if let Some(cb) = wrapped_cb.take() {
cb()
}
});
closure.into_js_value()
}
/// Runs the given function between the next repaint using
/// [`Window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame),
/// returning a cancelable handle.
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_animation_frame_with_handle(
cb: impl FnOnce() + 'static,
) -> Result<AnimationFrameRequestHandle, JsValue> {
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
#[cfg(feature = "tracing")]
let cb = move || {
let _guard = span.enter();
cb();
};
#[inline(never)]
fn raf(cb: JsValue) -> Result<AnimationFrameRequestHandle, JsValue> {
window()
.request_animation_frame(cb.as_ref().unchecked_ref())
.map(AnimationFrameRequestHandle)
}
raf(closure_once(cb))
}
/// Handle that is generated by [request_idle_callback_with_handle] and can be
/// used to cancel the idle callback.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct IdleCallbackHandle(u32);
impl IdleCallbackHandle {
/// Cancels the idle callback to which this refers.
/// See [`cancelAnimationFrame()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelIdleCallback)
pub fn cancel(&self) {
window().cancel_idle_callback(self.0);
}
}
/// Queues the given function during an idle period using
/// [`Window.requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestIdleCallback).
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_idle_callback(cb: impl Fn() + 'static) {
_ = request_idle_callback_with_handle(cb);
}
/// Queues the given function during an idle period using
/// [`Window.requestIdleCallback`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestIdleCallback),
/// returning a cancelable handle.
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(feature = "tracing", instrument(level = "trace", skip_all))]
#[inline(always)]
pub fn request_idle_callback_with_handle(
cb: impl Fn() + 'static,
) -> Result<IdleCallbackHandle, JsValue> {
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
#[cfg(feature = "tracing")]
let cb = move || {
let _guard = span.enter();
cb();
};
#[inline(never)]
fn ric(cb: Box<dyn Fn()>) -> Result<IdleCallbackHandle, JsValue> {
let cb = Closure::wrap(cb).into_js_value();
window()
.request_idle_callback(cb.as_ref().unchecked_ref())
.map(IdleCallbackHandle)
}
ric(Box::new(cb))
}
/// A microtask is a short function which will run after the current task has
/// completed its work and when there is no other code waiting to be run before
/// control of the execution context is returned to the browser's event loop.
///
/// Microtasks are especially useful for libraries and frameworks that need
/// to perform final cleanup or other just-before-rendering tasks.
///
/// [MDN queueMicrotask](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask)
///
/// <div class="warning">The task is called outside of the ownership tree, this means that if you want to access for example the context you need to reestablish the owner.</div>
pub fn queue_microtask(task: impl FnOnce() + 'static) {
tachys::renderer::dom::queue_microtask(task);
}
/// Handle that is generated by [set_timeout_with_handle] and can be used to clear the timeout.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct TimeoutHandle(i32);
impl TimeoutHandle {
/// Cancels the timeout to which this refers.
/// See [`clearTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout)
pub fn clear(&self) {
window().clear_timeout_with_handle(self.0);
}
}
/// Executes the given function after the given duration of time has passed.
/// [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout).
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(
feature = "tracing",
instrument(level = "trace", skip_all, fields(duration = ?duration))
)]
pub fn set_timeout(cb: impl FnOnce() + 'static, duration: Duration) {
_ = set_timeout_with_handle(cb, duration);
}
/// Executes the given function after the given duration of time has passed, returning a cancelable handle.
/// [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout).
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(
feature = "tracing",
instrument(level = "trace", skip_all, fields(duration = ?duration))
)]
#[inline(always)]
pub fn set_timeout_with_handle(
cb: impl FnOnce() + 'static,
duration: Duration,
) -> Result<TimeoutHandle, JsValue> {
#[cfg(debug_assertions)]
let cb = || {
let _z = SpecialNonReactiveZone::enter();
cb();
};
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
#[cfg(feature = "tracing")]
let cb = move || {
let _guard = span.enter();
cb();
};
#[inline(never)]
fn st(cb: JsValue, duration: Duration) -> Result<TimeoutHandle, JsValue> {
window()
.set_timeout_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)
.map(TimeoutHandle)
}
st(closure_once(cb), duration)
}
/// "Debounce" a callback function. This will cause it to wait for a period of `delay`
/// after it is called. If it is called again during that period, it will wait
/// `delay` before running, and so on. This can be used, for example, to wrap event
/// listeners to prevent them from firing constantly as you type.
///
/// ```
/// use leptos::{leptos_dom::helpers::debounce, logging::log, prelude::*, *};
///
/// #[component]
/// fn DebouncedButton() -> impl IntoView {
/// let delay = std::time::Duration::from_millis(250);
/// let on_click = debounce(delay, move |_| {
/// log!("...so many clicks!");
/// });
///
/// view! {
/// <button on:click=on_click>"Click me"</button>
/// }
/// }
/// ```
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
pub fn debounce<T: 'static>(
delay: Duration,
mut cb: impl FnMut(T) + 'static,
) -> impl FnMut(T) {
use std::sync::{Arc, RwLock};
#[cfg(debug_assertions)]
#[allow(unused_mut)]
let mut cb = move |value| {
let _z = SpecialNonReactiveZone::enter();
cb(value);
};
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
#[cfg(feature = "tracing")]
#[allow(unused_mut)]
let mut cb = move |value| {
let _guard = span.enter();
cb(value);
};
let cb = Arc::new(RwLock::new(cb));
let timer = Arc::new(RwLock::new(None::<TimeoutHandle>));
Owner::on_cleanup({
let timer = Arc::clone(&timer);
move || {
if let Some(timer) = timer.write().or_poisoned().take() {
timer.clear();
}
}
});
move |arg| {
if let Some(timer) = timer.write().unwrap().take() {
timer.clear();
}
let handle = set_timeout_with_handle(
{
let cb = Arc::clone(&cb);
move || {
cb.write().unwrap()(arg);
}
},
delay,
);
if let Ok(handle) = handle {
*timer.write().or_poisoned() = Some(handle);
}
}
}
/// Handle that is generated by [set_interval] and can be used to clear the interval.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct IntervalHandle(i32);
impl IntervalHandle {
/// Cancels the repeating event to which this refers.
/// See [`clearInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval)
pub fn clear(&self) {
window().clear_interval_with_handle(self.0);
}
}
/// Repeatedly calls the given function, with a delay of the given duration between calls.
/// See [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval).
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(
feature = "tracing",
instrument(level = "trace", skip_all, fields(duration = ?duration))
)]
pub fn set_interval(cb: impl Fn() + 'static, duration: Duration) {
_ = set_interval_with_handle(cb, duration);
}
/// Repeatedly calls the given function, with a delay of the given duration between calls,
/// returning a cancelable handle.
/// See [`setInterval()`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval).
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(
feature = "tracing",
instrument(level = "trace", skip_all, fields(duration = ?duration))
)]
#[inline(always)]
pub fn set_interval_with_handle(
cb: impl Fn() + 'static,
duration: Duration,
) -> Result<IntervalHandle, JsValue> {
#[cfg(debug_assertions)]
let cb = move || {
let _z = SpecialNonReactiveZone::enter();
cb();
};
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
#[cfg(feature = "tracing")]
let cb = move || {
let _guard = span.enter();
cb();
};
#[inline(never)]
fn si(
cb: Box<dyn FnMut()>,
duration: Duration,
) -> Result<IntervalHandle, JsValue> {
let cb = Closure::wrap(cb).into_js_value();
window()
.set_interval_with_callback_and_timeout_and_arguments_0(
cb.as_ref().unchecked_ref(),
duration.as_millis().try_into().unwrap_throw(),
)
.map(IntervalHandle)
}
si(Box::new(cb), duration)
}
/// Adds an event listener to the `Window`, typed as a generic `Event`,
/// returning a cancelable handle.
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
#[cfg_attr(
feature = "tracing",
instrument(level = "trace", skip_all, fields(event_name = %event_name))
)]
#[inline(always)]
pub fn window_event_listener_untyped(
event_name: &str,
cb: impl Fn(web_sys::Event) + 'static,
) -> WindowListenerHandle {
#[cfg(debug_assertions)]
let cb = move |e| {
let _z = SpecialNonReactiveZone::enter();
cb(e);
};
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
#[cfg(feature = "tracing")]
let cb = move |e| {
let _guard = span.enter();
cb(e);
};
if !is_server() {
#[inline(never)]
fn wel(
cb: Box<dyn FnMut(web_sys::Event)>,
event_name: &str,
) -> WindowListenerHandle {
let cb = Closure::wrap(cb).into_js_value();
_ = window().add_event_listener_with_callback(
event_name,
cb.unchecked_ref(),
);
let event_name = event_name.to_string();
let cb = SendWrapper::new(cb);
WindowListenerHandle(Box::new(move || {
_ = window().remove_event_listener_with_callback(
&event_name,
cb.unchecked_ref(),
);
}))
}
wel(Box::new(cb), event_name)
} else {
WindowListenerHandle(Box::new(|| ()))
}
}
/// Creates a window event listener from a typed event, returning a
/// cancelable handle.
/// ```
/// use leptos::{
/// ev, leptos_dom::helpers::window_event_listener, logging::log,
/// prelude::*,
/// };
///
/// #[component]
/// fn App() -> impl IntoView {
/// let handle = window_event_listener(ev::keypress, |ev| {
/// // ev is typed as KeyboardEvent automatically,
/// // so .code() can be called
/// let code = ev.code();
/// log!("code = {code:?}");
/// });
/// on_cleanup(move || handle.remove());
/// }
/// ```
///
/// ### Note about Context
///
/// The callback is called outside of the reactive ownership tree. This means that it does not have access to context via [`use_context`](reactive_graph::owner::use_context). If you want to use context inside the callback, you should either call `use_context` in the body of the component, and move the value into the callback, or access the current owner inside the component body using [`Owner::current`](reactive_graph::owner::Owner::current) and reestablish it in the callback with [`Owner::with`](reactive_graph::owner::Owner::with).
pub fn window_event_listener<E: EventDescriptor + 'static>(
event: E,
cb: impl Fn(E::EventType) + 'static,
) -> WindowListenerHandle
where
E::EventType: JsCast,
{
window_event_listener_untyped(&event.name(), move |e| {
cb(e.unchecked_into::<E::EventType>())
})
}
/// A handle that can be called to remove a global event listener.
pub struct WindowListenerHandle(Box<dyn FnOnce() + Send + Sync>);
impl core::fmt::Debug for WindowListenerHandle {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("WindowListenerHandle").finish()
}
}
impl WindowListenerHandle {
/// Removes the event listener.
pub fn remove(self) {
(self.0)()
}
}
/// Returns `true` if the current environment is a server.
pub fn is_server() -> bool {
#[cfg(feature = "hydration")]
{
Owner::current_shared_context()
.map(|sc| !sc.is_browser())
.unwrap_or(false)
}
#[cfg(not(feature = "hydration"))]
{
false
}
}
/// Returns `true` if the current environment is a browser.
pub fn is_browser() -> bool {
!is_server()
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/src/logging.rs | leptos_dom/src/logging.rs | //! Utilities for simple isomorphic logging to the console or terminal.
use wasm_bindgen::JsValue;
/// Uses `println!()`-style formatting to log something to the console (in the browser)
/// or via `println!()` (if not in the browser).
#[macro_export]
macro_rules! log {
($($t:tt)*) => ($crate::logging::console_log(&format_args!($($t)*).to_string()))
}
/// Uses `println!()`-style formatting to log warnings to the console (in the browser)
/// or via `eprintln!()` (if not in the browser).
#[macro_export]
macro_rules! warn {
($($t:tt)*) => ($crate::logging::console_warn(&format_args!($($t)*).to_string()))
}
/// Uses `println!()`-style formatting to log errors to the console (in the browser)
/// or via `eprintln!()` (if not in the browser).
#[macro_export]
macro_rules! error {
($($t:tt)*) => ($crate::logging::console_error(&format_args!($($t)*).to_string()))
}
/// Uses `println!()`-style formatting to log something to the console (in the browser)
/// or via `println!()` (if not in the browser), but only if it's a debug build.
#[macro_export]
macro_rules! debug_log {
($($x:tt)*) => {
{
if cfg!(debug_assertions) {
$crate::log!($($x)*)
}
}
}
}
/// Uses `println!()`-style formatting to log warnings to the console (in the browser)
/// or via `eprintln!()` (if not in the browser), but only if it's a debug build.
#[macro_export]
macro_rules! debug_warn {
($($x:tt)*) => {
{
if cfg!(debug_assertions) {
$crate::warn!($($x)*)
}
}
}
}
/// Uses `println!()`-style formatting to log errors to the console (in the browser)
/// or via `eprintln!()` (if not in the browser), but only if it's a debug build.
#[macro_export]
macro_rules! debug_error {
($($x:tt)*) => {
{
if cfg!(debug_assertions) {
$crate::error!($($x)*)
}
}
}
}
const fn log_to_stdout() -> bool {
cfg!(not(all(
target_arch = "wasm32",
not(any(target_os = "emscripten", target_os = "wasi"))
)))
}
/// Log a string to the console (in the browser)
/// or via `println!()` (if not in the browser).
pub fn console_log(s: &str) {
#[allow(clippy::print_stdout)]
if log_to_stdout() {
println!("{s}");
} else {
web_sys::console::log_1(&JsValue::from_str(s));
}
}
/// Log a warning to the console (in the browser)
/// or via `eprintln!()` (if not in the browser).
pub fn console_warn(s: &str) {
if log_to_stdout() {
eprintln!("{s}");
} else {
web_sys::console::warn_1(&JsValue::from_str(s));
}
}
/// Log an error to the console (in the browser)
/// or via `eprintln!()` (if not in the browser).
#[inline(always)]
pub fn console_error(s: &str) {
if log_to_stdout() {
eprintln!("{s}");
} else {
web_sys::console::error_1(&JsValue::from_str(s));
}
}
/// Log a string to the console (in the browser)
/// or via `println!()` (if not in the browser), but only in a debug build.
#[inline(always)]
pub fn console_debug_log(s: &str) {
if cfg!(debug_assertions) {
console_log(s)
}
}
/// Log a warning to the console (in the browser)
/// or via `eprintln!()` (if not in the browser), but only in a debug build.
#[inline(always)]
pub fn console_debug_warn(s: &str) {
if cfg!(debug_assertions) {
console_warn(s)
}
}
/// Log an error to the console (in the browser)
/// or via `eprintln!()` (if not in the browser), but only in a debug build.
#[inline(always)]
pub fn console_debug_error(s: &str) {
if cfg!(debug_assertions) {
console_error(s)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/src/macro_helpers/mod.rs | leptos_dom/src/macro_helpers/mod.rs | #[cfg(feature = "trace-component-props")]
#[doc(hidden)]
pub mod tracing_property;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/src/macro_helpers/tracing_property.rs | leptos_dom/src/macro_helpers/tracing_property.rs | use wasm_bindgen::UnwrapThrowExt;
#[macro_export]
/// Use for tracing property
macro_rules! tracing_props {
() => {
::leptos::tracing::span!(
::leptos::tracing::Level::TRACE,
"leptos_dom::tracing_props",
props = String::from("[]")
);
};
($($prop:tt),+ $(,)?) => {
{
use ::leptos::leptos_dom::macro_helpers::tracing_property::{Match, SerializeMatch, DefaultMatch};
let mut props = String::from('[');
$(
let prop = (&&Match {
name: stringify!{$prop},
value: std::cell::Cell::new(Some(&$prop))
}).spez();
props.push_str(&format!("{prop},"));
)*
props.pop();
props.push(']');
::leptos::tracing::span!(
::leptos::tracing::Level::TRACE,
"leptos_dom::tracing_props",
props
);
}
};
}
// Implementation based on spez
// see https://github.com/m-ou-se/spez
pub struct Match<T> {
pub name: &'static str,
pub value: std::cell::Cell<Option<T>>,
}
pub trait SerializeMatch {
type Return;
fn spez(&self) -> Self::Return;
}
impl<T: serde::Serialize> SerializeMatch for &Match<&T> {
type Return = String;
fn spez(&self) -> Self::Return {
let name = self.name;
// suppresses warnings when serializing signals into props
#[cfg(debug_assertions)]
let _z = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
serde_json::to_string(self.value.get().unwrap_throw()).map_or_else(
|err| format!(r#"{{"name": "{name}", "error": "{err}"}}"#),
|value| format!(r#"{{"name": "{name}", "value": {value}}}"#),
)
}
}
pub trait DefaultMatch {
type Return;
fn spez(&self) -> Self::Return;
}
impl<T> DefaultMatch for Match<&T> {
type Return = String;
fn spez(&self) -> Self::Return {
let name = self.name;
format!(r#"{{"name": "{name}", "value": "[unserializable value]"}}"#)
}
}
#[test]
fn match_primitive() {
// String
let test = String::from("string");
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(prop, r#"{"name": "test", "value": "string"}"#);
// &str
let test = "string";
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(prop, r#"{"name": "test", "value": "string"}"#);
// u128
let test: u128 = 1;
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(prop, r#"{"name": "test", "value": 1}"#);
// i128
let test: i128 = -1;
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(prop, r#"{"name": "test", "value": -1}"#);
// f64
let test = 3.25;
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(prop, r#"{"name": "test", "value": 3.25}"#);
// bool
let test = true;
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(prop, r#"{"name": "test", "value": true}"#);
}
#[test]
fn match_serialize() {
use serde::Serialize;
#[derive(Serialize)]
struct CustomStruct {
field: &'static str,
}
let test = CustomStruct { field: "field" };
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(prop, r#"{"name": "test", "value": {"field":"field"}}"#);
// Verification of ownership
assert_eq!(test.field, "field");
}
#[test]
#[allow(clippy::needless_borrow)]
fn match_no_serialize() {
struct CustomStruct {
field: &'static str,
}
let test = CustomStruct { field: "field" };
let prop = (&&Match {
name: stringify! {test},
value: std::cell::Cell::new(Some(&test)),
})
.spez();
assert_eq!(
prop,
r#"{"name": "test", "value": "[unserializable value]"}"#
);
// Verification of ownership
assert_eq!(test.field, "field");
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/examples/test-bench/src/main.rs | leptos_dom/examples/test-bench/src/main.rs | #![feature(iter_intersperse)]
#![allow(warnings)]
#[macro_use]
extern crate tracing;
use leptos::prelude::*;
use tracing::field::debug;
use tracing_subscriber::util::SubscriberInitExt;
fn main() {
console_error_panic_hook::set_once();
tracing_subscriber::fmt()
.with_max_level(tracing::Level::TRACE)
.without_time()
.with_file(true)
.with_line_number(true)
.with_target(false)
.with_writer(tracing_subscriber_wasm::MakeConsoleWriter::default())
.with_ansi(false)
.pretty()
.finish()
.init();
mount_to_body(view_fn);
}
fn view_fn() -> impl IntoView {
view! {
<h2>"Passing Tests"</h2>
<ul>
<Test from=[1] to=[]/>
<Test from=[1, 2] to=[3, 2] then=vec![2]/>
<Test from=[1, 2] to=[]/>
<Test from=[1, 2, 3] to=[]/>
<hr/>
<Test from=[] to=[1]/>
<Test from=[1, 2] to=[1]/>
<Test from=[2, 1] to=[1]/>
<hr/>
<Test from=[1, 2, 3] to=[1, 2]/>
<Test from=[2] to=[1, 2]/>
<Test from=[1] to=[1, 2]/>
<Test from=[] to=[1, 2, 3]/>
<Test from=[2] to=[1, 2, 3]/>
<Test from=[1] to=[1, 2, 3]/>
<Test from=[1, 3, 2] to=[1, 2, 3]/>
<Test from=[2, 1, 3] to=[1, 2, 3]/>
<Test from=[3] to=[1, 2, 3]/>
<Test from=[3, 1] to=[1, 2, 3]/>
<Test from=[3, 2, 1] to=[1, 2, 3]/>
<hr/>
<Test from=[1, 4, 2, 3] to=[1, 2, 3, 4]/>
<hr/>
<Test from=[1, 4, 3, 2, 5] to=[1, 2, 3, 4, 5]/>
<Test from=[4, 5, 3, 1, 2] to=[1, 2, 3, 4, 5]/>
</ul>
}
}
#[component]
fn Test<From, To>(
from: From,
to: To,
#[prop(optional)] then: Option<Vec<usize>>,
) -> impl IntoView
where
From: IntoIterator<Item = usize>,
To: IntoIterator<Item = usize>,
{
let from = from.into_iter().collect::<Vec<_>>();
let to = to.into_iter().collect::<Vec<_>>();
let (list, set_list) = create_signal(from.clone());
request_animation_frame({
let to = to.clone();
let then = then.clone();
move || {
set_list(to);
if let Some(then) = then {
request_animation_frame({
move || {
set_list(then);
}
});
}
}
});
view! {
<li>
"from: [" {move || {
from
.iter()
.map(ToString::to_string)
.intersperse(", ".to_string())
.collect::<String>()
}} "]" <br/> "to: [" {
let then = then.clone();
move || {
then
.clone()
.unwrap_or(to.iter().copied().collect())
.iter()
.map(ToString::to_string)
.intersperse(", ".to_string())
.collect::<String>()
}
} "]" <br/> "result: ["
<For
each=list
key=|i| *i
view=|i| {
view! { <span>{i} ", "</span> }
}
/> "]"
</li>
}
}
// fn view_fn(cx: Scope) -> impl IntoView {
// let (should_show_a, sett_should_show_a) = create_signal(cx, true);
// let a = vec![2];
// let b = vec![1, 2, 3];
// view! { cx,
// <button on:click=move |_| sett_should_show_a.update(|show| *show = !*show)>"Toggle"</button>
// <For
// each={move || if should_show_a.get() {
// a.clone()
// } else {
// b.clone()
// }}
// key=|i| *i
// view=|cx, i| view! { cx, <h1>{i}</h1> }
// />
// }
// }
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/examples/hydration-test/src/lib.rs | leptos_dom/examples/hydration-test/src/lib.rs | #![allow(warnings)]
use leptos::prelude::*;
#[component]
pub fn App() -> impl IntoView {
let pending_thing = create_resource(
|| false,
|_| async {
if cfg!(feature = "ssr") {
let (tx, rx) = futures::channel::oneshot::channel();
spawn_local(async {
std::thread::sleep(std::time::Duration::from_millis(10));
tx.send(());
});
rx.await;
} else {
}
true
},
);
view! {
<div>
<div>
"This is some text"
</div>
// <Suspense fallback=move || view! { <p>"Loading..."</p> }>
{move || pending_thing.read().map(|n| view! { <ComponentA/> })}
// </Suspense>
</div>
}
}
#[component]
pub fn ComponentA() -> impl IntoView {
let (value, set_value) = create_signal("Hello?".to_string());
let (counter, set_counter) = create_signal(0);
// Test to make sure hydration isn't broken by
// something like this
//let _ = [div()].into_view();
div()
.id("the-div")
.child(
input()
.attr("type", "text")
.prop("value", (value))
.on(ev::input, move |e| set_value(event_target_value(&e))),
)
.child(input().attr("type", "text").prop("value", value))
.child(p().child("Value: ").child(value))
.into_view()
}
#[cfg(feature = "hydrate")]
use wasm_bindgen::prelude::wasm_bindgen;
#[cfg(feature = "hydrate")]
#[wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
gloo::console::debug!("starting WASM");
leptos::mount_to_body(move || {
view! { <App/> }
});
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/examples/hydration-test/src/main.rs | leptos_dom/examples/hydration-test/src/main.rs | use actix_files::Files;
use actix_web::*;
use futures::StreamExt;
use hydration_test::*;
use leptos::prelude::*;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new()
.service(Files::new("/pkg", "./pkg"))
.route("/", web::get().to(
|| async {
let pkg_path = "/pkg/hydration_test";
let head = format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="modulepreload" href="{pkg_path}.js">
<link rel="preload" href="{pkg_path}_bg.wasm" as="fetch" type="application/wasm" crossorigin="">
<script type="module">import init, {{ hydrate }} from '{pkg_path}.js'; init('{pkg_path}_bg.wasm').then(hydrate);</script>
</head>
<body>"#
);
let tail = "</body></html>";
HttpResponse::Ok().content_type("text/html").streaming(
futures::stream::once(async move { head.clone() })
.chain(render_to_stream(
|| view! { <App/> }.into_view(),
))
.chain(futures::stream::once(async { tail.to_string() }))
.inspect(|html| println!("{html}"))
.map(|html| Ok(web::Bytes::from(html)) as Result<web::Bytes>),
)})
))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos_dom/examples/view-tests/src/main.rs | leptos_dom/examples/view-tests/src/main.rs | use leptos::prelude::*;
pub fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(|| view! { <Tests/> })
}
#[component]
fn SelfUpdatingEffect() -> Element {
let (a, set_a) = create_signal(false);
create_effect(move |_| {
if !a() {
set_a(true);
}
});
view! {
<h1>"Hello " {move || a().to_string()}</h1>
}
}
#[component]
fn Tests() -> Element {
view! {
<div>
<div><SelfUpdatingEffect/></div>
<div><BlockOrders/></div>
//<div><TemplateConsumer/></div>
</div>
}
}
#[component]
fn BlockOrders() -> Element {
let a = "A";
let b = "B";
let c = "C";
view! {
<div>
<div>"A"</div>
<div>{a}</div>
<div><span>"A"</span></div>
<div><span>{a}</span></div>
<hr/>
<div>"A" {b}</div>
<div>{a} "B"</div>
<div>{a} {b}</div>
<div>{"A"} {"B"}</div>
<div><span style="color: red">{a}</span> {b}</div>
<hr/>
<div>{a} "B" {c}</div>
<div>"A" {b} "C"</div>
<div>{a} {b} "C"</div>
<div>{a} {b} {c}</div>
<div>"A" {b} {c}</div>
<hr/>
<div>"A" {b} <span style="color: red">"C"</span></div>
<div>"A" {b} <span style="color: red">{c}</span></div>
<div>"A" <span style="color: red">"B"</span> "C"</div>
<div>"A" <span style="color: red">"B"</span> {c}</div>
<div>{a} <span style="color: red">{b}</span> {c}</div>
<div>"A" {b} <span style="color: red">{c}</span></div>
<div><span style="color: red">"A"</span> {b} {c}</div>
<div><span style="color: red">{a}</span> "B" {c}</div>
<div><span style="color: red">"A"</span> {b} "C"</div>
<hr/>
<div><span style="color: red">"A"</span> <span style="color: blue">{b}</span> {c}</div>
<div><span style="color: red">{a}</span> "B" <span style="color: blue">{c}</span></div>
<div><span style="color: red">"A"</span> {b} <span style="color: blue">"C"</span></div>
<hr/>
<div><A/></div>
<div>"A" <B/></div>
<div>{a} <B/></div>
<div><A/> "B"</div>
<div><A/> {b}</div>
<div><A/><B/></div>
<hr/>
<div><A/> "B" <C/></div>
<div><A/> {b} <C/></div>
<div><A/> {b} "C"</div>
</div>
}
}
#[component]
fn A() -> Element {
view! { <span style="color: red">"A"</span> }
}
#[component]
fn B() -> Element {
view! { <span style="color: red">"B"</span> }
}
#[component]
fn C() -> Element {
view! { <span style="color: red">"C"</span> }
}
#[component]
fn TemplateConsumer() -> Element {
let tpl = view! { <TemplateExample/> };
let cloned_tpl = tpl
.unchecked_ref::<web_sys::HtmlTemplateElement>()
.content()
.clone_node_with_deep(true)
.expect("couldn't clone template node");
view! {
<div id="template">
/* <h1>"Template Consumer"</h1>
{cloned_tpl} */
</div>
}
}
#[component]
fn TemplateExample() -> Element {
view! {
<template>
<div>"Template contents"</div>
</template>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/app.rs | examples/regression/src/app.rs | use crate::{
issue_4005::Routes4005, issue_4088::Routes4088, issue_4217::Routes4217,
issue_4285::Routes4285, issue_4296::Routes4296, issue_4324::Routes4324,
issue_4492::Routes4492, pr_4015::Routes4015, pr_4091::Routes4091,
};
use leptos::prelude::*;
use leptos_meta::{MetaTags, *};
use leptos_router::{
components::{Route, Router, Routes},
path,
};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone()/>
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
let fallback = || view! { "Page not found." }.into_view();
let (_, set_is_routing) = signal(false);
view! {
<Stylesheet id="leptos" href="/pkg/regression.css"/>
<Router set_is_routing>
<main>
<Routes fallback>
<Route path=path!("") view=HomePage/>
<Routes4091/>
<Routes4015/>
<Routes4088/>
<Routes4217/>
<Routes4005/>
<Routes4285/>
<Routes4296/>
<Routes4324/>
<Routes4492/>
</Routes>
</main>
</Router>
}
}
#[server]
async fn server_call() -> Result<(), ServerFnError> {
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
Ok(())
}
#[component]
fn HomePage() -> impl IntoView {
view! {
<Title text="Regression Tests"/>
<h1>"Listing of regression tests"</h1>
<nav>
<ul>
<li><a href="/4091/">"4091"</a></li>
<li><a href="/4015/">"4015"</a></li>
<li><a href="/4088/">"4088"</a></li>
<li><a href="/4217/">"4217"</a></li>
<li><a href="/4005/">"4005"</a></li>
<li><a href="/4285/">"4285"</a></li>
<li><a href="/4296/">"4296"</a></li>
<li><a href="/4324/">"4324"</a></li>
<li><a href="/4492/">"4492"</a></li>
</ul>
</nav>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/pr_4015.rs | examples/regression/src/pr_4015.rs | use leptos::{context::Provider, prelude::*};
use leptos_router::{
components::{ParentRoute, Route},
nested_router::Outlet,
path,
};
#[component]
pub fn Routes4015() -> impl leptos_router::MatchNestedRoutes + Clone {
view! {
<ParentRoute path=path!("4015") view=|| view! {
<Provider value=42i32>
<Outlet/>
</Provider>
}>
<Route path=path!("") view=Child/>
</ParentRoute>
}
.into_inner()
}
#[component]
fn Child() -> impl IntoView {
let value = use_context::<i32>();
view! {
<p id="result">{format!("{value:?}")}</p>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/issue_4005.rs | examples/regression/src/issue_4005.rs | use leptos::prelude::*;
#[allow(unused_imports)]
use leptos_router::{
components::Route, path, MatchNestedRoutes, NavigateOptions,
};
#[component]
pub fn Routes4005() -> impl MatchNestedRoutes + Clone {
view! {
<Route path=path!("4005") view=Issue4005/>
}
.into_inner()
}
#[component]
fn Issue4005() -> impl IntoView {
view! {
<select id="select" prop:value="2">
<option value="1">"Option 1"</option>
<option value="2">"Option 2"</option>
<option value="3">"Option 3"</option>
</select>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/lib.rs | examples/regression/src/lib.rs | pub mod app;
mod issue_4005;
mod issue_4088;
mod issue_4217;
mod issue_4285;
mod issue_4296;
mod issue_4324;
mod issue_4492;
mod pr_4015;
mod pr_4091;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use app::*;
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/issue_4324.rs | examples/regression/src/issue_4324.rs | use leptos::prelude::*;
#[allow(unused_imports)]
use leptos_router::{
components::Route, path, Lazy, MatchNestedRoutes, NavigateOptions,
};
#[component]
pub fn Routes4324() -> impl MatchNestedRoutes + Clone {
view! {
<Route path=path!("4324") view=Issue4324/>
}
.into_inner()
}
#[component]
pub fn Issue4324() -> impl IntoView {
view! {
<a href="/4324/">"This page"</a>
<p id="result">"Issue4324"</p>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/issue_4088.rs | examples/regression/src/issue_4088.rs | use leptos::{either::Either, prelude::*};
#[allow(unused_imports)]
use leptos_router::{
components::{Outlet, ParentRoute, Redirect, Route},
path, MatchNestedRoutes, NavigateOptions,
};
use serde::{Deserialize, Serialize};
#[component]
pub fn Routes4088() -> impl MatchNestedRoutes + Clone {
view! {
<ParentRoute path=path!("4088") view=|| view!{ <LoggedIn/> }>
<ParentRoute path=path!("") view=||view!{<AssignmentsSelector/>}>
<Route path=path!("/:team_id") view=||view!{<AssignmentsForTeam/>} />
<Route path=path!("") view=||view!{ <p>No class selected</p> }/>
</ParentRoute>
</ParentRoute>
}
.into_inner()
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserInfo {
pub id: usize,
}
#[server]
pub async fn get_user_info() -> Result<Option<UserInfo>, ServerFnError> {
Ok(Some(UserInfo { id: 42 }))
}
#[component]
pub fn LoggedIn() -> impl IntoView {
let user_info_resource =
Resource::new(|| (), move |_| async { get_user_info().await });
view! {
<Transition fallback=move || view!{
"loading"
}
>
{move || {
user_info_resource.get()
.map(|a|
match a {
Ok(Some(a)) => Either::Left(view! {
<LoggedInContent user_info={a} />
}),
_ => Either::Right(view!{
<Redirect path="/not_logged_in"/>
})
})
}}
</Transition>
}
}
#[component]
/// Component which provides UserInfo and renders it's child
/// Can also contain some code to check for specific situations (e.g. privacy policies accepted or not? redirect if needed...)
pub fn LoggedInContent(user_info: UserInfo) -> impl IntoView {
provide_context(user_info.clone());
if user_info.id == 42 {
Either::Left(Outlet())
} else {
Either::Right(
view! { <Redirect path="/somewhere" options={NavigateOptions::default()}/> },
)
}
}
#[component]
/// This component also uses Outlet (so nested Outlet)
fn AssignmentsSelector() -> impl IntoView {
let user_info = use_context::<UserInfo>().expect("user info not provided");
view! {
<p>"Assignments for user with ID: "{user_info.id}</p>
<ul id="nav">
<li><a href="/4088/1">"Class 1"</a></li>
<li><a href="/4088/2">"Class 2"</a></li>
<li><a href="/4088/3">"Class 3"</a></li>
</ul>
<Outlet />
}
}
#[component]
fn AssignmentsForTeam() -> impl IntoView {
// THIS FAILS -> Because of the nested outlet in LoggedInContent > AssignmentsSelector?
// It did not fail when LoggedIn did not use a resource and transition (but a hardcoded UserInfo in the component)
let user_info = use_context::<UserInfo>().expect("user info not provided");
let items = vec!["Assignment 1", "Assignment 2", "Assignment 3"];
view! {
<p id="result">"Assignments for team of user with id " {user_info.id}</p>
<ul>
{
items.into_iter().map(|item| {
view! {
<Assignment name=item.to_string() />
}
}).collect_view()
}
</ul>
}
}
#[component]
fn Assignment(name: String) -> impl IntoView {
let user_info = use_context::<UserInfo>().expect("user info not provided");
view! {
<li>{name}" "{user_info.id}</li>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/issue_4217.rs | examples/regression/src/issue_4217.rs | use leptos::prelude::*;
#[allow(unused_imports)]
use leptos_router::{
components::Route, path, MatchNestedRoutes, NavigateOptions,
};
#[component]
pub fn Routes4217() -> impl MatchNestedRoutes + Clone {
view! {
<Route path=path!("4217") view=Issue4217/>
}
.into_inner()
}
#[component]
fn Issue4217() -> impl IntoView {
view! {
<select multiple=true>
<option id="option1" value="1" selected>"Option 1"</option>
<option id="option2" value="2" selected>"Option 2"</option>
<option id="option3" value="3" selected>"Option 3"</option>
</select>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/issue_4285.rs | examples/regression/src/issue_4285.rs | use leptos::prelude::*;
use leptos_router::LazyRoute;
#[allow(unused_imports)]
use leptos_router::{
components::Route, path, Lazy, MatchNestedRoutes, NavigateOptions,
};
#[component]
pub fn Routes4285() -> impl MatchNestedRoutes + Clone {
view! {
<Route path=path!("4285") view={Lazy::<Issue4285>::new()}/>
}
.into_inner()
}
struct Issue4285 {
data: Resource<Result<i32, ServerFnError>>,
}
impl LazyRoute for Issue4285 {
fn data() -> Self {
Self {
data: Resource::new(|| (), |_| slow_call()),
}
}
async fn view(this: Self) -> AnyView {
let Issue4285 { data } = this;
view! {
<Suspense>
{move || {
Suspend::new(async move {
let data = data.await;
view! {
<p id="result">{data}</p>
}
})
}}
</Suspense>
}
.into_any()
}
}
#[server]
async fn slow_call() -> Result<i32, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
Ok(42)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/issue_4492.rs | examples/regression/src/issue_4492.rs | use leptos::prelude::*;
#[allow(unused_imports)]
use leptos_router::{
components::Route, path, MatchNestedRoutes, NavigateOptions,
};
#[component]
pub fn Routes4492() -> impl MatchNestedRoutes + Clone {
view! {
<Route path=path!("4492") view=Issue4492/>
}
.into_inner()
}
#[component]
fn Issue4492() -> impl IntoView {
let show_a = RwSignal::new(false);
let show_b = RwSignal::new(false);
let show_c = RwSignal::new(false);
view! {
<button id="a-toggle" on:click=move |_| show_a.set(!show_a.get())>"Toggle A"</button>
<button id="b-toggle" on:click=move |_| show_b.set(!show_b.get())>"Toggle B"</button>
<button id="c-toggle" on:click=move |_| show_c.set(!show_c.get())>"Toggle C"</button>
<Show when=move || show_a.get()>
<ScenarioA/>
</Show>
<Show when=move || show_b.get()>
<ScenarioB/>
</Show>
<Show when=move || show_c.get()>
<ScenarioC/>
</Show>
}
}
#[component]
fn ScenarioA() -> impl IntoView {
// scenario A: one truly-async resource is read on click
let counter = RwSignal::new(0);
let resource = Resource::new(
move || counter.get(),
|count| async move {
sleep(50).await.unwrap();
count
},
);
view! {
<Transition fallback=|| view! { <p id="a-result">"Loading..."</p> }>
<p id="a-result">{resource}</p>
</Transition>
<button id="a-button" on:click=move |_| *counter.write() += 1>"+1"</button>
}
}
#[component]
fn ScenarioB() -> impl IntoView {
// scenario B: resource immediately available first time, then after 250ms
let counter = RwSignal::new(0);
let resource = Resource::new(
move || counter.get(),
|count| async move {
if count == 0 {
count
} else {
sleep(50).await.unwrap();
count
}
},
);
view! {
<Transition fallback=|| view! { <p id="b-result">"Loading..."</p> }>
<p id="b-result">{resource}</p>
</Transition>
<button id="b-button" on:click=move |_| *counter.write() += 1>"+1"</button>
}
}
#[component]
fn ScenarioC() -> impl IntoView {
// scenario C: not even a resource on the first run, just a value
// see https://github.com/leptos-rs/leptos/issues/3868
let counter = RwSignal::new(0);
let s_res = StoredValue::new(None::<ArcLocalResource<i32>>);
let resource = move || {
let count = counter.get();
if count == 0 {
count
} else {
let r = s_res.get_value().unwrap_or_else(|| {
let res = ArcLocalResource::new(move || async move {
sleep(50).await.unwrap();
count
});
s_res.set_value(Some(res.clone()));
res
});
r.get().unwrap_or(42)
}
};
view! {
<Transition fallback=|| view! { <p id="c-result">"Loading..."</p> }>
<p id="c-result">{resource}</p>
</Transition>
<button id="c-button" on:click=move |_| *counter.write() += 1>"+1"</button>
}
}
#[server]
async fn sleep(ms: u64) -> Result<(), ServerFnError> {
tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/main.rs | examples/regression/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use regression::app::{shell, App};
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes(&leptos_options, routes, {
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
})
.fallback(leptos_axum::file_and_error_handler(shell))
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
println!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/issue_4296.rs | examples/regression/src/issue_4296.rs | use leptos::prelude::*;
#[allow(unused_imports)]
use leptos_router::{
components::Route, path, Lazy, MatchNestedRoutes, NavigateOptions,
};
use leptos_router::{hooks::use_query_map, LazyRoute};
#[component]
pub fn Routes4296() -> impl MatchNestedRoutes + Clone {
view! {
<Route path=path!("4296") view={Lazy::<Issue4296>::new()}/>
}
.into_inner()
}
struct Issue4296 {
query: Signal<Option<String>>,
}
impl LazyRoute for Issue4296 {
fn data() -> Self {
let query = use_query_map();
let query = Signal::derive(move || query.read().get("q"));
Self { query }
}
async fn view(this: Self) -> AnyView {
let Issue4296 { query } = this;
view! {
<a href="?q=abc">"abc"</a>
<a href="?q=def">"def"</a>
<p id="result">{move || format!("{:?}", query.get())}</p>
}
.into_any()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/src/pr_4091.rs | examples/regression/src/pr_4091.rs | use leptos::{context::Provider, prelude::*};
use leptos_router::{
components::{ParentRoute, Route, A},
nested_router::Outlet,
path,
};
// FIXME This should be a set rather than a naive vec for push and pop, as
// it may be possible for unexpected token be popped/pushed on multi-level
// navigation. For basic naive tests it should be Fine(TM).
#[derive(Clone)]
struct Expectations(Vec<&'static str>);
#[component]
pub fn Routes4091() -> impl leptos_router::MatchNestedRoutes + Clone {
view! {
<ParentRoute path=path!("4091") view=Container>
<Route path=path!("") view=Root/>
<Route path=path!("test1") view=Test1/>
</ParentRoute>
}
.into_inner()
}
#[component]
fn Container() -> impl IntoView {
let rw_signal = RwSignal::new(Expectations(Vec::new()));
provide_context(rw_signal);
view! {
<nav id="nav">
<ul>
<li><A href="/">"Home"</A></li>
<li><A href="./">"4091 Home"</A></li>
<li><A href="test1">"test1"</A></li>
</ul>
</nav>
<div id="result">{move || {
rw_signal.with(|ex| ex.0.iter().fold(String::new(), |a, b| a + b + " "))
}}</div>
<Provider value=rw_signal>
<Outlet/>
</Provider>
}
}
#[component]
fn Root() -> impl IntoView {
view! {
<div>"This is Root"</div>
}
}
#[component]
fn Test1() -> impl IntoView {
let signal = expect_context::<RwSignal<Expectations>>();
on_cleanup(move || {
signal.update(|ex| {
ex.0.pop();
});
});
view! {
{move || signal.update(|ex| ex.0.push("Test1"))}
<div>"This is Test1"</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/app_suite.rs | examples/regression/e2e/tests/app_suite.rs | mod fixtures;
use anyhow::Result;
use cucumber::World;
use fixtures::world::AppWorld;
use std::{ffi::OsStr, fs::read_dir};
#[tokio::main]
async fn main() -> Result<()> {
// Normally the below is done, but it's now gotten to the point of
// having a sufficient number of tests where the resource contention
// of the concurrently running browsers will cause failures on CI.
// AppWorld::cucumber()
// .fail_on_skipped()
// .run_and_exit("./features")
// .await;
// Mitigate the issue by manually stepping through each feature,
// rather than letting cucumber glob them and dispatch all at once.
for entry in read_dir("./features")? {
let path = entry?.path();
if path.extension() == Some(OsStr::new("feature")) {
AppWorld::cucumber()
.fail_on_skipped()
.run_and_exit(path)
.await;
}
}
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/fixtures/check.rs | examples/regression/e2e/tests/fixtures/check.rs | use crate::fixtures::find;
use anyhow::{Ok, Result};
use fantoccini::Client;
use pretty_assertions::assert_eq;
pub async fn result_text_is(
client: &Client,
expected_text: &str,
) -> Result<()> {
element_text_is(client, "result", expected_text).await
}
pub async fn element_text_is(
client: &Client,
id: &str,
expected_text: &str,
) -> Result<()> {
let actual = find::text_at_id(client, id).await?;
assert_eq!(&actual, expected_text);
Ok(())
}
pub async fn element_exists(client: &Client, id: &str) -> Result<()> {
find::element_by_id(client, id)
.await
.expect(&format!("could not find element with id `{id}`"));
Ok(())
}
pub async fn select_option_is_selected(
client: &Client,
id: &str,
) -> Result<()> {
let el = find::element_by_id(client, id)
.await
.expect(&format!("could not find element with id `{id}`"));
let selected = el.prop("selected").await?;
assert_eq!(selected.as_deref(), Some("true"));
Ok(())
}
pub async fn element_value_is(
client: &Client,
id: &str,
expected: &str,
) -> Result<()> {
let el = find::element_by_id(client, id)
.await
.expect(&format!("could not find element with id `{id}`"));
let value = el.prop("value").await?;
assert_eq!(value.as_deref(), Some(expected));
Ok(())
}
pub async fn path_is(client: &Client, expected_path: &str) -> Result<()> {
let url = client
.current_url()
.await
.expect("could not access current URL");
let path = url.path();
assert_eq!(expected_path, path);
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/fixtures/find.rs | examples/regression/e2e/tests/fixtures/find.rs | use anyhow::{Ok, Result};
use fantoccini::{elements::Element, Client, Locator};
pub async fn text_at_id(client: &Client, id: &str) -> Result<String> {
let element = element_by_id(client, id)
.await
.expect(format!("no such element with id `{}`", id).as_str());
let text = element.text().await?;
Ok(text)
}
pub async fn link_with_text(client: &Client, text: &str) -> Result<Element> {
let link = client
.wait()
.for_element(Locator::LinkText(text))
.await
.expect(format!("Link not found by `{}`", text).as_str());
Ok(link)
}
pub async fn element_by_id(client: &Client, id: &str) -> Result<Element> {
Ok(client.wait().for_element(Locator::Id(id)).await?)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/fixtures/mod.rs | examples/regression/e2e/tests/fixtures/mod.rs | pub mod action;
pub mod check;
pub mod find;
pub mod world;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/fixtures/action.rs | examples/regression/e2e/tests/fixtures/action.rs | use super::{find, world::HOST};
use anyhow::Result;
use fantoccini::Client;
use std::result::Result::Ok;
pub async fn goto_path(client: &Client, path: &str) -> Result<()> {
let url = format!("{}{}", HOST, path);
client.goto(&url).await?;
Ok(())
}
pub async fn click_link(client: &Client, text: &str) -> Result<()> {
let link = find::link_with_text(&client, &text).await?;
link.click().await?;
Ok(())
}
pub async fn click_button(client: &Client, id: &str) -> Result<()> {
let btn = find::element_by_id(&client, &id).await?;
btn.click().await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/fixtures/world/check_steps.rs | examples/regression/e2e/tests/fixtures/world/check_steps.rs | use crate::fixtures::{check, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::then;
#[then(regex = r"^I see the result is empty$")]
async fn i_see_the_result_is_empty(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
check::result_text_is(client, "").await?;
Ok(())
}
#[then(regex = r"^I see the result is the string (.*)$")]
async fn i_see_the_result_is_the_string(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::result_text_is(client, &text).await?;
Ok(())
}
#[then(regex = r"^I see ([\w-]+) has the text (.*)$")]
async fn i_see_element_has_text(
world: &mut AppWorld,
id: String,
text: String,
) -> Result<()> {
let client = &world.client;
check::element_text_is(client, &id, &text).await?;
Ok(())
}
#[then(regex = r"^I see the navbar$")]
async fn i_see_the_navbar(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
check::element_exists(client, "nav").await?;
Ok(())
}
#[then(regex = r"^I see ([\d\w]+) is selected$")]
async fn i_see_the_select(world: &mut AppWorld, id: String) -> Result<()> {
let client = &world.client;
check::select_option_is_selected(client, &id).await?;
Ok(())
}
#[then(regex = r"^I see the value of (\w+) is (.*)$")]
async fn i_see_the_value(
world: &mut AppWorld,
id: String,
value: String,
) -> Result<()> {
let client = &world.client;
check::element_value_is(client, &id, &value).await?;
Ok(())
}
#[then(regex = r"^I see the path is (.*)$")]
async fn i_see_the_path(world: &mut AppWorld, path: String) -> Result<()> {
let client = &world.client;
check::path_is(client, &path).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/fixtures/world/action_steps.rs | examples/regression/e2e/tests/fixtures/world/action_steps.rs | use crate::fixtures::{action, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::{gherkin::Step, given, when};
#[given("I see the app")]
#[when("I open the app")]
async fn i_open_the_app(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::goto_path(client, "").await?;
Ok(())
}
#[given(regex = "^I can access regression test (.*)$")]
#[when(regex = "^I select the link (.*)$")]
async fn i_select_the_link(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::click_link(client, &text).await?;
Ok(())
}
#[when(regex = "^I click the button (.*)$")]
async fn i_click_the_button(world: &mut AppWorld, id: String) -> Result<()> {
let client = &world.client;
action::click_button(client, &id).await?;
Ok(())
}
#[given(expr = "I select the following links")]
#[when(expr = "I select the following links")]
async fn i_select_the_following_links(
world: &mut AppWorld,
step: &Step,
) -> Result<()> {
let client = &world.client;
if let Some(table) = step.table.as_ref() {
for row in table.rows.iter() {
action::click_link(client, &row[0]).await?;
}
}
Ok(())
}
#[given(regex = "^I (refresh|reload) the (browser|page)$")]
#[when(regex = "^I (refresh|reload) the (browser|page)$")]
async fn i_refresh_the_browser(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
client.refresh().await?;
Ok(())
}
#[given(regex = "^I press the back button$")]
#[when(regex = "^I press the back button$")]
async fn i_go_back(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
client.back().await?;
Ok(())
}
#[when(regex = r"^I wait (\d+)ms$")]
async fn i_wait_ms(_world: &mut AppWorld, ms: u64) -> Result<()> {
tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/regression/e2e/tests/fixtures/world/mod.rs | examples/regression/e2e/tests/fixtures/world/mod.rs | pub mod action_steps;
pub mod check_steps;
use anyhow::Result;
use cucumber::World;
use fantoccini::{
error::NewSessionError, wd::Capabilities, Client, ClientBuilder,
};
pub const HOST: &str = "http://127.0.0.1:3000";
#[derive(Debug, World)]
#[world(init = Self::new)]
pub struct AppWorld {
pub client: Client,
}
impl AppWorld {
async fn new() -> Result<Self, anyhow::Error> {
let webdriver_client = build_client().await?;
Ok(Self {
client: webdriver_client,
})
}
}
async fn build_client() -> Result<Client, NewSessionError> {
let mut cap = Capabilities::new();
let arg = serde_json::from_str("{\"args\": [\"-headless\"]}").unwrap();
cap.insert("goog:chromeOptions".to_string(), arg);
let client = ClientBuilder::native()
.capabilities(cap)
.connect("http://localhost:4444")
.await?;
Ok(client)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/parent_child/src/lib.rs | examples/parent_child/src/lib.rs | use leptos::prelude::*;
use web_sys::MouseEvent;
// This highlights four different ways that child components can communicate
// with their parent:
// 1) <ButtonA/>: passing a WriteSignal as one of the child component props,
// for the child component to write into and the parent to read
// 2) <ButtonB/>: passing a closure as one of the child component props, for
// the child component to call
// 3) <ButtonC/>: adding an `on:` event listener to a component
// 4) <ButtonD/>: providing a context that is used in the component (rather than prop drilling)
#[derive(Copy, Clone)]
struct SmallcapsContext(WriteSignal<bool>);
#[component]
pub fn App() -> impl IntoView {
// just some signals to toggle three classes on our <p>
let (red, set_red) = signal(false);
let (right, set_right) = signal(false);
let (italics, set_italics) = signal(false);
let (smallcaps, set_smallcaps) = signal(false);
// the newtype pattern isn't *necessary* here but is a good practice
// it avoids confusion with other possible future `WriteSignal<bool>` contexts
// and makes it easier to refer to it in ButtonC
provide_context(SmallcapsContext(set_smallcaps));
view! {
<main>
<p
// class: attributes take F: Fn() => bool, and these signals all implement Fn()
class:red=red
class:right=right
class:italics=italics
class:smallcaps=smallcaps
>
"Lorem ipsum sit dolor amet."
</p>
// Button A: pass the signal setter
<ButtonA setter=set_red/>
// Button B: pass a closure
<ButtonB on_click=move |_| set_right.update(|value| *value = !*value)/>
// Button C: use a regular event listener
// setting an event listener on a component like this applies it
// to each of the top-level elements the component returns
<ButtonC on:click=move |_| set_italics.update(|value| *value = !*value)/>
// Button D gets its setter from context rather than props
<ButtonD/>
</main>
}
}
/// Button A receives a signal setter and updates the signal itself
#[component]
pub fn ButtonA(
/// Signal that will be toggled when the button is clicked.
setter: WriteSignal<bool>,
) -> impl IntoView {
view! { <button on:click=move |_| setter.update(|value| *value = !*value)>"Toggle Red"</button> }
}
/// Button B receives a closure
#[component]
pub fn ButtonB(
/// Callback that will be invoked when the button is clicked.
on_click: impl FnMut(MouseEvent) + 'static,
) -> impl IntoView {
view! { <button on:click=on_click>"Toggle Right"</button> }
}
/// Button C is a dummy: it renders a button but doesn't handle
/// its click. Instead, the parent component adds an event listener.
#[component]
pub fn ButtonC() -> impl IntoView {
view! { <button>"Toggle Italics"</button> }
}
/// Button D is very similar to Button A, but instead of passing the setter as a prop
/// we get it from the context
#[component]
pub fn ButtonD() -> impl IntoView {
let setter = use_context::<SmallcapsContext>().unwrap().0;
view! {
<button on:click=move |_| {
setter.update(|value| *value = !*value)
}>"Toggle Small Caps"</button>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/parent_child/src/main.rs | examples/parent_child/src/main.rs | use leptos::prelude::*;
use parent_child::*;
pub fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
mount_to_body(App)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_url_query/src/lib.rs | examples/counter_url_query/src/lib.rs | use leptos::prelude::*;
use leptos_router::hooks::query_signal;
/// A simple counter component.
///
/// You can use doc comments like this to document your component.
#[component]
pub fn SimpleQueryCounter() -> impl IntoView {
let (count, set_count) = query_signal::<i32>("count");
let clear = move |_| set_count.set(None);
let decrement = move |_| set_count.set(Some(count.get().unwrap_or(0) - 1));
let increment = move |_| set_count.set(Some(count.get().unwrap_or(0) + 1));
let (msg, set_msg) = query_signal::<String>("message");
let update_msg = move |ev| {
let new_msg = event_target_value(&ev);
if new_msg.is_empty() {
set_msg.set(None);
} else {
set_msg.set(Some(new_msg));
}
};
view! {
<div>
<button on:click=clear>"Clear"</button>
<button on:click=decrement>"-1"</button>
<span>"Value: " {move || count.get().unwrap_or(0)} "!"</span>
<button on:click=increment>"+1"</button>
<br />
<input
prop:value=move || msg.get().unwrap_or_default()
on:input=update_msg
/>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counter_url_query/src/main.rs | examples/counter_url_query/src/main.rs | use counter_url_query::SimpleQueryCounter;
use leptos::prelude::*;
use leptos_router::components::Router;
pub fn main() {
console_error_panic_hook::set_once();
leptos::mount::mount_to_body(|| {
view! {
<Router>
<SimpleQueryCounter/>
</Router>
}
})
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/slots/src/lib.rs | examples/slots/src/lib.rs | use leptos::prelude::*;
// Slots are created in similar manner to components, except that they use the #[slot] macro.
#[slot]
struct Then {
children: ChildrenFn,
}
// Props work just like component props, for example, you can specify a prop as optional by prefixing
// the type with Option<...> and marking the option as #[prop(optional)].
#[slot]
struct ElseIf {
cond: Signal<bool>,
children: ChildrenFn,
}
#[slot]
struct Fallback {
children: ChildrenFn,
}
// Slots are added to components like any other prop.
#[component]
fn SlotIf(
cond: Signal<bool>,
then: Then,
#[prop(default=vec![])] else_if: Vec<ElseIf>,
#[prop(optional)] fallback: Option<Fallback>,
) -> impl IntoView {
move || {
if cond.get() {
(then.children)().into_any()
} else if let Some(else_if) = else_if.iter().find(|i| i.cond.get()) {
(else_if.children)().into_any()
} else if let Some(fallback) = &fallback {
(fallback.children)().into_any()
} else {
().into_any()
}
}
}
#[component]
pub fn App() -> impl IntoView {
let (count, set_count) = signal(0);
let is_even = Signal::derive(move || count.get() % 2 == 0);
let is_div5 = Signal::derive(move || count.get() % 5 == 0);
let is_div7 = Signal::derive(move || count.get() % 7 == 0);
view! {
<button on:click=move |_| set_count.update(|value| *value += 1)>"+1"</button>
" "{count}" is "
<SlotIf cond=is_even>
// The slot name can be emitted if it would match the slot struct name (in snake case).
<Then slot>"even"</Then>
// Props are passed just like on normal components.
<ElseIf slot cond=is_div5>"divisible by 5"</ElseIf>
<ElseIf slot cond=is_div7>"divisible by 7"</ElseIf>
<Fallback slot>"odd"</Fallback>
</SlotIf>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/slots/src/main.rs | examples/slots/src/main.rs | use slots::App;
pub fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
leptos::mount::mount_to_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/src/app.rs | examples/lazy_routes/src/app.rs | use leptos::{prelude::*, task::spawn_local};
use leptos_router::{
components::{Outlet, ParentRoute, Route, Router, Routes},
lazy_route, Lazy, LazyRoute, StaticSegment,
};
use serde::{Deserialize, Serialize};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone()/>
<HydrationScripts options/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
let count = RwSignal::new(0);
provide_context(count);
let (is_routing, set_is_routing) = signal(false);
view! {
<nav id="nav" style="width: 100%">
<a href="/">"A"</a> " | "
<a href="/b">"B"</a> " | "
<a href="/c">"C"</a> " | "
<a href="/d">"D"</a>
<span style="float: right" id="navigating">
{move || is_routing.get().then_some("Navigating...")}
</span>
</nav>
<Router set_is_routing>
<Routes fallback=|| "Not found.">
<Route path=StaticSegment("") view=ViewA/>
<Route path=StaticSegment("b") view=ViewB/>
<Route path=StaticSegment("c") view={Lazy::<ViewC>::new()}/>
// you can nest lazy routes, and there data and views will all load concurrently
<ParentRoute path=StaticSegment("d") view={Lazy::<ViewD>::new()}>
<Route path=StaticSegment("") view={Lazy::<ViewE>::new()}/>
</ParentRoute>
</Routes>
</Router>
}
}
// View A: A plain old synchronous route, just like they all currently work. The WASM binary code
// for this is shipped as part of the main bundle. Any data-loading code (like resources that run
// in the body of the component) will be shipped as part of the main bundle.
#[component]
pub fn ViewA() -> impl IntoView {
leptos::logging::log!("View A");
let result = RwSignal::new("Click a button to see the result".to_string());
view! {
<p id="page">"View A"</p>
<pre id="result">{result}</pre>
<button id="First" on:click=move |_| spawn_local(async move { result.set(first_value().await); })>"First"</button>
<button id="Second" on:click=move |_| spawn_local(async move { result.set(second_value().await); })>"Second"</button>
// test to make sure duplicate names in different scopes can be used
<button id="Third" on:click=move |_| {
#[lazy]
pub fn second_value() -> String {
"Third value.".to_string()
}
spawn_local(async move {
result.set(second_value().await);
});
}>"Third"</button>
}
}
// View B: lazy-loaded route with lazy-loaded data
#[derive(Debug, Clone, Deserialize)]
pub struct Comment {
#[serde(rename = "postId")]
post_id: usize,
id: usize,
name: String,
email: String,
body: String,
}
#[lazy]
fn deserialize_comments(data: &str) -> Vec<Comment> {
serde_json::from_str(data).unwrap()
}
#[component]
pub fn ViewB() -> impl IntoView {
let data = LocalResource::new(|| async move {
let preload = deserialize_comments("[]");
let (_, data) = futures::future::join(preload, async {
gloo_timers::future::TimeoutFuture::new(500).await;
r#"
[
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "Eliseo@gardner.biz",
"body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "Jayne_Kuhic@sydney.com",
"body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
},
{
"postId": 1,
"id": 3,
"name": "odio adipisci rerum aut animi",
"email": "Nikita@garfield.biz",
"body": "quia molestiae reprehenderit quasi aspernatur\naut expedita occaecati aliquam eveniet laudantium\nomnis quibusdam delectus saepe quia accusamus maiores nam est\ncum et ducimus et vero voluptates excepturi deleniti ratione"
}
]
"#
})
.await;
deserialize_comments(data).await
});
view! {
<p id="page">"View B"</p>
<Suspense fallback=|| view! { <p id="loading">"Loading..."</p> }>
<ul>
{move || Suspend::new(async move {
let items = data.await;
items.into_iter()
.map(|comment| view! {
<li id=format!("{}-{}", comment.post_id, comment.id)>
<strong>{comment.name}</strong> " (by " {comment.email} ")"<br/>
{comment.body}
</li>
})
.collect_view()
})}
</ul>
</Suspense>
}
.into_any()
}
#[derive(Debug, Clone, Deserialize)]
pub struct Album {
#[serde(rename = "userId")]
user_id: usize,
id: usize,
title: String,
}
// View C: a lazy view, and some data, loaded in parallel when we navigate to /c.
#[derive(Clone)]
pub struct ViewC {
data: LocalResource<Vec<Album>>,
}
// Lazy-loaded routes need to implement the LazyRoute trait. They define a "route data" struct,
// which is created with `::data()`, and then a separate view function which is lazily loaded.
//
// This is important because it allows us to concurrently 1) load the route data, and 2) lazily
// load the component, rather than creating a "waterfall" where we can't start loading the route
// data until we've received the view.
//
// The `#[lazy_route]` macro makes `view` into a lazy-loaded inner function, replacing `self` with
// `this`.
#[lazy_route]
impl LazyRoute for ViewC {
fn data() -> Self {
// the data method itself is synchronous: it typically creates things like Resources,
// which are created synchronously but spawn an async data-loading task
// if you want further code-splitting, however, you can create a lazy function to load the data!
#[lazy]
async fn lazy_data() -> Vec<Album> {
gloo_timers::future::TimeoutFuture::new(250).await;
vec![
Album {
user_id: 1,
id: 1,
title: "quidem molestiae enim".into(),
},
Album {
user_id: 1,
id: 2,
title: "sunt qui excepturi placeat culpa".into(),
},
Album {
user_id: 1,
id: 3,
title: "omnis laborum odio".into(),
},
]
}
Self {
data: LocalResource::new(lazy_data),
}
}
fn view(this: Self) -> AnyView {
let albums = move || {
Suspend::new(async move {
this.data
.await
.into_iter()
.map(|album| {
view! {
<li id=format!("{}-{}", album.user_id, album.id)>
{album.title}
</li>
}
})
.collect::<Vec<_>>()
})
};
view! {
<p id="page">"View C"</p>
<hr/>
<Suspense fallback=|| view! { <p id="loading">"Loading..."</p> }>
<ul>{albums}</ul>
</Suspense>
}
.into_any()
}
}
// When two functions have shared code, that shared code will be split out automatically
// into an additional file. For example, the shared serde code here will be split into a single file,
// and then loaded lazily once when the first of the two functions is called
#[lazy]
pub fn first_value() -> String {
#[derive(Serialize)]
struct FirstValue {
a: String,
b: i32,
}
serde_json::to_string(&FirstValue {
a: "First Value".into(),
b: 1,
})
.unwrap()
}
#[lazy]
pub fn second_value() -> String {
#[derive(Serialize)]
struct SecondValue {
a: String,
b: i32,
}
serde_json::to_string(&SecondValue {
a: "Second Value".into(),
b: 2,
})
.unwrap()
}
struct ViewD {
data: Resource<Result<Vec<i32>, ServerFnError>>,
}
#[lazy_route]
impl LazyRoute for ViewD {
fn data() -> Self {
Self {
data: Resource::new(|| (), |_| d_data()),
}
}
fn view(this: Self) -> AnyView {
let items = move || {
Suspend::new(async move {
this.data
.await
.unwrap_or_default()
.into_iter()
.map(|item| view! { <li>{item}</li> })
.collect::<Vec<_>>()
})
};
view! {
<p id="page">"View D"</p>
<hr/>
<Suspense fallback=|| view! { <p id="loading">"Loading..."</p> }>
<ul>{items}</ul>
</Suspense>
<Outlet/>
}
.into_any()
}
}
// Server functions can be made lazy by combining the two macros,
// with `#[server]` coming first, then `#[lazy]`
#[server]
#[lazy]
async fn d_data() -> Result<Vec<i32>, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
Ok(vec![1, 1, 2, 3, 5, 8, 13])
}
struct ViewE {
data: Resource<Result<Vec<String>, ServerFnError>>,
}
#[lazy_route]
impl LazyRoute for ViewE {
fn data() -> Self {
Self {
data: Resource::new(|| (), |_| e_data()),
}
}
fn view(this: Self) -> AnyView {
let items = move || {
Suspend::new(async move {
this.data
.await
.unwrap_or_default()
.into_iter()
.map(|item| view! { <li>{item}</li> })
.collect::<Vec<_>>()
})
};
view! {
<p id="page">"View E"</p>
<hr/>
<Suspense fallback=|| view! { <p id="loading">"Loading..."</p> }>
<ul>{items}</ul>
</Suspense>
}
.into_any()
}
}
#[server]
async fn e_data() -> Result<Vec<String>, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
Ok(vec!["foo".into(), "bar".into(), "baz".into()])
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/src/lib.rs | examples/lazy_routes/src/lib.rs | pub mod app;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use app::*;
console_error_panic_hook::set_once();
leptos::mount::hydrate_lazy(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/src/main.rs | examples/lazy_routes/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use lazy_routes::app::{shell, App};
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes(&leptos_options, routes, {
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
})
.fallback(leptos_axum::file_and_error_handler(shell))
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
println!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/app_suite.rs | examples/lazy_routes/e2e/tests/app_suite.rs | mod fixtures;
use anyhow::Result;
use cucumber::World;
use fixtures::world::AppWorld;
use std::{ffi::OsStr, fs::read_dir};
#[tokio::main]
async fn main() -> Result<()> {
// Normally the below is done, but it's now gotten to the point of
// having a sufficient number of tests where the resource contention
// of the concurrently running browsers will cause failures on CI.
// AppWorld::cucumber()
// .fail_on_skipped()
// .run_and_exit("./features")
// .await;
// Mitigate the issue by manually stepping through each feature,
// rather than letting cucumber glob them and dispatch all at once.
for entry in read_dir("./features")? {
let path = entry?.path();
if path.extension() == Some(OsStr::new("feature")) {
AppWorld::cucumber()
.fail_on_skipped()
.run_and_exit(path)
.await;
}
}
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/fixtures/check.rs | examples/lazy_routes/e2e/tests/fixtures/check.rs | use crate::fixtures::find;
use anyhow::{Ok, Result};
use fantoccini::Client;
use pretty_assertions::assert_eq;
pub async fn page_name_is(client: &Client, expected_text: &str) -> Result<()> {
let actual = find::text_at_id(client, "page").await?;
assert_eq!(&actual, expected_text);
Ok(())
}
pub async fn result_is(client: &Client, expected_text: &str) -> Result<()> {
let actual = find::text_at_id(client, "result").await?;
assert_eq!(&actual, expected_text);
Ok(())
}
pub async fn navigating_appears(client: &Client) -> Result<()> {
let actual = find::text_at_id(client, "navigating").await?;
assert_eq!(&actual, "Navigating...");
Ok(())
}
pub async fn element_exists(client: &Client, id: &str) -> Result<()> {
find::element_by_id(client, id)
.await
.expect(&format!("could not find element with id `{id}`"));
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/fixtures/find.rs | examples/lazy_routes/e2e/tests/fixtures/find.rs | use anyhow::{Ok, Result};
use fantoccini::{elements::Element, Client, Locator};
pub async fn text_at_id(client: &Client, id: &str) -> Result<String> {
let element = element_by_id(client, id)
.await
.expect(format!("no such element with id `{}`", id).as_str());
let text = element.text().await?;
Ok(text)
}
pub async fn link_with_text(client: &Client, text: &str) -> Result<Element> {
let link = client
.wait()
.for_element(Locator::LinkText(text))
.await
.expect(format!("Link not found by `{}`", text).as_str());
Ok(link)
}
pub async fn element_by_id(client: &Client, id: &str) -> Result<Element> {
Ok(client.wait().for_element(Locator::Id(id)).await?)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/fixtures/mod.rs | examples/lazy_routes/e2e/tests/fixtures/mod.rs | pub mod action;
pub mod check;
pub mod find;
pub mod world;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/fixtures/action.rs | examples/lazy_routes/e2e/tests/fixtures/action.rs | use super::{find, world::HOST};
use anyhow::Result;
use fantoccini::Client;
use std::result::Result::Ok;
pub async fn goto_path(client: &Client, path: &str) -> Result<()> {
let url = format!("{}{}", HOST, path);
client.goto(&url).await?;
Ok(())
}
pub async fn click_link(client: &Client, text: &str) -> Result<()> {
let link = find::link_with_text(&client, &text).await?;
link.click().await?;
Ok(())
}
pub async fn click_button(client: &Client, id: &str) -> Result<()> {
let btn = find::element_by_id(&client, &id).await?;
btn.click().await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/fixtures/world/check_steps.rs | examples/lazy_routes/e2e/tests/fixtures/world/check_steps.rs | use crate::fixtures::{check, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::then;
#[then(regex = r"^I see the navigating indicator")]
async fn i_see_the_nav(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
check::navigating_appears(client).await?;
Ok(())
}
#[then(regex = r"^I see the page is (.*)$")]
async fn i_see_the_page_is(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
check::page_name_is(client, &text).await?;
Ok(())
}
#[then(regex = r"^I see the result is (.*)$")]
async fn i_see_the_result_is(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
check::result_is(client, &text).await?;
Ok(())
}
#[then(regex = r"^I see the navbar$")]
async fn i_see_the_navbar(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
check::element_exists(client, "nav").await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/fixtures/world/action_steps.rs | examples/lazy_routes/e2e/tests/fixtures/world/action_steps.rs | use crate::fixtures::{action, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::{gherkin::Step, given, when};
#[given("I see the app")]
#[when("I open the app")]
async fn i_open_the_app(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::goto_path(client, "").await?;
Ok(())
}
#[when(regex = "^I open the app at (.*)$")]
async fn i_open_the_app_at(world: &mut AppWorld, url: String) -> Result<()> {
let client = &world.client;
action::goto_path(client, &url).await?;
Ok(())
}
#[when(regex = "^I select the link (.*)$")]
async fn i_select_the_link(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::click_link(client, &text).await?;
Ok(())
}
#[when(regex = "^I click the button (.*)$")]
async fn i_click_the_button(world: &mut AppWorld, id: String) -> Result<()> {
let client = &world.client;
action::click_button(client, &id).await?;
Ok(())
}
#[when(expr = "I select the following links")]
async fn i_select_the_following_links(
world: &mut AppWorld,
step: &Step,
) -> Result<()> {
let client = &world.client;
if let Some(table) = step.table.as_ref() {
for row in table.rows.iter() {
action::click_link(client, &row[0]).await?;
}
}
Ok(())
}
#[when("I wait for a second")]
async fn i_wait_for_a_second(world: &mut AppWorld) -> Result<()> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(())
}
#[given(regex = "^I (refresh|reload) the (browser|page)$")]
#[when(regex = "^I (refresh|reload) the (browser|page)$")]
async fn i_refresh_the_browser(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
client.refresh().await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/lazy_routes/e2e/tests/fixtures/world/mod.rs | examples/lazy_routes/e2e/tests/fixtures/world/mod.rs | pub mod action_steps;
pub mod check_steps;
use anyhow::Result;
use cucumber::World;
use fantoccini::{
error::NewSessionError, wd::Capabilities, Client, ClientBuilder,
};
pub const HOST: &str = "http://127.0.0.1:3000";
#[derive(Debug, World)]
#[world(init = Self::new)]
pub struct AppWorld {
pub client: Client,
}
impl AppWorld {
async fn new() -> Result<Self, anyhow::Error> {
let webdriver_client = build_client().await?;
Ok(Self {
client: webdriver_client,
})
}
}
async fn build_client() -> Result<Client, NewSessionError> {
let mut cap = Capabilities::new();
let arg = serde_json::from_str("{\"args\": [\"-headless\"]}").unwrap();
cap.insert("goog:chromeOptions".to_string(), arg);
let client = ClientBuilder::native()
.capabilities(cap)
.connect("http://localhost:4444")
.await?;
Ok(client)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_axum/src/app.rs | examples/tailwind_axum/src/app.rs | use leptos::prelude::*;
use leptos_meta::*;
use leptos_router::{
components::{FlatRoutes, Route, Router},
StaticSegment,
};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone() />
<HydrationScripts options/>
<link rel="stylesheet" id="leptos" href="/pkg/leptos_tailwind.css"/>
<link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
view! {
<Router>
<FlatRoutes fallback=|| "Page not found.">
<Route path=StaticSegment("") view=Home/>
</FlatRoutes>
</Router>
}
}
#[component]
fn Home() -> impl IntoView {
let (value, set_value) = signal(0);
// thanks to https://tailwindcomponents.com/component/blue-buttons-example for the showcase layout
view! {
<Title text="Leptos + Tailwindcss"/>
<main>
<div class="bg-gradient-to-tl from-blue-800 to-blue-500 text-white font-mono flex flex-col min-h-screen">
<div class="flex flex-row-reverse flex-wrap m-auto">
<button on:click=move |_| set_value.update(|value| *value += 1) class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white">
"+"
</button>
<button class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-800 border-blue-900 text-white">
{value}
</button>
<button
on:click=move |_| set_value.update(|value| *value -= 1)
class="rounded px-3 py-2 m-1 border-b-4 border-l-2 shadow-lg bg-blue-700 border-blue-800 text-white"
class:invisible=move || {value.get() < 1}
>
"-"
</button>
</div>
</div>
</main>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_axum/src/lib.rs | examples/tailwind_axum/src/lib.rs | pub mod app;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::App;
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/tailwind_axum/src/main.rs | examples/tailwind_axum/src/main.rs | use axum::Router;
use leptos::prelude::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use leptos_tailwind::app::{shell, App};
#[tokio::main]
async fn main() {
// Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
// build our application with a route
let app = Router::new()
.leptos_routes(&leptos_options, routes, {
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
})
.fallback(leptos_axum::file_and_error_handler(shell))
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
println!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for a purely client-side app
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/src/errors.rs | examples/todo_app_sqlite_csr/src/errors.rs | use http::status::StatusCode;
use thiserror::Error;
#[derive(Debug, Clone, Error)]
pub enum TodoAppError {
#[error("Not Found")]
NotFound,
#[error("Internal Server Error")]
InternalServerError,
}
impl TodoAppError {
pub fn status_code(&self) -> StatusCode {
match self {
TodoAppError::NotFound => StatusCode::NOT_FOUND,
TodoAppError::InternalServerError => {
StatusCode::INTERNAL_SERVER_ERROR
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/src/lib.rs | examples/todo_app_sqlite_csr/src/lib.rs | pub mod error_template;
pub mod errors;
#[cfg(feature = "ssr")]
pub mod fallback;
pub mod todo;
#[cfg_attr(feature = "csr", wasm_bindgen::prelude::wasm_bindgen)]
pub fn hydrate() {
use crate::todo::*;
console_error_panic_hook::set_once();
leptos::mount::mount_to_body(TodoApp);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/src/todo.rs | examples/todo_app_sqlite_csr/src/todo.rs | use crate::error_template::ErrorTemplate;
use leptos::{either::Either, prelude::*};
use serde::{Deserialize, Serialize};
use server_fn::ServerFnError;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
pub struct Todo {
id: u16,
title: String,
completed: bool,
}
#[cfg(feature = "ssr")]
pub mod ssr {
// use http::{header::SET_COOKIE, HeaderMap, HeaderValue, StatusCode};
use leptos::server_fn::ServerFnError;
use sqlx::{Connection, SqliteConnection};
pub async fn db() -> Result<SqliteConnection, ServerFnError> {
Ok(SqliteConnection::connect("sqlite:Todos.db").await?)
}
}
#[server]
pub async fn get_todos() -> Result<Vec<Todo>, ServerFnError> {
use self::ssr::*;
use http::request::Parts;
// this is just an example of how to access server context injected in the handlers
let req_parts = use_context::<Parts>();
if let Some(req_parts) = req_parts {
println!("Uri = {:?}", req_parts.uri);
}
use futures::TryStreamExt;
let mut conn = db().await?;
let mut todos = Vec::new();
let mut rows =
sqlx::query_as::<_, Todo>("SELECT * FROM todos").fetch(&mut conn);
while let Some(row) = rows.try_next().await? {
todos.push(row);
}
// Lines below show how to set status code and headers on the response
// let resp = expect_context::<ResponseOptions>();
// resp.set_status(StatusCode::IM_A_TEAPOT);
// resp.insert_header(SET_COOKIE, HeaderValue::from_str("fizz=buzz").unwrap());
Ok(todos)
}
#[server]
pub async fn add_todo(title: String) -> Result<(), ServerFnError> {
use self::ssr::*;
let mut conn = db().await?;
// fake API delay
std::thread::sleep(std::time::Duration::from_millis(250));
match sqlx::query("INSERT INTO todos (title, completed) VALUES ($1, false)")
.bind(title)
.execute(&mut conn)
.await
{
Ok(_row) => Ok(()),
Err(e) => Err(ServerFnError::ServerError(e.to_string())),
}
}
#[server]
pub async fn delete_todo(id: u16) -> Result<(), ServerFnError> {
use self::ssr::*;
let mut conn = db().await?;
Ok(sqlx::query("DELETE FROM todos WHERE id = $1")
.bind(id)
.execute(&mut conn)
.await
.map(|_| ())?)
}
#[component]
pub fn TodoApp() -> impl IntoView {
view! {
<header>
<h1>"My Tasks"</h1>
</header>
<main>
<Todos/>
</main>
}
}
#[component]
pub fn Todos() -> impl IntoView {
let add_todo = ServerMultiAction::<AddTodo>::new();
let submissions = add_todo.submissions();
let delete_todo = ServerAction::<DeleteTodo>::new();
// list of todos is loaded from the server in reaction to changes
let todos = Resource::new(
move || {
(
delete_todo.version().get(),
add_todo.version().get(),
delete_todo.version().get(),
)
},
move |_| get_todos(),
);
let existing_todos = move || {
Suspend::new(async move {
todos
.await
.map(|todos| {
if todos.is_empty() {
Either::Left(view! { <p>"No tasks were found."</p> })
} else {
Either::Right(
todos
.iter()
.map(move |todo| {
let id = todo.id;
view! {
<li>
{todo.title.clone()}
<ActionForm action=delete_todo>
<input type="hidden" name="id" value=id/>
<input type="submit" value="X"/>
</ActionForm>
</li>
}
})
.collect::<Vec<_>>(),
)
}
})
})
};
view! {
<MultiActionForm action=add_todo>
<label>"Add a Todo" <input type="text" name="title"/></label>
<input type="submit" value="Add"/>
</MultiActionForm>
<div>
<Transition fallback=move || view! { <p>"Loading..."</p> }>
<ErrorBoundary fallback=|errors| view! { <ErrorTemplate errors/> }>
<ul>
{existing_todos}
{move || {
submissions
.get()
.into_iter()
.filter(|submission| submission.pending().get())
.map(|submission| {
view! {
<li class="pending">
{move || submission.input().get().map(|data| data.title)}
</li>
}
})
.collect::<Vec<_>>()
}}
</ul>
</ErrorBoundary>
</Transition>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/src/error_template.rs | examples/todo_app_sqlite_csr/src/error_template.rs | use crate::errors::TodoAppError;
use leptos::prelude::*;
#[cfg(feature = "ssr")]
use leptos_axum::ResponseOptions;
// A basic function to display errors served by the error boundaries. Feel free to do more complicated things
// here than just displaying them
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional, into)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => RwSignal::new(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
// Downcast lets us take a type that implements `std::error::Error`
let errors: Vec<TodoAppError> = errors
.get()
.into_iter()
.filter_map(|(_, v)| v.downcast_ref::<TodoAppError>().cloned())
.collect();
// Only the response code for the first error is actually sent from the server
// this may be customized by the specific application
#[cfg(feature = "ssr")]
{
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<h1>"Errors"</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each= move || {errors.clone().into_iter().enumerate()}
// a unique key for each item as a reference
key=|(index, _error)| *index
// renders each item to a view
children=move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/src/main.rs | examples/todo_app_sqlite_csr/src/main.rs | #[cfg(feature = "ssr")]
#[allow(unused)]
mod ssr_imports {
pub use axum::{
body::Body as AxumBody,
extract::{Path, State},
http::Request,
response::{Html, IntoResponse, Response},
routing::{get, post},
Router,
};
pub use leptos::prelude::*;
pub use leptos_axum::{generate_route_list, LeptosRoutes};
pub use todo_app_sqlite_csr::{
fallback::file_or_index_handler, todo::*, *,
};
}
#[cfg(feature = "ssr")]
#[cfg_attr(feature = "ssr", tokio::main)]
async fn main() {
use ssr_imports::*;
let _conn = ssr::db().await.expect("couldn't connect to DB");
// Setting this to None means we'll be using cargo-leptos and its env vars
let conf = get_configuration(None).unwrap();
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
// build our application with a route
let app = Router::new()
// server function handlers are normally set up by .leptos_routes()
// here, we're not actually doing server side rendering, so we set up a manual
// handler for the server fns
// this should include a get() handler if you have any GetUrl-based server fns
.route("/api/{*fn_name}", post(leptos_axum::handle_server_fns))
.fallback(file_or_index_handler)
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
leptos::logging::log!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr)
.await
.expect("couldn't bind to address");
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// This example cannot be built as a trunk standalone CSR-only app.
// Only the server may directly connect to the database.
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/src/fallback.rs | examples/todo_app_sqlite_csr/src/fallback.rs | use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode, Uri},
response::{Html, IntoResponse, Response as AxumResponse},
};
use leptos::{
config::LeptosOptions,
hydration::{AutoReload, HydrationScripts},
prelude::*,
};
use tower::util::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_or_index_handler(
uri: Uri,
State(options): State<LeptosOptions>,
) -> AxumResponse {
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else {
Html(view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone() />
<HydrationScripts options=options.clone()/>
<link rel="stylesheet" id="leptos" href="/pkg/todo_app_sqlite_csr.css"/>
<link rel="shortcut icon" type="image/ico" href="/favicon.ico"/>
</head>
<body></body>
</html>
}.to_html()).into_response()
}
}
async fn get_static_file(
uri: Uri,
root: &str,
) -> Result<Response<Body>, (StatusCode, String)> {
let req = Request::builder()
.uri(uri.clone())
.body(Body::empty())
.unwrap();
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
// This path is relative to the cargo root
match ServeDir::new(root).oneshot(req).await {
Ok(res) => Ok(res.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/app_suite.rs | examples/todo_app_sqlite_csr/e2e/tests/app_suite.rs | mod fixtures;
use anyhow::Result;
use cucumber::World;
use fixtures::world::AppWorld;
#[tokio::main]
async fn main() -> Result<()> {
AppWorld::cucumber()
.fail_on_skipped()
.run_and_exit("./features")
.await;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/fixtures/check.rs | examples/todo_app_sqlite_csr/e2e/tests/fixtures/check.rs | use super::find;
use anyhow::{Ok, Result};
use fantoccini::{Client, Locator};
use pretty_assertions::assert_eq;
pub async fn text_on_element(
client: &Client,
selector: &str,
expected_text: &str,
) -> Result<()> {
let element = client
.wait()
.for_element(Locator::Css(selector))
.await
.expect(
format!("Element not found by Css selector `{}`", selector)
.as_str(),
);
let actual = element.text().await?;
assert_eq!(&actual, expected_text);
Ok(())
}
pub async fn todo_present(
client: &Client,
text: &str,
expected: bool,
) -> Result<()> {
let todo_present = is_todo_present(client, text).await;
assert_eq!(todo_present, expected);
Ok(())
}
async fn is_todo_present(client: &Client, text: &str) -> bool {
let todos = find::todos(client).await;
for todo in todos {
let todo_title = todo.text().await.expect("Todo title not found");
if todo_title == text {
return true;
}
}
false
}
pub async fn todo_is_pending(client: &Client) -> Result<()> {
if let None = find::pending_todo(client).await {
assert!(false, "Pending todo not found");
}
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/fixtures/find.rs | examples/todo_app_sqlite_csr/e2e/tests/fixtures/find.rs | use fantoccini::{elements::Element, Client, Locator};
pub async fn todo_input(client: &Client) -> Element {
let textbox = client
.wait()
.for_element(Locator::Css("input[name='title"))
.await
.expect("Todo textbox not found");
textbox
}
pub async fn add_button(client: &Client) -> Element {
let button = client
.wait()
.for_element(Locator::Css("input[value='Add']"))
.await
.expect("");
button
}
pub async fn first_delete_button(client: &Client) -> Option<Element> {
if let Ok(element) = client
.wait()
.for_element(Locator::Css("li:first-child input[value='X']"))
.await
{
return Some(element);
}
None
}
pub async fn delete_button(client: &Client, text: &str) -> Option<Element> {
let selector = format!("//*[text()='{text}']//input[@value='X']");
if let Ok(element) =
client.wait().for_element(Locator::XPath(&selector)).await
{
return Some(element);
}
None
}
pub async fn pending_todo(client: &Client) -> Option<Element> {
if let Ok(element) =
client.wait().for_element(Locator::Css(".pending")).await
{
return Some(element);
}
None
}
pub async fn todos(client: &Client) -> Vec<Element> {
let todos = client
.find_all(Locator::Css("li"))
.await
.expect("Todo List not found");
todos
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/fixtures/mod.rs | examples/todo_app_sqlite_csr/e2e/tests/fixtures/mod.rs | pub mod action;
pub mod check;
pub mod find;
pub mod world;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/fixtures/action.rs | examples/todo_app_sqlite_csr/e2e/tests/fixtures/action.rs | use super::{find, world::HOST};
use anyhow::Result;
use fantoccini::Client;
use std::result::Result::Ok;
use tokio::{self, time};
pub async fn goto_path(client: &Client, path: &str) -> Result<()> {
let url = format!("{}{}", HOST, path);
client.goto(&url).await?;
Ok(())
}
pub async fn add_todo(client: &Client, text: &str) -> Result<()> {
fill_todo(client, text).await?;
click_add_button(client).await?;
Ok(())
}
pub async fn fill_todo(client: &Client, text: &str) -> Result<()> {
let textbox = find::todo_input(client).await;
textbox.send_keys(text).await?;
Ok(())
}
pub async fn click_add_button(client: &Client) -> Result<()> {
let add_button = find::add_button(client).await;
add_button.click().await?;
Ok(())
}
pub async fn empty_todo_list(client: &Client) -> Result<()> {
let todos = find::todos(client).await;
for _todo in todos {
let _ = delete_first_todo(client).await?;
}
Ok(())
}
pub async fn delete_first_todo(client: &Client) -> Result<()> {
if let Some(element) = find::first_delete_button(client).await {
element.click().await.expect("Failed to delete todo");
time::sleep(time::Duration::from_millis(250)).await;
}
Ok(())
}
pub async fn delete_todo(client: &Client, text: &str) -> Result<()> {
if let Some(element) = find::delete_button(client, text).await {
element.click().await?;
time::sleep(time::Duration::from_millis(250)).await;
}
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/fixtures/world/check_steps.rs | examples/todo_app_sqlite_csr/e2e/tests/fixtures/world/check_steps.rs | use crate::fixtures::{check, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::then;
#[then(regex = "^I see the page title is (.*)$")]
async fn i_see_the_page_title_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::text_on_element(client, "h1", &text).await?;
Ok(())
}
#[then(regex = "^I see the label of the input is (.*)$")]
async fn i_see_the_label_of_the_input_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::text_on_element(client, "label", &text).await?;
Ok(())
}
#[then(regex = "^I see the todo named (.*)$")]
async fn i_see_the_todo_is_present(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::todo_present(client, text.as_str(), true).await?;
Ok(())
}
#[then("I see the pending todo")]
async fn i_see_the_pending_todo(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
check::todo_is_pending(client).await?;
Ok(())
}
#[then(regex = "^I see the empty list message is (.*)$")]
async fn i_see_the_empty_list_message_is(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::text_on_element(client, "ul p", &text).await?;
Ok(())
}
#[then(regex = "^I do not see the todo named (.*)$")]
async fn i_do_not_see_the_todo_is_present(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
check::todo_present(client, text.as_str(), false).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/fixtures/world/action_steps.rs | examples/todo_app_sqlite_csr/e2e/tests/fixtures/world/action_steps.rs | use crate::fixtures::{action, world::AppWorld};
use anyhow::{Ok, Result};
use cucumber::{given, when};
#[given("I see the app")]
#[when("I open the app")]
async fn i_open_the_app(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::goto_path(client, "").await?;
Ok(())
}
#[given(regex = "^I add a todo as (.*)$")]
#[when(regex = "^I add a todo as (.*)$")]
async fn i_add_a_todo_titled(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::add_todo(client, text.as_str()).await?;
Ok(())
}
#[given(regex = "^I set the todo as (.*)$")]
async fn i_set_the_todo_as(world: &mut AppWorld, text: String) -> Result<()> {
let client = &world.client;
action::fill_todo(client, &text).await?;
Ok(())
}
#[when(regex = "I click the Add button$")]
async fn i_click_the_button(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::click_add_button(client).await?;
Ok(())
}
#[when(regex = "^I delete the todo named (.*)$")]
async fn i_delete_the_todo_named(
world: &mut AppWorld,
text: String,
) -> Result<()> {
let client = &world.client;
action::delete_todo(client, text.as_str()).await?;
Ok(())
}
#[given("the todo list is empty")]
#[when("I empty the todo list")]
async fn i_empty_the_todo_list(world: &mut AppWorld) -> Result<()> {
let client = &world.client;
action::empty_todo_list(client).await?;
Ok(())
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/todo_app_sqlite_csr/e2e/tests/fixtures/world/mod.rs | examples/todo_app_sqlite_csr/e2e/tests/fixtures/world/mod.rs | pub mod action_steps;
pub mod check_steps;
use anyhow::Result;
use cucumber::World;
use fantoccini::{
error::NewSessionError, wd::Capabilities, Client, ClientBuilder,
};
pub const HOST: &str = "http://127.0.0.1:3000";
#[derive(Debug, World)]
#[world(init = Self::new)]
pub struct AppWorld {
pub client: Client,
}
impl AppWorld {
async fn new() -> Result<Self, anyhow::Error> {
let webdriver_client = build_client().await?;
Ok(Self {
client: webdriver_client,
})
}
}
async fn build_client() -> Result<Client, NewSessionError> {
let mut cap = Capabilities::new();
let arg = serde_json::from_str("{\"args\": [\"-headless\"]}").unwrap();
cap.insert("goog:chromeOptions".to_string(), arg);
let client = ClientBuilder::native()
.capabilities(cap)
.connect("http://localhost:4444")
.await?;
Ok(client)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counters/src/lib.rs | examples/counters/src/lib.rs | use leptos::prelude::*;
const MANY_COUNTERS: usize = 1000;
type CounterHolder = Vec<(usize, ArcRwSignal<i32>)>;
#[derive(Copy, Clone)]
struct CounterUpdater {
set_counters: WriteSignal<CounterHolder>,
}
#[component]
pub fn Counters() -> impl IntoView {
let (next_counter_id, set_next_counter_id) = signal(0);
let (counters, set_counters) = signal::<CounterHolder>(vec![]);
provide_context(CounterUpdater { set_counters });
let add_counter = move |_| {
let id = next_counter_id.get();
let sig = ArcRwSignal::new(0);
set_counters.update(move |counters| counters.push((id, sig)));
set_next_counter_id.update(|id| *id += 1);
};
let add_many_counters = move |_| {
let next_id = next_counter_id.get();
let new_counters = (next_id..next_id + MANY_COUNTERS).map(|id| {
let signal = ArcRwSignal::new(0);
(id, signal)
});
set_counters.update(move |counters| counters.extend(new_counters));
set_next_counter_id.update(|id| *id += MANY_COUNTERS);
};
let clear_counters = move |_| {
set_counters.update(|counters| counters.clear());
};
view! {
<div>
<button on:click=add_counter>"Add Counter"</button>
<button on:click=add_many_counters>{format!("Add {MANY_COUNTERS} Counters")}</button>
<button on:click=clear_counters>"Clear Counters"</button>
<p>
"Total: "
<span data-testid="total">
{move || {
counters.get().iter().map(|(_, count)| count.get()).sum::<i32>().to_string()
}}
</span> " from "
<span data-testid="counters">{move || counters.get().len().to_string()}</span>
" counters."
</p>
<ul>
<For
each=move || counters.get()
key=|counter| counter.0
children=move |(id, value)| {
view! { <Counter id value/> }
}
/>
</ul>
</div>
}
}
#[component]
fn Counter(id: usize, value: ArcRwSignal<i32>) -> impl IntoView {
let value = RwSignal::from(value);
let CounterUpdater { set_counters } = use_context().unwrap();
view! {
<li>
<button on:click=move |_| value.update(move |value| *value -= 1)>"-1"</button>
<input
type="text"
prop:value=value
on:input:target=move |ev| {
value.set(ev.target().value().parse::<i32>().unwrap_or_default())
}
/>
<span>{value}</span>
<button on:click=move |_| value.update(move |value| *value += 1)>"+1"</button>
<button on:click=move |_| {
set_counters
.update(move |counters| counters.retain(|(counter_id, _)| counter_id != &id))
}>"x"</button>
</li>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counters/src/main.rs | examples/counters/src/main.rs | use counters::Counters;
fn main() {
console_error_panic_hook::set_once();
leptos::mount::mount_to_body(Counters)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/counters/tests/web.rs | examples/counters/tests/web.rs | #![allow(dead_code)]
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
use counters::Counters;
use leptos::{prelude::*, task::tick};
use web_sys::HtmlElement;
#[wasm_bindgen_test]
async fn inc() {
mount_to_body(Counters);
let document = document();
let div = document.query_selector("div").unwrap().unwrap();
let add_counter = div
.first_child()
.unwrap()
.dyn_into::<HtmlElement>()
.unwrap();
assert_eq!(
div.inner_html(),
"<button>Add Counter</button><button>Add 1000 \
Counters</button><button>Clear Counters</button><p>Total: <span \
data-testid=\"total\">0</span> from <span \
data-testid=\"counters\">0</span> counters.</p><ul><!----></ul>"
);
// add 3 counters
add_counter.click();
add_counter.click();
add_counter.click();
tick().await;
// check HTML
assert_eq!(
div.inner_html(),
"<button>Add Counter</button><button>Add 1000 \
Counters</button><button>Clear Counters</button><p>Total: <span \
data-testid=\"total\">0</span> from <span \
data-testid=\"counters\">3</span> \
counters.</p><ul><li><button>-1</button><input \
type=\"text\"><span>0</span><button>+1</button><button>x</button></\
li><li><button>-1</button><input \
type=\"text\"><span>0</span><button>+1</button><button>x</button></\
li><li><button>-1</button><input \
type=\"text\"><span>0</span><button>+1</button><button>x</button></\
li><!----></ul>"
);
let counters = div
.query_selector("ul")
.unwrap()
.unwrap()
.unchecked_into::<HtmlElement>()
.children();
// click first counter once, second counter twice, etc.
// `NodeList` isn't a `Vec` so we iterate over it in this slightly awkward way
for idx in 0..counters.length() {
let counter = counters.item(idx).unwrap();
let inc_button = counter
.first_child()
.unwrap()
.next_sibling()
.unwrap()
.next_sibling()
.unwrap()
.next_sibling()
.unwrap()
.unchecked_into::<HtmlElement>();
for _ in 0..=idx {
inc_button.click();
}
}
tick().await;
assert_eq!(
div.inner_html(),
"<button>Add Counter</button><button>Add 1000 \
Counters</button><button>Clear Counters</button><p>Total: <span \
data-testid=\"total\">6</span> from <span \
data-testid=\"counters\">3</span> \
counters.</p><ul><li><button>-1</button><input \
type=\"text\"><span>1</span><button>+1</button><button>x</button></\
li><li><button>-1</button><input \
type=\"text\"><span>2</span><button>+1</button><button>x</button></\
li><li><button>-1</button><input \
type=\"text\"><span>3</span><button>+1</button><button>x</button></\
li><!----></ul>"
);
// remove the first counter
counters
.item(0)
.unwrap()
.last_child()
.unwrap()
.unchecked_into::<HtmlElement>()
.click();
tick().await;
assert_eq!(
div.inner_html(),
"<button>Add Counter</button><button>Add 1000 \
Counters</button><button>Clear Counters</button><p>Total: <span \
data-testid=\"total\">5</span> from <span \
data-testid=\"counters\">2</span> \
counters.</p><ul><li><button>-1</button><input \
type=\"text\"><span>2</span><button>+1</button><button>x</button></\
li><li><button>-1</button><input \
type=\"text\"><span>3</span><button>+1</button><button>x</button></\
li><!----></ul>"
);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/portal/src/lib.rs | examples/portal/src/lib.rs | use leptos::{control_flow::Show, portal::Portal, prelude::*};
#[component]
pub fn App() -> impl IntoView {
let (show_overlay, set_show_overlay) = signal(false);
let (show_inside_overlay, set_show_inside_overlay) = signal(false);
view! {
<div>
<button id="btn-show" on:click=move |_| set_show_overlay.set(true)>
"Show Overlay"
</button>
<Show when=move || show_overlay.get() fallback=|| ()>
<div>Show</div>
<Portal mount=document().get_element_by_id("app").unwrap()>
<div style="position: fixed; z-index: 10; width: 100vw; height: 100vh; top: 0; left: 0; background: rgba(0, 0, 0, 0.8); color: white;">
<p>This is in the body element</p>
<button id="btn-hide" on:click=move |_| set_show_overlay.set(false)>
"Close Overlay"
</button>
<button
id="btn-toggle"
on:click=move |_| {
set_show_inside_overlay.set(!show_inside_overlay.get())
}
>
"Toggle inner"
</button>
<Show when=move || show_inside_overlay.get() fallback=|| view! { "Hidden" }>
"Visible"
</Show>
</div>
</Portal>
</Show>
</div>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/portal/src/main.rs | examples/portal/src/main.rs | use leptos::prelude::*;
use portal::App;
use wasm_bindgen::JsCast;
fn main() {
_ = console_log::init_with_level(log::Level::Debug);
console_error_panic_hook::set_once();
let handle = mount_to(
document()
.get_element_by_id("app")
.unwrap()
.unchecked_into(),
App,
);
handle.forget();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/portal/tests/web.rs | examples/portal/tests/web.rs | #![allow(dead_code)]
use leptos::{leptos_dom::helpers::document, mount::mount_to, task::tick};
use portal::App;
use wasm_bindgen::JsCast;
use wasm_bindgen_test::*;
use web_sys::HtmlButtonElement;
wasm_bindgen_test_configure!(run_in_browser);
fn minify(html: &str) -> String {
let mut result = String::with_capacity(html.len());
let mut in_tag = false;
let mut last_char_was_tag_end = false;
let mut whitespace_buffer = String::new();
for c in html.chars() {
match c {
'<' => {
// Starting a new tag
in_tag = true;
last_char_was_tag_end = false;
// Discard any buffered whitespace
whitespace_buffer.clear();
result.push(c);
}
'>' => {
// Ending a tag
in_tag = false;
last_char_was_tag_end = true;
result.push(c);
}
c if c.is_whitespace() => {
if in_tag {
// Preserve whitespace inside tags
result.push(c);
} else if !last_char_was_tag_end {
// Buffer whitespace between content
whitespace_buffer.push(c);
}
// Whitespace immediately after a tag end is ignored
}
_ => {
// Regular character
last_char_was_tag_end = false;
// If we have buffered whitespace and are outputting content,
// preserve a single space
if !whitespace_buffer.is_empty() {
result.push(' ');
whitespace_buffer.clear();
}
result.push(c);
}
}
}
result
}
#[wasm_bindgen_test]
async fn portal() {
let document = document();
let body = document.body().unwrap();
let div = document.create_element("div").unwrap();
div.set_id("app");
let _ = body.append_child(&div);
let _handle = mount_to(div.clone().unchecked_into(), App);
let show_button = document
.get_element_by_id("btn-show")
.unwrap()
.unchecked_into::<HtmlButtonElement>();
show_button.click();
tick().await;
// check HTML
assert_eq!(
minify(div.inner_html().as_str()),
minify(
"<div><button id=\"btn-show\">Show \
Overlay</button><div>Show</div><!----></div><div><div \
style=\"position: fixed; z-index: 10; width: 100vw; height: \
100vh; top: 0; left: 0; background: rgba(0, 0, 0, 0.8); color: \
white;\"><p>This is in the body element</p><button \
id=\"btn-hide\">Close Overlay</button><button \
id=\"btn-toggle\">Toggle inner</button>Hidden</div></div>"
)
);
let toggle_button = document
.get_element_by_id("btn-toggle")
.unwrap()
.unchecked_into::<HtmlButtonElement>();
toggle_button.click();
assert_eq!(
minify(div.inner_html().as_str()),
minify(
"<div><button id=\"btn-show\">Show \
Overlay</button><div>Show</div><!----></div><div><div \
style=\"position: fixed; z-index: 10; width: 100vw; height: \
100vh; top: 0; left: 0; background: rgba(0, 0, 0, 0.8); color: \
white;\"><p>This is in the body element</p><button \
id=\"btn-hide\">Close Overlay</button><button \
id=\"btn-toggle\">Toggle inner</button>Hidden</div></div>"
)
);
let hide_button = document
.get_element_by_id("btn-hide")
.unwrap()
.unchecked_into::<HtmlButtonElement>();
hide_button.click();
assert_eq!(
minify(div.inner_html().as_str()),
minify(
"<div><button id=\"btn-show\">Show \
Overlay</button><div>Show</div><!----></div><div><div \
style=\"position: fixed; z-index: 10; width: 100vw; height: \
100vh; top: 0; left: 0; background: rgba(0, 0, 0, 0.8); color: \
white;\"><p>This is in the body element</p><button \
id=\"btn-hide\">Close Overlay</button><button \
id=\"btn-toggle\">Toggle inner</button>Hidden</div></div>"
)
);
}
#[test]
fn test_minify() {
let input = r#"<div>
<p> Hello world! </p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>"#;
let expected = r#"<div><p>Hello world!</p><ul><li>Item 1</li><li>Item 2</li></ul></div>"#;
assert_eq!(minify(input), expected);
}
#[test]
fn test_preserve_whitespace_in_tags() {
let input = r#"<div class = "container">"#;
let expected = r#"<div class = "container">"#;
assert_eq!(minify(input), expected);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/ssr_modes_axum/src/app.rs | examples/ssr_modes_axum/src/app.rs | use leptos::prelude::*;
use leptos_meta::{MetaTags, *};
use leptos_router::{
components::{FlatRoutes, ProtectedRoute, Route, Router},
hooks::use_params,
params::Params,
ParamSegment, SsrMode, StaticSegment,
};
use serde::{Deserialize, Serialize};
#[cfg(feature = "ssr")]
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::LazyLock;
use thiserror::Error;
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone()/>
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[cfg(feature = "ssr")]
static IS_ADMIN: AtomicBool = AtomicBool::new(true);
#[server]
pub async fn is_admin() -> Result<bool, ServerFnError> {
Ok(IS_ADMIN.load(Ordering::Relaxed))
}
#[server]
pub async fn set_is_admin(is_admin: bool) -> Result<(), ServerFnError> {
IS_ADMIN.store(is_admin, Ordering::Relaxed);
Ok(())
}
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
let fallback = || view! { "Page not found." }.into_view();
let toggle_admin = ServerAction::<SetIsAdmin>::new();
let is_admin =
Resource::new(move || toggle_admin.version().get(), |_| is_admin());
view! {
<Stylesheet id="leptos" href="/pkg/ssr_modes.css"/>
<Title text="Welcome to Leptos"/>
<Meta name="color-scheme" content="dark light"/>
<Router>
<nav>
<a href="/">"Home"</a>
<a href="/admin">"Admin"</a>
<Transition>
<ActionForm action=toggle_admin>
<input
type="hidden"
name="is_admin"
value=move || {
(!is_admin.get().and_then(|n| n.ok()).unwrap_or_default())
.to_string()
}
/>
<button>
{move || {
if is_admin.get().and_then(Result::ok).unwrap_or_default() {
"Log Out"
} else {
"Log In"
}
}}
</button>
</ActionForm>
</Transition>
</nav>
<main>
<FlatRoutes fallback>
// We’ll load the home page with out-of-order streaming and <Suspense/>
<Route path=StaticSegment("") view=HomePage/>
// We'll load the posts with async rendering, so they can set
// the title and metadata *after* loading the data
<Route
path=(StaticSegment("post"), ParamSegment("id"))
view=Post
ssr=SsrMode::Async
/>
<Route
path=(StaticSegment("post_in_order"), ParamSegment("id"))
view=Post
ssr=SsrMode::InOrder
/>
<Route
path=(StaticSegment("post_partially_blocked"), ParamSegment("id"))
view=Post
/>
<ProtectedRoute
path=StaticSegment("admin")
view=Admin
ssr=SsrMode::Async
condition=move || is_admin.get().map(|n| n.unwrap_or(false))
redirect_path=|| "/"
/>
</FlatRoutes>
</main>
</Router>
}
}
#[component]
fn HomePage() -> impl IntoView {
// load the posts
let posts = Resource::new(|| (), |_| list_post_metadata());
let posts = move || {
posts
.get()
.map(|n| n.unwrap_or_default())
.unwrap_or_default()
};
let posts2 = Resource::new(|| (), |_| list_post_metadata());
let posts2 = Resource::new(
|| (),
move |_| async move { posts2.await.as_ref().map(Vec::len).unwrap_or(0) },
);
view! {
<h1>"My Great Blog"</h1>
<Suspense fallback=move || view! { <p>"Loading posts..."</p> }>
<p>"number of posts: " {Suspend::new(async move { posts2.await })}</p>
</Suspense>
<Suspense fallback=move || view! { <p>"Loading posts..."</p> }>
<ul>
<For each=posts key=|post| post.id let:post>
<li>
<a href=format!("/post/{}", post.id)>{post.title.clone()}</a>
"|"
<a href=format!(
"/post_in_order/{}",
post.id,
)>{post.title.clone()} "(in order)"</a>
"|"
<a href=format!(
"/post_partially_blocked/{}",
post.id,
)>{post.title} "(partially blocked)"</a>
</li>
</For>
</ul>
</Suspense>
}
}
#[derive(Params, Copy, Clone, Debug, PartialEq, Eq)]
pub struct PostParams {
id: Option<usize>,
}
#[component]
fn Post() -> impl IntoView {
let query = use_params::<PostParams>();
let id = move || {
query.with(|q| {
q.as_ref()
.map(|q| q.id.unwrap_or_default())
.map_err(|_| PostError::InvalidId)
})
};
let post_resource = Resource::new_blocking(id, |id| async move {
match id {
Err(e) => Err(e),
Ok(id) => get_post(id)
.await
.map(|data| data.ok_or(PostError::PostNotFound))
.map_err(|_| PostError::ServerError),
}
});
let comments_resource = Resource::new(id, |id| async move {
match id {
Err(e) => Err(e),
Ok(id) => {
get_comments(id).await.map_err(|_| PostError::ServerError)
}
}
});
let post_view = Suspend::new(async move {
match post_resource.await {
Ok(Ok(post)) => {
Ok(view! {
<h1>{post.title.clone()}</h1>
<p>{post.content.clone()}</p>
// since we're using async rendering for this page,
// this metadata should be included in the actual HTML <head>
// when it's first served
<Title text=post.title/>
<Meta name="description" content=post.content/>
})
}
_ => Err(PostError::ServerError),
}
});
let comments_view = Suspend::new(async move {
match comments_resource.await {
Ok(comments) => Ok(view! {
<h1>"Comments"</h1>
<ul>
{comments
.into_iter()
.map(|comment| view! { <li>{comment}</li> })
.collect_view()}
</ul>
}),
_ => Err(PostError::ServerError),
}
});
view! {
<em>"The world's best content."</em>
<Suspense fallback=move || view! { <p>"Loading post..."</p> }>
<ErrorBoundary fallback=|errors| {
view! {
<div class="error">
<h1>"Something went wrong."</h1>
<ul>
{move || {
errors
.get()
.into_iter()
.map(|(_, error)| view! { <li>{error.to_string()}</li> })
.collect::<Vec<_>>()
}}
</ul>
</div>
}
}>{post_view}</ErrorBoundary>
</Suspense>
<Suspense fallback=move || view! { <p>"Loading comments..."</p> }>{comments_view}</Suspense>
}
}
#[component]
pub fn Admin() -> impl IntoView {
view! { <p>"You can only see this page if you're logged in."</p> }
}
// Dummy API
static POSTS: LazyLock<[Post; 3]> = LazyLock::new(|| {
[
Post {
id: 0,
title: "My first post".to_string(),
content: "This is my first post".to_string(),
},
Post {
id: 1,
title: "My second post".to_string(),
content: "This is my second post".to_string(),
},
Post {
id: 2,
title: "My third post".to_string(),
content: "This is my third post".to_string(),
},
]
});
#[derive(Error, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PostError {
#[error("Invalid post ID.")]
InvalidId,
#[error("Post not found.")]
PostNotFound,
#[error("Server error.")]
ServerError,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Post {
id: usize,
title: String,
content: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PostMetadata {
id: usize,
title: String,
}
#[server]
pub async fn list_post_metadata() -> Result<Vec<PostMetadata>, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(POSTS
.iter()
.map(|data| PostMetadata {
id: data.id,
title: data.title.clone(),
})
.collect())
}
#[server]
pub async fn get_post(id: usize) -> Result<Option<Post>, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(POSTS.iter().find(|post| post.id == id).cloned())
}
#[server]
pub async fn get_comments(id: usize) -> Result<Vec<String>, ServerFnError> {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
_ = id;
Ok(vec!["Some comment".into(), "Some other comment".into()])
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/ssr_modes_axum/src/lib.rs | examples/ssr_modes_axum/src/lib.rs | pub mod app;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use app::*;
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/ssr_modes_axum/src/main.rs | examples/ssr_modes_axum/src/main.rs | #[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::{
http::{HeaderName, HeaderValue},
Router,
};
use leptos::{logging::log, prelude::*};
use leptos_axum::{generate_route_list, LeptosRoutes};
use ssr_modes_axum::app::*;
let conf = get_configuration(None).unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes(&leptos_options, routes, {
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
})
.fallback(leptos_axum::file_and_error_handler_with_context(
move || {
// if you want to add custom headers to the static file handler response,
// you can do that by providing `ResponseOptions` via context
let opts = use_context::<leptos_axum::ResponseOptions>()
.unwrap_or_default();
opts.insert_header(
HeaderName::from_static("cross-origin-opener-policy"),
HeaderValue::from_static("same-origin"),
);
opts.insert_header(
HeaderName::from_static("cross-origin-embedder-policy"),
HeaderValue::from_static("require-corp"),
);
provide_context(opts);
},
shell,
))
.with_state(leptos_options);
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
log!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/subsecond_hot_patch/src/main.rs | examples/subsecond_hot_patch/src/main.rs | use leptos::{prelude::*, subsecond::connect_to_hot_patch_messages};
use leptos_router::{
components::{Route, Router, Routes},
path,
};
fn main() {
// connect to DX CLI and patch the WASM binary whenever we receive a message
connect_to_hot_patch_messages();
// wrapping App here in a closure so we can hot-reload it, because we only do that
// for reactive views right now. changing anything will re-run App and update the view
mount_to_body(|| App);
}
#[component]
fn App() -> impl IntoView {
view! {
<nav>
<a href="/">"Home"</a>
<a href="/about">"About"</a>
</nav>
<Router>
<Routes fallback=|| "Not found">
<Route path=path!("/") view=HomePage/>
<Route path=path!("/about") view=About/>
</Routes>
</Router>
}
}
#[component]
fn HomePage() -> impl IntoView {
view! {
<h1>"Home Page"</h1>
}
}
#[component]
fn About() -> impl IntoView {
view! {
<h1>"About"</h1>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/lib.rs | examples/hackernews_axum/src/lib.rs | use leptos::prelude::*;
mod api;
mod routes;
use leptos_meta::{provide_meta_context, Link, Meta, MetaTags, Stylesheet};
use leptos_router::{
components::{FlatRoutes, Route, Router, RoutingProgress},
Lazy, OptionalParamSegment, ParamSegment, StaticSegment,
};
use routes::{nav::*, stories::*, story::*, users::*};
use std::time::Duration;
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<AutoReload options=options.clone() />
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
let (is_routing, set_is_routing) = signal(false);
view! {
<Stylesheet id="leptos" href="/pkg/hackernews_axum.css"/>
<Link rel="shortcut icon" type_="image/ico" href="/favicon.ico"/>
<Meta name="description" content="Leptos implementation of a HackerNews demo."/>
<Router set_is_routing>
// shows a progress bar while async data are loading
<div class="routing-progress">
<RoutingProgress is_routing max_time=Duration::from_millis(250)/>
</div>
<Nav />
<main>
<FlatRoutes fallback=|| "Not found.">
<Route path=(StaticSegment("users"), ParamSegment("id")) view={Lazy::<UserRoute>::new()}/>
<Route path=(StaticSegment("stories"), ParamSegment("id")) view={Lazy::<StoryRoute>::new()}/>
<Route path=OptionalParamSegment("stories") view=Stories/>
</FlatRoutes>
</main>
</Router>
}
}
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/handlers.rs | examples/hackernews_axum/src/handlers.rs | use axum::{
body::Body,
http::{Request, Response, StatusCode, Uri},
response::IntoResponse,
};
use tower::ServiceExt;
use tower_http::services::ServeDir;
pub async fn file_handler(
uri: Uri,
) -> Result<Response<Body>, (StatusCode, String)> {
let res = get_static_file(uri.clone(), "/pkg").await?;
if res.status() == StatusCode::NOT_FOUND {
// try with `.html`
// TODO: handle if the Uri has query parameters
match format!("{}.html", uri).parse() {
Ok(uri_html) => get_static_file(uri_html, "/pkg").await,
Err(_) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
"Invalid URI".to_string(),
)),
}
} else {
Ok(res)
}
}
pub async fn get_static_file_handler(
uri: Uri,
) -> Result<Response<Body>, (StatusCode, String)> {
let res = get_static_file(uri.clone(), "/static").await?;
if res.status() == StatusCode::NOT_FOUND {
Err((StatusCode::INTERNAL_SERVER_ERROR, "Invalid URI".to_string()))
} else {
Ok(res)
}
}
async fn get_static_file(
uri: Uri,
base: &str,
) -> Result<Response<Body>, (StatusCode, String)> {
let req = Request::builder().uri(&uri).body(Body::empty()).unwrap();
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
// When run normally, the root should be the crate root
if base == "/static" {
match ServeDir::new("./static").oneshot(req).await {
Ok(res) => Ok(res.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", err),
)),
}
} else if base == "/pkg" {
match ServeDir::new("./pkg").oneshot(req).await {
Ok(res) => Ok(res.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", err),
)),
}
} else {
Err((StatusCode::NOT_FOUND, "Not Found".to_string()))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/api.rs | examples/hackernews_axum/src/api.rs | use leptos::logging;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
pub fn story(path: &str) -> String {
format!("https://node-hnapi.herokuapp.com/{path}")
}
pub fn user(path: &str) -> String {
format!("https://hacker-news.firebaseio.com/v0/user/{path}.json")
}
#[cfg(not(feature = "ssr"))]
pub fn fetch_api<T>(
path: &str,
) -> impl std::future::Future<Output = Option<T>> + Send + '_
where
T: Serialize + DeserializeOwned,
{
use leptos::prelude::on_cleanup;
use send_wrapper::SendWrapper;
SendWrapper::new(async move {
let abort_controller =
SendWrapper::new(web_sys::AbortController::new().ok());
let abort_signal = abort_controller.as_ref().map(|a| a.signal());
// abort in-flight requests if, e.g., we've navigated away from this page
on_cleanup(move || {
if let Some(abort_controller) = abort_controller.take() {
abort_controller.abort()
}
});
gloo_net::http::Request::get(path)
.abort_signal(abort_signal.as_ref())
.send()
.await
.map_err(|e| logging::error!("{e}"))
.ok()?
.json()
.await
.ok()
})
}
#[cfg(feature = "ssr")]
pub async fn fetch_api<T>(path: &str) -> Option<T>
where
T: Serialize + DeserializeOwned,
{
reqwest::get(path)
.await
.map_err(|e| logging::error!("{e}"))
.ok()?
.json()
.await
.ok()
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct Story {
pub id: usize,
pub title: String,
pub points: Option<i32>,
pub user: Option<String>,
pub time: usize,
pub time_ago: String,
#[serde(alias = "type")]
pub story_type: String,
pub url: String,
#[serde(default)]
pub domain: String,
#[serde(default)]
pub comments: Option<Vec<Comment>>,
pub comments_count: Option<usize>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct Comment {
pub id: usize,
pub level: usize,
pub user: Option<String>,
pub time: usize,
pub time_ago: String,
pub content: Option<String>,
pub comments: Vec<Comment>,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)]
pub struct User {
pub created: usize,
pub id: String,
pub karma: i32,
pub about: Option<String>,
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/examples/hackernews_axum/src/error_template.rs | examples/hackernews_axum/src/error_template.rs | use leptos::{view, Errors, For, IntoView, RwSignal, SignalGet, View};
// A basic function to display errors served by the error boundaries. Feel free to do more complicated things
// here than just displaying them
pub fn error_template(errors: Option<RwSignal<Errors>>) -> View {
let Some(errors) = errors else {
panic!("No Errors found and we expected errors!");
};
view! {
<h1>"Errors"</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each=move || errors.get()
// a unique key for each item as a reference
key=|(key, _)| key.clone()
// renders each item to a view
children=move | (_, error)| {
let error_string = error.to_string();
view! {
<p>"Error: " {error_string}</p>
}
}
/>
}
.into_view()
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.