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/server_fn/src/middleware/mod.rs | server_fn/src/middleware/mod.rs | use crate::error::ServerFnErrorErr;
use bytes::Bytes;
use std::{future::Future, pin::Pin};
/// An abstraction over a middleware layer, which can be used to add additional
/// middleware layer to a [`Service`].
pub trait Layer<Req, Res>: Send + Sync + 'static {
/// Adds this layer to the inner service.
fn layer(&self, inner: BoxedService<Req, Res>) -> BoxedService<Req, Res>;
}
/// A type-erased service, which takes an HTTP request and returns a response.
pub struct BoxedService<Req, Res> {
/// A function that converts a [`ServerFnErrorErr`] into a string.
pub ser: fn(ServerFnErrorErr) -> Bytes,
/// The inner service.
pub service: Box<dyn Service<Req, Res> + Send>,
}
impl<Req, Res> BoxedService<Req, Res> {
/// Constructs a type-erased service from this service.
pub fn new(
ser: fn(ServerFnErrorErr) -> Bytes,
service: impl Service<Req, Res> + Send + 'static,
) -> Self {
Self {
ser,
service: Box::new(service),
}
}
/// Converts a request into a response by running the inner service.
pub fn run(
&mut self,
req: Req,
) -> Pin<Box<dyn Future<Output = Res> + Send>> {
self.service.run(req, self.ser)
}
}
/// A service converts an HTTP request into a response.
pub trait Service<Request, Response> {
/// Converts a request into a response.
fn run(
&mut self,
req: Request,
ser: fn(ServerFnErrorErr) -> Bytes,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
}
#[cfg(feature = "axum-no-default")]
mod axum {
use super::{BoxedService, Service};
use crate::{error::ServerFnErrorErr, response::Res, ServerFnError};
use axum::body::Body;
use bytes::Bytes;
use http::{Request, Response};
use std::{future::Future, pin::Pin};
impl<S> super::Service<Request<Body>, Response<Body>> for S
where
S: tower::Service<Request<Body>, Response = Response<Body>>,
S::Future: Send + 'static,
S::Error: std::fmt::Display + Send + 'static,
{
fn run(
&mut self,
req: Request<Body>,
ser: fn(ServerFnErrorErr) -> Bytes,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> {
let path = req.uri().path().to_string();
let inner = self.call(req);
Box::pin(async move {
inner.await.unwrap_or_else(|e| {
// TODO: This does not set the Content-Type on the response. Doing so will
// require a breaking change in order to get the correct encoding from the
// error's `FromServerFnError::Encoder::CONTENT_TYPE` impl.
// Note: This only applies to middleware errors.
let err =
ser(ServerFnErrorErr::MiddlewareError(e.to_string()));
Response::<Body>::error_response(&path, err)
})
})
}
}
impl tower::Service<Request<Body>>
for BoxedService<Request<Body>, Response<Body>>
{
type Response = Response<Body>;
type Error = ServerFnError;
type Future = Pin<
Box<
dyn std::future::Future<
Output = Result<Self::Response, Self::Error>,
> + Send,
>,
>;
fn poll_ready(
&mut self,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
Ok(()).into()
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let inner = self.service.run(req, self.ser);
Box::pin(async move { Ok(inner.await) })
}
}
impl<L> super::Layer<Request<Body>, Response<Body>> for L
where
L: tower_layer::Layer<BoxedService<Request<Body>, Response<Body>>>
+ Sync
+ Send
+ 'static,
L::Service: Service<Request<Body>, Response<Body>> + Send + 'static,
{
fn layer(
&self,
inner: BoxedService<Request<Body>, Response<Body>>,
) -> BoxedService<Request<Body>, Response<Body>> {
BoxedService::new(inner.ser, self.layer(inner))
}
}
}
#[cfg(feature = "actix-no-default")]
mod actix {
use crate::{
error::ServerFnErrorErr,
request::actix::ActixRequest,
response::{actix::ActixResponse, Res},
};
use actix_web::{HttpRequest, HttpResponse};
use bytes::Bytes;
use std::{future::Future, pin::Pin};
impl<S> super::Service<HttpRequest, HttpResponse> for S
where
S: actix_web::dev::Service<HttpRequest, Response = HttpResponse>,
S::Future: Send + 'static,
S::Error: std::fmt::Display + Send + 'static,
{
fn run(
&mut self,
req: HttpRequest,
ser: fn(ServerFnErrorErr) -> Bytes,
) -> Pin<Box<dyn Future<Output = HttpResponse> + Send>> {
let path = req.uri().path().to_string();
let inner = self.call(req);
Box::pin(async move {
inner.await.unwrap_or_else(|e| {
// TODO: This does not set the Content-Type on the response. Doing so will
// require a breaking change in order to get the correct encoding from the
// error's `FromServerFnError::Encoder::CONTENT_TYPE` impl.
// Note: This only applies to middleware errors.
let err =
ser(ServerFnErrorErr::MiddlewareError(e.to_string()));
ActixResponse::error_response(&path, err).take()
})
})
}
}
impl<S> super::Service<ActixRequest, ActixResponse> for S
where
S: actix_web::dev::Service<HttpRequest, Response = HttpResponse>,
S::Future: Send + 'static,
S::Error: std::fmt::Display + Send + 'static,
{
fn run(
&mut self,
req: ActixRequest,
ser: fn(ServerFnErrorErr) -> Bytes,
) -> Pin<Box<dyn Future<Output = ActixResponse> + Send>> {
let path = req.0 .0.uri().path().to_string();
let inner = self.call(req.0.take().0);
Box::pin(async move {
ActixResponse::from(inner.await.unwrap_or_else(|e| {
let err =
ser(ServerFnErrorErr::MiddlewareError(e.to_string()));
ActixResponse::error_response(&path, err).take()
}))
})
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/response/actix.rs | server_fn/src/response/actix.rs | use super::{Res, TryRes};
use crate::error::{
FromServerFnError, ServerFnErrorWrapper, SERVER_FN_ERROR_HEADER,
};
use actix_web::{
http::{
header,
header::{HeaderValue, CONTENT_TYPE, LOCATION},
StatusCode,
},
HttpResponse,
};
use bytes::Bytes;
use futures::{Stream, StreamExt};
use send_wrapper::SendWrapper;
/// A wrapped Actix response.
///
/// This uses a [`SendWrapper`] that allows the Actix `HttpResponse` type to be `Send`, but panics
/// if it it is ever sent to another thread. Actix pins request handling to a single thread, so this
/// is necessary to be compatible with traits that require `Send` but should never panic in actual use.
pub struct ActixResponse(pub(crate) SendWrapper<HttpResponse>);
impl ActixResponse {
/// Returns the raw Actix response.
pub fn take(self) -> HttpResponse {
self.0.take()
}
}
impl From<HttpResponse> for ActixResponse {
fn from(value: HttpResponse) -> Self {
Self(SendWrapper::new(value))
}
}
impl<E> TryRes<E> for ActixResponse
where
E: FromServerFnError,
{
fn try_from_string(content_type: &str, data: String) -> Result<Self, E> {
let mut builder = HttpResponse::build(StatusCode::OK);
Ok(ActixResponse(SendWrapper::new(
builder
.insert_header((header::CONTENT_TYPE, content_type))
.body(data),
)))
}
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E> {
let mut builder = HttpResponse::build(StatusCode::OK);
Ok(ActixResponse(SendWrapper::new(
builder
.insert_header((header::CONTENT_TYPE, content_type))
.body(data),
)))
}
fn try_from_stream(
content_type: &str,
data: impl Stream<Item = Result<Bytes, Bytes>> + 'static,
) -> Result<Self, E> {
let mut builder = HttpResponse::build(StatusCode::OK);
Ok(ActixResponse(SendWrapper::new(
builder
.insert_header((header::CONTENT_TYPE, content_type))
.streaming(data.map(|data| {
data.map_err(|e| ServerFnErrorWrapper(E::de(e)))
})),
)))
}
}
impl Res for ActixResponse {
fn error_response(path: &str, err: Bytes) -> Self {
ActixResponse(SendWrapper::new(
HttpResponse::build(StatusCode::INTERNAL_SERVER_ERROR)
.append_header((SERVER_FN_ERROR_HEADER, path))
.body(err),
))
}
fn content_type(&mut self, content_type: &str) {
if let Ok(content_type) = HeaderValue::from_str(content_type) {
self.0.headers_mut().insert(CONTENT_TYPE, content_type);
}
}
fn redirect(&mut self, path: &str) {
if let Ok(path) = HeaderValue::from_str(path) {
*self.0.status_mut() = StatusCode::FOUND;
self.0.headers_mut().insert(LOCATION, path);
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/response/http.rs | server_fn/src/response/http.rs | use super::{Res, TryRes};
use crate::error::{
FromServerFnError, IntoAppError, ServerFnErrorErr, ServerFnErrorWrapper,
SERVER_FN_ERROR_HEADER,
};
use axum::body::Body;
use bytes::Bytes;
use futures::{Stream, TryStreamExt};
use http::{header, HeaderValue, Response, StatusCode};
impl<E> TryRes<E> for Response<Body>
where
E: Send + Sync + FromServerFnError,
{
fn try_from_string(content_type: &str, data: String) -> Result<Self, E> {
let builder = http::Response::builder();
builder
.status(200)
.header(http::header::CONTENT_TYPE, content_type)
.body(Body::from(data))
.map_err(|e| {
ServerFnErrorErr::Response(e.to_string()).into_app_error()
})
}
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E> {
let builder = http::Response::builder();
builder
.status(200)
.header(http::header::CONTENT_TYPE, content_type)
.body(Body::from(data))
.map_err(|e| {
ServerFnErrorErr::Response(e.to_string()).into_app_error()
})
}
fn try_from_stream(
content_type: &str,
data: impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
) -> Result<Self, E> {
let body =
Body::from_stream(data.map_err(|e| ServerFnErrorWrapper(E::de(e))));
let builder = http::Response::builder();
builder
.status(200)
.header(http::header::CONTENT_TYPE, content_type)
.body(body)
.map_err(|e| {
ServerFnErrorErr::Response(e.to_string()).into_app_error()
})
}
}
impl Res for Response<Body> {
fn error_response(path: &str, err: Bytes) -> Self {
Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.header(SERVER_FN_ERROR_HEADER, path)
.body(err.into())
.unwrap()
}
fn content_type(&mut self, content_type: &str) {
if let Ok(content_type) = HeaderValue::from_str(content_type) {
self.headers_mut()
.insert(header::CONTENT_TYPE, content_type);
}
}
fn redirect(&mut self, path: &str) {
if let Ok(path) = HeaderValue::from_str(path) {
self.headers_mut().insert(header::LOCATION, path);
*self.status_mut() = StatusCode::FOUND;
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/response/browser.rs | server_fn/src/response/browser.rs | use super::ClientRes;
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
redirect::REDIRECT_HEADER,
};
use bytes::Bytes;
use futures::{Stream, StreamExt};
pub use gloo_net::http::Response;
use http::{HeaderMap, HeaderName, HeaderValue};
use js_sys::Uint8Array;
use send_wrapper::SendWrapper;
use std::{future::Future, str::FromStr};
use wasm_bindgen::JsCast;
use wasm_streams::ReadableStream;
/// The response to a `fetch` request made in the browser.
pub struct BrowserResponse(pub(crate) SendWrapper<Response>);
impl BrowserResponse {
/// Generate the headers from the internal [`Response`] object.
/// This is a workaround for the fact that the `Response` object does not
/// have a [`HeaderMap`] directly. This function will iterate over the
/// headers and convert them to a [`HeaderMap`].
pub fn generate_headers(&self) -> HeaderMap {
self.0
.headers()
.entries()
.filter_map(|(key, value)| {
let key = HeaderName::from_str(&key).ok()?;
let value = HeaderValue::from_str(&value).ok()?;
Some((key, value))
})
.collect()
}
}
impl<E: FromServerFnError> ClientRes<E> for BrowserResponse {
fn try_into_string(self) -> impl Future<Output = Result<String, E>> + Send {
// the browser won't send this async work between threads (because it's single-threaded)
// so we can safely wrap this
SendWrapper::new(async move {
self.0.text().await.map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string())
.into_app_error()
})
})
}
fn try_into_bytes(self) -> impl Future<Output = Result<Bytes, E>> + Send {
// the browser won't send this async work between threads (because it's single-threaded)
// so we can safely wrap this
SendWrapper::new(async move {
self.0.binary().await.map(Bytes::from).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string())
.into_app_error()
})
})
}
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static, E>
{
let stream = ReadableStream::from_raw(self.0.body().unwrap())
.into_stream()
.map(|data| match data {
Err(e) => {
web_sys::console::error_1(&e);
Err(E::from_server_fn_error(ServerFnErrorErr::Request(
format!("{e:?}"),
))
.ser())
}
Ok(data) => {
let data = data.unchecked_into::<Uint8Array>();
let mut buf = Vec::new();
let length = data.length();
buf.resize(length as usize, 0);
data.copy_to(&mut buf);
Ok(Bytes::from(buf))
}
});
Ok(SendWrapper::new(stream))
}
fn status(&self) -> u16 {
self.0.status()
}
fn status_text(&self) -> String {
self.0.status_text()
}
fn location(&self) -> String {
self.0
.headers()
.get("Location")
.unwrap_or_else(|| self.0.url())
}
fn has_redirect(&self) -> bool {
self.0.headers().get(REDIRECT_HEADER).is_some()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/response/reqwest.rs | server_fn/src/response/reqwest.rs | use super::ClientRes;
use crate::error::{FromServerFnError, IntoAppError, ServerFnErrorErr};
use bytes::Bytes;
use futures::{Stream, TryStreamExt};
use reqwest::Response;
impl<E: FromServerFnError> ClientRes<E> for Response {
async fn try_into_string(self) -> Result<String, E> {
self.text().await.map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})
}
async fn try_into_bytes(self) -> Result<Bytes, E> {
self.bytes().await.map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})
}
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static, E>
{
Ok(self.bytes_stream().map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Response(e.to_string()))
.ser()
}))
}
fn status(&self) -> u16 {
self.status().as_u16()
}
fn status_text(&self) -> String {
self.status().to_string()
}
fn location(&self) -> String {
self.headers()
.get("Location")
.map(|value| String::from_utf8_lossy(value.as_bytes()).to_string())
.unwrap_or_else(|| self.url().to_string())
}
fn has_redirect(&self) -> bool {
self.headers().get("Location").is_some()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/response/mod.rs | server_fn/src/response/mod.rs | /// Response types for Actix.
#[cfg(feature = "actix-no-default")]
pub mod actix;
/// Response types for the browser.
#[cfg(feature = "browser")]
pub mod browser;
#[cfg(feature = "generic")]
pub mod generic;
/// Response types for Axum.
#[cfg(feature = "axum-no-default")]
pub mod http;
/// Response types for [`reqwest`].
#[cfg(feature = "reqwest")]
pub mod reqwest;
use bytes::Bytes;
use futures::Stream;
use std::future::Future;
/// Represents the response as created by the server;
pub trait TryRes<E>
where
Self: Sized,
{
/// Attempts to convert a UTF-8 string into an HTTP response.
fn try_from_string(content_type: &str, data: String) -> Result<Self, E>;
/// Attempts to convert a binary blob represented as bytes into an HTTP response.
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E>;
/// Attempts to convert a stream of bytes into an HTTP response.
fn try_from_stream(
content_type: &str,
data: impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
) -> Result<Self, E>;
}
/// Represents the response as created by the server;
pub trait Res {
/// Converts an error into a response, with a `500` status code and the error as its body.
fn error_response(path: &str, err: Bytes) -> Self;
/// Set the `Content-Type` header for the response.
fn content_type(&mut self, #[allow(unused_variables)] content_type: &str) {
// TODO 0.9: remove this method and default implementation. It is only included here
// to allow setting the `Content-Type` header for error responses without requiring a
// semver-incompatible change.
}
/// Redirect the response by setting a 302 code and Location header.
fn redirect(&mut self, path: &str);
}
/// Represents the response as received by the client.
pub trait ClientRes<E> {
/// Attempts to extract a UTF-8 string from an HTTP response.
fn try_into_string(self) -> impl Future<Output = Result<String, E>> + Send;
/// Attempts to extract a binary blob from an HTTP response.
fn try_into_bytes(self) -> impl Future<Output = Result<Bytes, E>> + Send;
/// Attempts to extract a binary stream from an HTTP response.
fn try_into_stream(
self,
) -> Result<
impl Stream<Item = Result<Bytes, Bytes>> + Send + Sync + 'static,
E,
>;
/// HTTP status code of the response.
fn status(&self) -> u16;
/// Status text for the status code.
fn status_text(&self) -> String;
/// The `Location` header or (if none is set), the URL of the response.
fn location(&self) -> String;
/// Whether the response has the [`REDIRECT_HEADER`](crate::redirect::REDIRECT_HEADER) set.
fn has_redirect(&self) -> bool;
}
/// A mocked response type that can be used in place of the actual server response,
/// when compiling for the browser.
///
/// ## Panics
/// This always panics if its methods are called. It is used solely to stub out the
/// server response type when compiling for the client.
pub struct BrowserMockRes;
impl<E> TryRes<E> for BrowserMockRes {
fn try_from_string(_content_type: &str, _data: String) -> Result<Self, E> {
unreachable!()
}
fn try_from_bytes(_content_type: &str, _data: Bytes) -> Result<Self, E> {
unreachable!()
}
fn try_from_stream(
_content_type: &str,
_data: impl Stream<Item = Result<Bytes, Bytes>>,
) -> Result<Self, E> {
unreachable!()
}
}
impl Res for BrowserMockRes {
fn error_response(_path: &str, _err: Bytes) -> Self {
unreachable!()
}
fn content_type(&mut self, _content_type: &str) {
unreachable!()
}
fn redirect(&mut self, _path: &str) {
unreachable!()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/response/generic.rs | server_fn/src/response/generic.rs | //! This module uses platform-agnostic abstractions
//! allowing users to run server functions on a wide range of
//! platforms.
//!
//! The crates in use in this crate are:
//!
//! * `bytes`: platform-agnostic manipulation of bytes.
//! * `http`: low-dependency HTTP abstractions' *front-end*.
//!
//! # Users
//!
//! * `wasm32-wasip*` integration crate `leptos_wasi` is using this
//! crate under the hood.
use super::{Res, TryRes};
use crate::error::{
FromServerFnError, IntoAppError, ServerFnErrorErr, ServerFnErrorWrapper,
SERVER_FN_ERROR_HEADER,
};
use bytes::Bytes;
use futures::{Stream, TryStreamExt};
use http::{header, HeaderValue, Response, StatusCode};
use std::pin::Pin;
use throw_error::Error;
/// The Body of a Response whose *execution model* can be
/// customised using the variants.
pub enum Body {
/// The response body will be written synchronously.
Sync(Bytes),
/// The response body will be written asynchronously,
/// this execution model is also known as
/// "streaming".
Async(Pin<Box<dyn Stream<Item = Result<Bytes, Error>> + Send + 'static>>),
}
impl From<String> for Body {
fn from(value: String) -> Self {
Body::Sync(Bytes::from(value))
}
}
impl From<Bytes> for Body {
fn from(value: Bytes) -> Self {
Body::Sync(value)
}
}
impl<E> TryRes<E> for Response<Body>
where
E: Send + Sync + FromServerFnError,
{
fn try_from_string(content_type: &str, data: String) -> Result<Self, E> {
let builder = http::Response::builder();
builder
.status(200)
.header(http::header::CONTENT_TYPE, content_type)
.body(data.into())
.map_err(|e| {
ServerFnErrorErr::Response(e.to_string()).into_app_error()
})
}
fn try_from_bytes(content_type: &str, data: Bytes) -> Result<Self, E> {
let builder = http::Response::builder();
builder
.status(200)
.header(http::header::CONTENT_TYPE, content_type)
.body(Body::Sync(data))
.map_err(|e| {
ServerFnErrorErr::Response(e.to_string()).into_app_error()
})
}
fn try_from_stream(
content_type: &str,
data: impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
) -> Result<Self, E> {
let builder = http::Response::builder();
builder
.status(200)
.header(http::header::CONTENT_TYPE, content_type)
.body(Body::Async(Box::pin(
data.map_err(|e| ServerFnErrorWrapper(E::de(e)))
.map_err(Error::from),
)))
.map_err(|e| {
ServerFnErrorErr::Response(e.to_string()).into_app_error()
})
}
}
impl Res for Response<Body> {
fn error_response(path: &str, err: Bytes) -> Self {
Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.header(SERVER_FN_ERROR_HEADER, path)
.body(err.into())
.unwrap()
}
fn content_type(&mut self, content_type: &str) {
if let Ok(content_type) = HeaderValue::from_str(content_type) {
self.headers_mut()
.insert(header::CONTENT_TYPE, content_type);
}
}
fn redirect(&mut self, path: &str) {
if let Ok(path) = HeaderValue::from_str(path) {
self.headers_mut().insert(header::LOCATION, path);
*self.status_mut() = StatusCode::FOUND;
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/request/actix.rs | server_fn/src/request/actix.rs | use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::Req,
response::actix::ActixResponse,
};
use actix_web::{web::Payload, HttpRequest};
use actix_ws::Message;
use bytes::Bytes;
use futures::{FutureExt, Stream, StreamExt};
use send_wrapper::SendWrapper;
use std::{borrow::Cow, future::Future};
/// A wrapped Actix request.
///
/// This uses a [`SendWrapper`] that allows the Actix `HttpRequest` type to be `Send`, but panics
/// if it it is ever sent to another thread. Actix pins request handling to a single thread, so this
/// is necessary to be compatible with traits that require `Send` but should never panic in actual use.
pub struct ActixRequest(pub(crate) SendWrapper<(HttpRequest, Payload)>);
impl ActixRequest {
/// Returns the raw Actix request, and its body.
pub fn take(self) -> (HttpRequest, Payload) {
self.0.take()
}
fn header(&self, name: &str) -> Option<Cow<'_, str>> {
self.0
.0
.headers()
.get(name)
.map(|h| String::from_utf8_lossy(h.as_bytes()))
}
}
impl From<(HttpRequest, Payload)> for ActixRequest {
fn from(value: (HttpRequest, Payload)) -> Self {
ActixRequest(SendWrapper::new(value))
}
}
impl<Error, InputStreamError, OutputStreamError>
Req<Error, InputStreamError, OutputStreamError> for ActixRequest
where
Error: FromServerFnError + Send,
InputStreamError: FromServerFnError + Send,
OutputStreamError: FromServerFnError + Send,
{
type WebsocketResponse = ActixResponse;
fn as_query(&self) -> Option<&str> {
self.0 .0.uri().query()
}
fn to_content_type(&self) -> Option<Cow<'_, str>> {
self.header("Content-Type")
}
fn accepts(&self) -> Option<Cow<'_, str>> {
self.header("Accept")
}
fn referer(&self) -> Option<Cow<'_, str>> {
self.header("Referer")
}
fn try_into_bytes(
self,
) -> impl Future<Output = Result<Bytes, Error>> + Send {
// Actix is going to keep this on a single thread anyway so it's fine to wrap it
// with SendWrapper, which makes it `Send` but will panic if it moves to another thread
SendWrapper::new(async move {
let payload = self.0.take().1;
payload.to_bytes().await.map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string())
.into_app_error()
})
})
}
fn try_into_string(
self,
) -> impl Future<Output = Result<String, Error>> + Send {
// Actix is going to keep this on a single thread anyway so it's fine to wrap it
// with SendWrapper, which makes it `Send` but will panic if it moves to another thread
SendWrapper::new(async move {
let payload = self.0.take().1;
let bytes = payload.to_bytes().await.map_err(|e| {
Error::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
})?;
String::from_utf8(bytes.into()).map_err(|e| {
Error::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
})
})
}
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send, Error> {
let payload = self.0.take().1;
let stream = payload.map(|res| {
res.map_err(|e| {
Error::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
.ser()
})
});
Ok(SendWrapper::new(stream))
}
async fn try_into_websocket(
self,
) -> Result<
(
impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
impl futures::Sink<Bytes> + Send + 'static,
Self::WebsocketResponse,
),
Error,
> {
let (request, payload) = self.0.take();
let (response, mut session, mut msg_stream) =
actix_ws::handle(&request, payload).map_err(|e| {
Error::from_server_fn_error(ServerFnErrorErr::Request(
e.to_string(),
))
})?;
let (mut response_stream_tx, response_stream_rx) =
futures::channel::mpsc::channel(2048);
let (response_sink_tx, mut response_sink_rx) =
futures::channel::mpsc::channel::<Bytes>(2048);
actix_web::rt::spawn(async move {
loop {
futures::select! {
incoming = response_sink_rx.next() => {
let Some(incoming) = incoming else {
break;
};
if let Err(err) = session.binary(incoming).await {
_ = response_stream_tx.start_send(Err(InputStreamError::from_server_fn_error(ServerFnErrorErr::Request(err.to_string())).ser()));
}
},
outgoing = msg_stream.next().fuse() => {
let Some(outgoing) = outgoing else {
break;
};
match outgoing {
Ok(Message::Ping(bytes)) => {
if session.pong(&bytes).await.is_err() {
break;
}
}
Ok(Message::Binary(bytes)) => {
_ = response_stream_tx
.start_send(
Ok(bytes),
);
}
Ok(Message::Text(text)) => {
_ = response_stream_tx.start_send(Ok(text.into_bytes()));
}
Ok(Message::Close(_)) => {
break;
}
Ok(_other) => {
}
Err(e) => {
_ = response_stream_tx.start_send(Err(InputStreamError::from_server_fn_error(ServerFnErrorErr::Response(e.to_string())).ser()));
}
}
}
}
}
let _ = session.close(None).await;
});
Ok((
response_stream_rx,
response_sink_tx,
ActixResponse::from(response),
))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/request/axum.rs | server_fn/src/request/axum.rs | use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::Req,
};
use axum::{
body::{Body, Bytes},
response::Response,
};
use futures::{Sink, Stream, StreamExt};
use http::{
header::{ACCEPT, CONTENT_TYPE, REFERER},
Request,
};
use http_body_util::BodyExt;
use std::borrow::Cow;
impl<Error, InputStreamError, OutputStreamError>
Req<Error, InputStreamError, OutputStreamError> for Request<Body>
where
Error: FromServerFnError + Send,
InputStreamError: FromServerFnError + Send,
OutputStreamError: FromServerFnError + Send,
{
type WebsocketResponse = Response;
fn as_query(&self) -> Option<&str> {
self.uri().query()
}
fn to_content_type(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(CONTENT_TYPE)
.map(|h| String::from_utf8_lossy(h.as_bytes()))
}
fn accepts(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(ACCEPT)
.map(|h| String::from_utf8_lossy(h.as_bytes()))
}
fn referer(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(REFERER)
.map(|h| String::from_utf8_lossy(h.as_bytes()))
}
async fn try_into_bytes(self) -> Result<Bytes, Error> {
let (_parts, body) = self.into_parts();
body.collect().await.map(|c| c.to_bytes()).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})
}
async fn try_into_string(self) -> Result<String, Error> {
let bytes = Req::<Error>::try_into_bytes(self).await?;
String::from_utf8(bytes.to_vec()).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})
}
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static, Error>
{
Ok(self.into_body().into_data_stream().map(|chunk| {
chunk.map_err(|e| {
Error::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
.ser()
})
}))
}
async fn try_into_websocket(
self,
) -> Result<
(
impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
impl Sink<Bytes> + Send + 'static,
Self::WebsocketResponse,
),
Error,
> {
#[cfg(not(feature = "axum"))]
{
Err::<
(
futures::stream::Once<
std::future::Ready<Result<Bytes, Bytes>>,
>,
futures::sink::Drain<Bytes>,
Self::WebsocketResponse,
),
Error,
>(Error::from_server_fn_error(
crate::ServerFnErrorErr::Response(
"Websocket connections not supported for Axum when the \
`axum` feature is not enabled on the `server_fn` crate."
.to_string(),
),
))
}
#[cfg(feature = "axum")]
{
use axum::extract::{ws::Message, FromRequest};
use futures::FutureExt;
let upgrade =
axum::extract::ws::WebSocketUpgrade::from_request(self, &())
.await
.map_err(|err| {
Error::from_server_fn_error(ServerFnErrorErr::Request(
err.to_string(),
))
})?;
let (mut outgoing_tx, outgoing_rx) =
futures::channel::mpsc::channel::<Result<Bytes, Bytes>>(2048);
let (incoming_tx, mut incoming_rx) =
futures::channel::mpsc::channel::<Bytes>(2048);
let response = upgrade
.on_failed_upgrade({
let mut outgoing_tx = outgoing_tx.clone();
move |err: axum::Error| {
_ = outgoing_tx.start_send(Err(InputStreamError::from_server_fn_error(ServerFnErrorErr::Response(err.to_string())).ser()));
}
})
.on_upgrade(|mut session| async move {
loop {
futures::select! {
incoming = incoming_rx.next() => {
let Some(incoming) = incoming else {
break;
};
if let Err(err) = session.send(Message::Binary(incoming)).await {
_ = outgoing_tx.start_send(Err(InputStreamError::from_server_fn_error(ServerFnErrorErr::Request(err.to_string())).ser()));
}
},
outgoing = session.recv().fuse() => {
let Some(outgoing) = outgoing else {
break;
};
match outgoing {
Ok(Message::Binary(bytes)) => {
_ = outgoing_tx
.start_send(
Ok(bytes),
);
}
Ok(Message::Text(text)) => {
_ = outgoing_tx.start_send(Ok(Bytes::from(text)));
}
Ok(Message::Ping(bytes)) => {
if session.send(Message::Pong(bytes)).await.is_err() {
break;
}
}
Ok(_other) => {}
Err(e) => {
_ = outgoing_tx.start_send(Err(InputStreamError::from_server_fn_error(ServerFnErrorErr::Response(e.to_string())).ser()));
}
}
}
}
}
_ = session.send(Message::Close(None)).await;
});
Ok((outgoing_rx, incoming_tx, response))
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/request/browser.rs | server_fn/src/request/browser.rs | use super::ClientReq;
use crate::{
client::get_server_url,
error::{FromServerFnError, ServerFnErrorErr},
};
use bytes::Bytes;
use futures::{Stream, StreamExt};
pub use gloo_net::http::Request;
use http::Method;
use js_sys::{Reflect, Uint8Array};
use send_wrapper::SendWrapper;
use std::ops::{Deref, DerefMut};
use wasm_bindgen::JsValue;
use wasm_streams::ReadableStream;
use web_sys::{
AbortController, AbortSignal, FormData, Headers, RequestInit,
UrlSearchParams,
};
/// A `fetch` request made in the browser.
#[derive(Debug)]
pub struct BrowserRequest(pub(crate) SendWrapper<RequestInner>);
#[derive(Debug)]
pub(crate) struct RequestInner {
pub(crate) request: Request,
pub(crate) abort_ctrl: Option<AbortOnDrop>,
}
#[derive(Debug)]
pub(crate) struct AbortOnDrop(Option<AbortController>);
impl AbortOnDrop {
/// Prevents the request from being aborted on drop.
pub fn prevent_cancellation(&mut self) {
self.0.take();
}
}
impl Drop for AbortOnDrop {
fn drop(&mut self) {
if let Some(inner) = self.0.take() {
inner.abort();
}
}
}
impl From<BrowserRequest> for Request {
fn from(value: BrowserRequest) -> Self {
value.0.take().request
}
}
impl From<BrowserRequest> for web_sys::Request {
fn from(value: BrowserRequest) -> Self {
value.0.take().request.into()
}
}
impl Deref for BrowserRequest {
type Target = Request;
fn deref(&self) -> &Self::Target {
&self.0.deref().request
}
}
impl DerefMut for BrowserRequest {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0.deref_mut().request
}
}
/// The `FormData` type available in the browser.
#[derive(Debug)]
pub struct BrowserFormData(pub(crate) SendWrapper<FormData>);
impl BrowserFormData {
/// Returns the raw `web_sys::FormData` struct.
pub fn take(self) -> FormData {
self.0.take()
}
}
impl From<FormData> for BrowserFormData {
fn from(value: FormData) -> Self {
Self(SendWrapper::new(value))
}
}
fn abort_signal() -> (Option<AbortOnDrop>, Option<AbortSignal>) {
let ctrl = AbortController::new().ok();
let signal = ctrl.as_ref().map(|ctrl| ctrl.signal());
(ctrl.map(|ctrl| AbortOnDrop(Some(ctrl))), signal)
}
impl<E> ClientReq<E> for BrowserRequest
where
E: FromServerFnError,
{
type FormData = BrowserFormData;
fn try_new_req_query(
path: &str,
content_type: &str,
accepts: &str,
query: &str,
method: http::Method,
) -> Result<Self, E> {
let (abort_ctrl, abort_signal) = abort_signal();
let server_url = get_server_url();
let mut url = String::with_capacity(
server_url.len() + path.len() + 1 + query.len(),
);
url.push_str(server_url);
url.push_str(path);
url.push('?');
url.push_str(query);
Ok(Self(SendWrapper::new(RequestInner {
request: match method {
Method::GET => Request::get(&url),
Method::DELETE => Request::delete(&url),
Method::POST => Request::post(&url),
Method::PUT => Request::put(&url),
Method::PATCH => Request::patch(&url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(
m.to_string(),
),
))
}
}
.header("Content-Type", content_type)
.header("Accept", accepts)
.abort_signal(abort_signal.as_ref())
.build()
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(
e.to_string(),
))
})?,
abort_ctrl,
})))
}
fn try_new_req_text(
path: &str,
content_type: &str,
accepts: &str,
body: String,
method: Method,
) -> Result<Self, E> {
let (abort_ctrl, abort_signal) = abort_signal();
let server_url = get_server_url();
let mut url = String::with_capacity(server_url.len() + path.len());
url.push_str(server_url);
url.push_str(path);
Ok(Self(SendWrapper::new(RequestInner {
request: match method {
Method::POST => Request::post(&url),
Method::PATCH => Request::patch(&url),
Method::PUT => Request::put(&url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(
m.to_string(),
),
))
}
}
.header("Content-Type", content_type)
.header("Accept", accepts)
.abort_signal(abort_signal.as_ref())
.body(body)
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(
e.to_string(),
))
})?,
abort_ctrl,
})))
}
fn try_new_req_bytes(
path: &str,
content_type: &str,
accepts: &str,
body: Bytes,
method: Method,
) -> Result<Self, E> {
let (abort_ctrl, abort_signal) = abort_signal();
let server_url = get_server_url();
let mut url = String::with_capacity(server_url.len() + path.len());
url.push_str(server_url);
url.push_str(path);
let body: &[u8] = &body;
let body = Uint8Array::from(body).buffer();
Ok(Self(SendWrapper::new(RequestInner {
request: match method {
Method::POST => Request::post(&url),
Method::PATCH => Request::patch(&url),
Method::PUT => Request::put(&url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(
m.to_string(),
),
))
}
}
.header("Content-Type", content_type)
.header("Accept", accepts)
.abort_signal(abort_signal.as_ref())
.body(body)
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(
e.to_string(),
))
})?,
abort_ctrl,
})))
}
fn try_new_req_multipart(
path: &str,
accepts: &str,
body: Self::FormData,
method: Method,
) -> Result<Self, E> {
let (abort_ctrl, abort_signal) = abort_signal();
let server_url = get_server_url();
let mut url = String::with_capacity(server_url.len() + path.len());
url.push_str(server_url);
url.push_str(path);
Ok(Self(SendWrapper::new(RequestInner {
request: match method {
Method::POST => Request::post(&url),
Method::PATCH => Request::patch(&url),
Method::PUT => Request::put(&url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(
m.to_string(),
),
))
}
}
.header("Accept", accepts)
.abort_signal(abort_signal.as_ref())
.body(body.0.take())
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(
e.to_string(),
))
})?,
abort_ctrl,
})))
}
fn try_new_req_form_data(
path: &str,
accepts: &str,
content_type: &str,
body: Self::FormData,
method: Method,
) -> Result<Self, E> {
let (abort_ctrl, abort_signal) = abort_signal();
let form_data = body.0.take();
let url_params =
UrlSearchParams::new_with_str_sequence_sequence(&form_data)
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Serialization(
e.as_string().unwrap_or_else(|| {
"Could not serialize FormData to URLSearchParams"
.to_string()
}),
))
})?;
Ok(Self(SendWrapper::new(RequestInner {
request: match method {
Method::POST => Request::post(path),
Method::PUT => Request::put(path),
Method::PATCH => Request::patch(path),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(
m.to_string(),
),
))
}
}
.header("Content-Type", content_type)
.header("Accept", accepts)
.abort_signal(abort_signal.as_ref())
.body(url_params)
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(
e.to_string(),
))
})?,
abort_ctrl,
})))
}
fn try_new_req_streaming(
path: &str,
accepts: &str,
content_type: &str,
body: impl Stream<Item = Bytes> + 'static,
method: Method,
) -> Result<Self, E> {
// Only allow for methods with bodies
match method {
Method::POST | Method::PATCH | Method::PUT => {}
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(m.to_string()),
))
}
}
// TODO abort signal
let (request, abort_ctrl) =
streaming_request(path, accepts, content_type, body, method)
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(format!(
"{e:?}"
)))
})?;
Ok(Self(SendWrapper::new(RequestInner {
request,
abort_ctrl,
})))
}
}
fn streaming_request(
path: &str,
accepts: &str,
content_type: &str,
body: impl Stream<Item = Bytes> + 'static,
method: Method,
) -> Result<(Request, Option<AbortOnDrop>), JsValue> {
let (abort_ctrl, abort_signal) = abort_signal();
let stream = ReadableStream::from_stream(body.map(|bytes| {
let data = Uint8Array::from(bytes.as_ref());
let data = JsValue::from(data);
Ok(data) as Result<JsValue, JsValue>
}))
.into_raw();
let headers = Headers::new()?;
headers.append("Content-Type", content_type)?;
headers.append("Accept", accepts)?;
let init = RequestInit::new();
init.set_headers(&headers);
init.set_method(method.as_str());
init.set_signal(abort_signal.as_ref());
init.set_body(&stream);
// Chrome requires setting `duplex: "half"` on streaming requests
Reflect::set(
&init,
&JsValue::from_str("duplex"),
&JsValue::from_str("half"),
)?;
let req = web_sys::Request::new_with_str_and_init(path, &init)?;
Ok((Request::from(req), abort_ctrl))
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/request/reqwest.rs | server_fn/src/request/reqwest.rs | use super::ClientReq;
use crate::{
client::get_server_url,
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
};
use bytes::Bytes;
use futures::{Stream, StreamExt};
use reqwest::{
header::{ACCEPT, CONTENT_TYPE},
Body,
};
pub use reqwest::{multipart::Form, Client, Method, Request, Url};
use std::sync::LazyLock;
pub(crate) static CLIENT: LazyLock<Client> = LazyLock::new(Client::new);
impl<E> ClientReq<E> for Request
where
E: FromServerFnError,
{
type FormData = Form;
fn try_new_req_query(
path: &str,
content_type: &str,
accepts: &str,
query: &str,
method: Method,
) -> Result<Self, E> {
let url = format!("{}{}", get_server_url(), path);
let mut url = Url::try_from(url.as_str()).map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(e.to_string()))
})?;
url.set_query(Some(query));
let req = match method {
Method::GET => CLIENT.get(url),
Method::DELETE => CLIENT.delete(url),
Method::HEAD => CLIENT.head(url),
Method::POST => CLIENT.post(url),
Method::PATCH => CLIENT.patch(url),
Method::PUT => CLIENT.put(url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(m.to_string()),
))
}
}
.header(CONTENT_TYPE, content_type)
.header(ACCEPT, accepts)
.build()
.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Request(e.to_string()))
})?;
Ok(req)
}
fn try_new_req_text(
path: &str,
content_type: &str,
accepts: &str,
body: String,
method: Method,
) -> Result<Self, E> {
let url = format!("{}{}", get_server_url(), path);
match method {
Method::POST => CLIENT.post(url),
Method::PUT => CLIENT.put(url),
Method::PATCH => CLIENT.patch(url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(m.to_string()),
))
}
}
.header(CONTENT_TYPE, content_type)
.header(ACCEPT, accepts)
.body(body)
.build()
.map_err(|e| ServerFnErrorErr::Request(e.to_string()).into_app_error())
}
fn try_new_req_bytes(
path: &str,
content_type: &str,
accepts: &str,
body: Bytes,
method: Method,
) -> Result<Self, E> {
let url = format!("{}{}", get_server_url(), path);
match method {
Method::POST => CLIENT.post(url),
Method::PATCH => CLIENT.patch(url),
Method::PUT => CLIENT.put(url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(m.to_string()),
))
}
}
.header(CONTENT_TYPE, content_type)
.header(ACCEPT, accepts)
.body(body)
.build()
.map_err(|e| ServerFnErrorErr::Request(e.to_string()).into_app_error())
}
fn try_new_req_multipart(
path: &str,
accepts: &str,
body: Self::FormData,
method: Method,
) -> Result<Self, E> {
match method {
Method::POST => CLIENT.post(path),
Method::PUT => CLIENT.put(path),
Method::PATCH => CLIENT.patch(path),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(m.to_string()),
))
}
}
.header(ACCEPT, accepts)
.multipart(body)
.build()
.map_err(|e| ServerFnErrorErr::Request(e.to_string()).into_app_error())
}
fn try_new_req_form_data(
path: &str,
accepts: &str,
content_type: &str,
body: Self::FormData,
method: Method,
) -> Result<Self, E> {
match method {
Method::POST => CLIENT.post(path),
Method::PATCH => CLIENT.patch(path),
Method::PUT => CLIENT.put(path),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(m.to_string()),
))
}
}
.header(CONTENT_TYPE, content_type)
.header(ACCEPT, accepts)
.multipart(body)
.build()
.map_err(|e| ServerFnErrorErr::Request(e.to_string()).into_app_error())
}
fn try_new_req_streaming(
path: &str,
accepts: &str,
content_type: &str,
body: impl Stream<Item = Bytes> + Send + 'static,
method: Method,
) -> Result<Self, E> {
let url = format!("{}{}", get_server_url(), path);
let body = Body::wrap_stream(
body.map(|chunk| Ok(chunk) as Result<Bytes, ServerFnErrorErr>),
);
match method {
Method::POST => CLIENT.post(url),
Method::PUT => CLIENT.put(url),
Method::PATCH => CLIENT.patch(url),
m => {
return Err(E::from_server_fn_error(
ServerFnErrorErr::UnsupportedRequestMethod(m.to_string()),
))
}
}
.header(CONTENT_TYPE, content_type)
.header(ACCEPT, accepts)
.body(body)
.build()
.map_err(|e| ServerFnErrorErr::Request(e.to_string()).into_app_error())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/request/mod.rs | server_fn/src/request/mod.rs | use bytes::Bytes;
use futures::{Sink, Stream};
use http::Method;
use std::{borrow::Cow, future::Future};
/// Request types for Actix.
#[cfg(feature = "actix-no-default")]
pub mod actix;
/// Request types for Axum.
#[cfg(feature = "axum-no-default")]
pub mod axum;
/// Request types for the browser.
#[cfg(feature = "browser")]
pub mod browser;
#[cfg(feature = "generic")]
pub mod generic;
/// Request types for [`reqwest`].
#[cfg(feature = "reqwest")]
pub mod reqwest;
/// Represents a request as made by the client.
pub trait ClientReq<E>
where
Self: Sized,
{
/// The type used for URL-encoded form data in this client.
type FormData;
/// Attempts to construct a new request with query parameters.
fn try_new_req_query(
path: &str,
content_type: &str,
accepts: &str,
query: &str,
method: Method,
) -> Result<Self, E>;
/// Attempts to construct a new request with a text body.
fn try_new_req_text(
path: &str,
content_type: &str,
accepts: &str,
body: String,
method: Method,
) -> Result<Self, E>;
/// Attempts to construct a new request with a binary body.
fn try_new_req_bytes(
path: &str,
content_type: &str,
accepts: &str,
body: Bytes,
method: Method,
) -> Result<Self, E>;
/// Attempts to construct a new request with form data as the body.
fn try_new_req_form_data(
path: &str,
accepts: &str,
content_type: &str,
body: Self::FormData,
method: Method,
) -> Result<Self, E>;
/// Attempts to construct a new request with a multipart body.
fn try_new_req_multipart(
path: &str,
accepts: &str,
body: Self::FormData,
method: Method,
) -> Result<Self, E>;
/// Attempts to construct a new request with a streaming body.
fn try_new_req_streaming(
path: &str,
accepts: &str,
content_type: &str,
body: impl Stream<Item = Bytes> + Send + 'static,
method: Method,
) -> Result<Self, E>;
/// Attempts to construct a new `GET` request.
fn try_new_get(
path: &str,
content_type: &str,
accepts: &str,
query: &str,
) -> Result<Self, E> {
Self::try_new_req_query(path, content_type, accepts, query, Method::GET)
}
/// Attempts to construct a new `DELETE` request.
/// **Note**: Browser support for `DELETE` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_delete(
path: &str,
content_type: &str,
accepts: &str,
query: &str,
) -> Result<Self, E> {
Self::try_new_req_query(
path,
content_type,
accepts,
query,
Method::DELETE,
)
}
/// Attempts to construct a new `POST` request with a text body.
fn try_new_post(
path: &str,
content_type: &str,
accepts: &str,
body: String,
) -> Result<Self, E> {
Self::try_new_req_text(path, content_type, accepts, body, Method::POST)
}
/// Attempts to construct a new `PATCH` request with a text body.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_patch(
path: &str,
content_type: &str,
accepts: &str,
body: String,
) -> Result<Self, E> {
Self::try_new_req_text(path, content_type, accepts, body, Method::PATCH)
}
/// Attempts to construct a new `PUT` request with a text body.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_put(
path: &str,
content_type: &str,
accepts: &str,
body: String,
) -> Result<Self, E> {
Self::try_new_req_text(path, content_type, accepts, body, Method::PUT)
}
/// Attempts to construct a new `POST` request with a binary body.
fn try_new_post_bytes(
path: &str,
content_type: &str,
accepts: &str,
body: Bytes,
) -> Result<Self, E> {
Self::try_new_req_bytes(path, content_type, accepts, body, Method::POST)
}
/// Attempts to construct a new `PATCH` request with a binary body.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_patch_bytes(
path: &str,
content_type: &str,
accepts: &str,
body: Bytes,
) -> Result<Self, E> {
Self::try_new_req_bytes(
path,
content_type,
accepts,
body,
Method::PATCH,
)
}
/// Attempts to construct a new `PUT` request with a binary body.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_put_bytes(
path: &str,
content_type: &str,
accepts: &str,
body: Bytes,
) -> Result<Self, E> {
Self::try_new_req_bytes(path, content_type, accepts, body, Method::PUT)
}
/// Attempts to construct a new `POST` request with form data as the body.
fn try_new_post_form_data(
path: &str,
accepts: &str,
content_type: &str,
body: Self::FormData,
) -> Result<Self, E> {
Self::try_new_req_form_data(
path,
accepts,
content_type,
body,
Method::POST,
)
}
/// Attempts to construct a new `PATCH` request with form data as the body.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_patch_form_data(
path: &str,
accepts: &str,
content_type: &str,
body: Self::FormData,
) -> Result<Self, E> {
Self::try_new_req_form_data(
path,
accepts,
content_type,
body,
Method::PATCH,
)
}
/// Attempts to construct a new `PUT` request with form data as the body.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_put_form_data(
path: &str,
accepts: &str,
content_type: &str,
body: Self::FormData,
) -> Result<Self, E> {
Self::try_new_req_form_data(
path,
accepts,
content_type,
body,
Method::PUT,
)
}
/// Attempts to construct a new `POST` request with a multipart body.
fn try_new_post_multipart(
path: &str,
accepts: &str,
body: Self::FormData,
) -> Result<Self, E> {
Self::try_new_req_multipart(path, accepts, body, Method::POST)
}
/// Attempts to construct a new `PATCH` request with a multipart body.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_patch_multipart(
path: &str,
accepts: &str,
body: Self::FormData,
) -> Result<Self, E> {
Self::try_new_req_multipart(path, accepts, body, Method::PATCH)
}
/// Attempts to construct a new `PUT` request with a multipart body.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_put_multipart(
path: &str,
accepts: &str,
body: Self::FormData,
) -> Result<Self, E> {
Self::try_new_req_multipart(path, accepts, body, Method::PUT)
}
/// Attempts to construct a new `POST` request with a streaming body.
fn try_new_post_streaming(
path: &str,
accepts: &str,
content_type: &str,
body: impl Stream<Item = Bytes> + Send + 'static,
) -> Result<Self, E> {
Self::try_new_req_streaming(
path,
accepts,
content_type,
body,
Method::POST,
)
}
/// Attempts to construct a new `PATCH` request with a streaming body.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_patch_streaming(
path: &str,
accepts: &str,
content_type: &str,
body: impl Stream<Item = Bytes> + Send + 'static,
) -> Result<Self, E> {
Self::try_new_req_streaming(
path,
accepts,
content_type,
body,
Method::PATCH,
)
}
/// Attempts to construct a new `PUT` request with a streaming body.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
fn try_new_put_streaming(
path: &str,
accepts: &str,
content_type: &str,
body: impl Stream<Item = Bytes> + Send + 'static,
) -> Result<Self, E> {
Self::try_new_req_streaming(
path,
accepts,
content_type,
body,
Method::PUT,
)
}
}
/// Represents the request as received by the server.
pub trait Req<Error, InputStreamError = Error, OutputStreamError = Error>
where
Self: Sized,
{
/// The response type for websockets.
type WebsocketResponse: Send;
/// Returns the query string of the request’s URL, starting after the `?`.
fn as_query(&self) -> Option<&str>;
/// Returns the `Content-Type` header, if any.
fn to_content_type(&self) -> Option<Cow<'_, str>>;
/// Returns the `Accepts` header, if any.
fn accepts(&self) -> Option<Cow<'_, str>>;
/// Returns the `Referer` header, if any.
fn referer(&self) -> Option<Cow<'_, str>>;
/// Attempts to extract the body of the request into [`Bytes`].
fn try_into_bytes(
self,
) -> impl Future<Output = Result<Bytes, Error>> + Send;
/// Attempts to convert the body of the request into a string.
fn try_into_string(
self,
) -> impl Future<Output = Result<String, Error>> + Send;
/// Attempts to convert the body of the request into a stream of bytes.
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static, Error>;
/// Attempts to convert the body of the request into a websocket handle.
#[allow(clippy::type_complexity)]
fn try_into_websocket(
self,
) -> impl Future<
Output = Result<
(
impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
impl Sink<Bytes> + Send + 'static,
Self::WebsocketResponse,
),
Error,
>,
> + Send;
}
/// A mocked request type that can be used in place of the actual server request,
/// when compiling for the browser.
pub struct BrowserMockReq;
impl<Error, InputStreamError, OutputStreamError>
Req<Error, InputStreamError, OutputStreamError> for BrowserMockReq
where
Error: Send + 'static,
InputStreamError: Send + 'static,
OutputStreamError: Send + 'static,
{
type WebsocketResponse = crate::response::BrowserMockRes;
fn as_query(&self) -> Option<&str> {
unreachable!()
}
fn to_content_type(&self) -> Option<Cow<'_, str>> {
unreachable!()
}
fn accepts(&self) -> Option<Cow<'_, str>> {
unreachable!()
}
fn referer(&self) -> Option<Cow<'_, str>> {
unreachable!()
}
async fn try_into_bytes(self) -> Result<Bytes, Error> {
unreachable!()
}
async fn try_into_string(self) -> Result<String, Error> {
unreachable!()
}
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send, Error> {
Ok(futures::stream::once(async { unreachable!() }))
}
async fn try_into_websocket(
self,
) -> Result<
(
impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
impl Sink<Bytes> + Send + 'static,
Self::WebsocketResponse,
),
Error,
> {
#[allow(unreachable_code)]
Err::<
(
futures::stream::Once<std::future::Ready<Result<Bytes, Bytes>>>,
futures::sink::Drain<Bytes>,
Self::WebsocketResponse,
),
_,
>(unreachable!())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/request/spin.rs | server_fn/src/request/spin.rs | use crate::{error::ServerFnError, request::Req};
use axum::body::{Body, Bytes};
use futures::{Stream, StreamExt};
use http::{
header::{ACCEPT, CONTENT_TYPE, REFERER},
Request,
};
use http_body_util::BodyExt;
use std::borrow::Cow;
impl<E> Req<E> for IncomingRequest
where
CustErr: 'static,
{
fn as_query(&self) -> Option<&str> {
self.uri().query()
}
fn to_content_type(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(CONTENT_TYPE)
.map(|h| String::from_utf8_lossy(h.as_bytes()))
}
fn accepts(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(ACCEPT)
.map(|h| String::from_utf8_lossy(h.as_bytes()))
}
fn referer(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(REFERER)
.map(|h| String::from_utf8_lossy(h.as_bytes()))
}
async fn try_into_bytes(self) -> Result<Bytes, E> {
let (_parts, body) = self.into_parts();
body.collect().await.map(|c| c.to_bytes()).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into()
})
}
async fn try_into_string(self) -> Result<String, E> {
let bytes = self.try_into_bytes().await?;
String::from_utf8(bytes.to_vec()).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into()
})
}
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static, E>
{
Ok(self.into_body().into_data_stream().map(|chunk| {
chunk.map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
.ser()
})
}))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/request/generic.rs | server_fn/src/request/generic.rs | //! This module uses platform-agnostic abstractions
//! allowing users to run server functions on a wide range of
//! platforms.
//!
//! The crates in use in this crate are:
//!
//! * `bytes`: platform-agnostic manipulation of bytes.
//! * `http`: low-dependency HTTP abstractions' *front-end*.
//!
//! # Users
//!
//! * `wasm32-wasip*` integration crate `leptos_wasi` is using this
//! crate under the hood.
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::Req,
};
use bytes::Bytes;
use futures::{
stream::{self, Stream},
Sink, StreamExt,
};
use http::{Request, Response};
use std::borrow::Cow;
impl<Error, InputStreamError, OutputStreamError>
Req<Error, InputStreamError, OutputStreamError> for Request<Bytes>
where
Error: FromServerFnError + Send,
InputStreamError: FromServerFnError + Send,
OutputStreamError: FromServerFnError + Send,
{
type WebsocketResponse = Response<Bytes>;
async fn try_into_bytes(self) -> Result<Bytes, Error> {
Ok(self.into_body())
}
async fn try_into_string(self) -> Result<String, Error> {
String::from_utf8(self.into_body().into()).map_err(|err| {
ServerFnErrorErr::Deserialization(err.to_string()).into_app_error()
})
}
fn try_into_stream(
self,
) -> Result<impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static, Error>
{
Ok(stream::iter(self.into_body())
.ready_chunks(16)
.map(|chunk| Ok(Bytes::from(chunk))))
}
fn to_content_type(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(http::header::CONTENT_TYPE)
.map(|val| String::from_utf8_lossy(val.as_bytes()))
}
fn accepts(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(http::header::ACCEPT)
.map(|val| String::from_utf8_lossy(val.as_bytes()))
}
fn referer(&self) -> Option<Cow<'_, str>> {
self.headers()
.get(http::header::REFERER)
.map(|val| String::from_utf8_lossy(val.as_bytes()))
}
fn as_query(&self) -> Option<&str> {
self.uri().query()
}
async fn try_into_websocket(
self,
) -> Result<
(
impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
impl Sink<Bytes> + Send + 'static,
Self::WebsocketResponse,
),
Error,
> {
Err::<
(
futures::stream::Once<std::future::Ready<Result<Bytes, Bytes>>>,
futures::sink::Drain<Bytes>,
Self::WebsocketResponse,
),
_,
>(Error::from_server_fn_error(
crate::ServerFnErrorErr::Response(
"Websockets are not supported on this platform.".to_string(),
),
))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/server_macro.rs | server_fn/tests/server_macro.rs | // The trybuild output has slightly different error message output for
// different combinations of features. Since tests are run with `test-all-features`
// multiple combinations of features are tested. This ensures this file is only
// run when **only** the browser feature is enabled.
#![cfg(all(
rustc_nightly,
feature = "browser",
not(any(
feature = "postcard",
feature = "multipart",
feature = "serde-lite",
feature = "cbor",
feature = "msgpack",
feature = "bitcode",
))
))]
#[test]
fn aliased_results() {
let t = trybuild::TestCases::new();
t.pass("tests/valid/*.rs");
t.compile_fail("tests/invalid/*.rs")
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/valid/aliased_return_full.rs | server_fn/tests/valid/aliased_return_full.rs | use server_fn_macro_default::server;
use server_fn::error::ServerFnError;
type FullAlias = Result<String, ServerFnError>;
#[server]
pub async fn full_alias_result() -> FullAlias {
Ok("hello".to_string())
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/valid/custom_error_aliased_return_part.rs | server_fn/tests/valid/custom_error_aliased_return_part.rs | use server_fn::{
codec::JsonEncoding,
error::{FromServerFnError, ServerFnErrorErr},
};
use server_fn_macro_default::server;
#[derive(
Debug, thiserror::Error, Clone, serde::Serialize, serde::Deserialize,
)]
pub enum CustomError {
#[error("error a")]
ErrorA,
#[error("error b")]
ErrorB,
}
impl FromServerFnError for CustomError {
type Encoder = JsonEncoding;
fn from_server_fn_error(_: ServerFnErrorErr) -> Self {
Self::ErrorA
}
}
type PartAlias<T> = Result<T, CustomError>;
#[server]
pub async fn part_alias_result() -> PartAlias<String> {
Ok("hello".to_string())
}
fn main() {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/valid/aliased_return_part.rs | server_fn/tests/valid/aliased_return_part.rs | use server_fn_macro_default::server;
use server_fn::error::ServerFnError;
type PartAlias<T> = Result<T, ServerFnError>;
#[server]
pub async fn part_alias_result() -> PartAlias<String> {
Ok("hello".to_string())
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/valid/aliased_return_none.rs | server_fn/tests/valid/aliased_return_none.rs | use server_fn_macro_default::server;
use server_fn::error::ServerFnError;
#[server]
pub async fn no_alias_result() -> Result<String, ServerFnError> {
Ok("hello".to_string())
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/valid/custom_error_aliased_return_none.rs | server_fn/tests/valid/custom_error_aliased_return_none.rs | use server_fn::{
codec::JsonEncoding,
error::{FromServerFnError, ServerFnErrorErr},
};
use server_fn_macro_default::server;
#[derive(
Debug, thiserror::Error, Clone, serde::Serialize, serde::Deserialize,
)]
pub enum CustomError {
#[error("error a")]
ErrorA,
#[error("error b")]
ErrorB,
}
impl FromServerFnError for CustomError {
type Encoder = JsonEncoding;
fn from_server_fn_error(_: ServerFnErrorErr) -> Self {
Self::ErrorA
}
}
#[server]
pub async fn no_alias_result() -> Result<String, CustomError> {
Ok("hello".to_string())
}
fn main() {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/valid/custom_error_aliased_return_full.rs | server_fn/tests/valid/custom_error_aliased_return_full.rs | use server_fn::{
codec::JsonEncoding,
error::{FromServerFnError, ServerFnErrorErr},
};
use server_fn_macro_default::server;
#[derive(
Debug, thiserror::Error, Clone, serde::Serialize, serde::Deserialize,
)]
pub enum CustomError {
#[error("error a")]
ErrorA,
#[error("error b")]
ErrorB,
}
impl FromServerFnError for CustomError {
type Encoder = JsonEncoding;
fn from_server_fn_error(_: ServerFnErrorErr) -> Self {
Self::ErrorA
}
}
type FullAlias = Result<String, CustomError>;
#[server]
pub async fn full_alias_result() -> FullAlias {
Ok("hello".to_string())
}
fn main() {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/invalid/aliased_return_full.rs | server_fn/tests/invalid/aliased_return_full.rs | use server_fn_macro_default::server;
#[derive(Debug, thiserror::Error, Clone, serde::Serialize, serde::Deserialize)]
pub enum InvalidError {
#[error("error a")]
A,
}
type FullAlias = Result<String, InvalidError>;
#[server]
pub async fn full_alias_result() -> FullAlias {
Ok("hello".to_string())
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/invalid/no_return.rs | server_fn/tests/invalid/no_return.rs | use server_fn_macro_default::server;
#[server]
pub async fn no_return() {}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/invalid/not_async.rs | server_fn/tests/invalid/not_async.rs | use server_fn_macro_default::server;
use server_fn::error::ServerFnError;
#[server]
pub fn not_async() -> Result<String, ServerFnError> {
Ok("hello".to_string())
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/invalid/aliased_return_part.rs | server_fn/tests/invalid/aliased_return_part.rs | use server_fn_macro_default::server;
#[derive(Debug, thiserror::Error, Clone, serde::Serialize, serde::Deserialize)]
pub enum InvalidError {
#[error("error a")]
A,
}
type PartAlias<T> = Result<T, InvalidError>;
#[server]
pub async fn part_alias_result() -> PartAlias<String> {
Ok("hello".to_string())
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/invalid/aliased_return_none.rs | server_fn/tests/invalid/aliased_return_none.rs | use server_fn_macro_default::server;
#[derive(Debug, thiserror::Error, Clone, serde::Serialize, serde::Deserialize)]
pub enum InvalidError {
#[error("error a")]
A,
}
#[server]
pub async fn no_alias_result() -> Result<String, InvalidError> {
Ok("hello".to_string())
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/invalid/empty_return.rs | server_fn/tests/invalid/empty_return.rs | use server_fn_macro_default::server;
#[server]
pub async fn empty_return() -> () {
()
}
fn main() {} | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/tests/invalid/not_result.rs | server_fn/tests/invalid/not_result.rs | use server_fn::{
codec::JsonEncoding,
error::{FromServerFnError, ServerFnErrorErr},
};
use server_fn_macro_default::server;
#[derive(
Debug, thiserror::Error, Clone, serde::Serialize, serde::Deserialize,
)]
pub enum CustomError {
#[error("error a")]
A,
#[error("error b")]
B,
}
impl FromServerFnError for CustomError {
type Encoder = JsonEncoding;
fn from_server_fn_error(_: ServerFnErrorErr) -> Self {
Self::A
}
}
#[server]
pub async fn full_alias_result() -> CustomError {
CustomError::A
}
fn main() {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/server_fn_macro_default/src/lib.rs | server_fn/server_fn_macro_default/src/lib.rs | #![forbid(unsafe_code)]
#![deny(missing_docs)]
//! This crate contains the default implementation of the #[macro@crate::server] macro without additional context from the server.
//! See the [server_fn_macro] crate for more information.
use proc_macro::TokenStream;
use server_fn_macro::server_macro_impl;
use syn::__private::ToTokens;
/// Declares that a function is a [server function](https://docs.rs/server_fn/).
/// This means that its body will only run on the server, i.e., when the `ssr`
/// feature is enabled on this crate.
///
/// ## Usage
/// ```rust,ignore
/// #[server]
/// pub async fn blog_posts(
/// category: String,
/// ) -> Result<Vec<BlogPost>, ServerFnError> {
/// let posts = load_posts(&category).await?;
/// // maybe do some other work
/// Ok(posts)
/// }
/// ```
///
/// ## Named Arguments
///
/// You can any combination of the following named arguments:
/// - `name`: sets the identifier for the server function’s type, which is a struct created
/// to hold the arguments (defaults to the function identifier in PascalCase)
/// - `prefix`: a prefix at which the server function handler will be mounted (defaults to `/api`)
/// - `endpoint`: specifies the exact path at which the server function handler will be mounted,
/// relative to the prefix (defaults to the function name followed by unique hash)
/// - `input`: the encoding for the arguments (defaults to `PostUrl`)
/// - `input_derive`: a list of derives to be added on the generated input struct (defaults to `(Clone, serde::Serialize, serde::Deserialize)` if `input` is set to a custom struct, won't have an effect otherwise)
/// - `output`: the encoding for the response (defaults to `Json`)
/// - `client`: a custom `Client` implementation that will be used for this server fn
/// - `encoding`: (legacy, may be deprecated in future) specifies the encoding, which may be one
/// of the following (not case sensitive)
/// - `"Url"`: `POST` request with URL-encoded arguments and JSON response
/// - `"GetUrl"`: `GET` request with URL-encoded arguments and JSON response
/// - `"Cbor"`: `POST` request with CBOR-encoded arguments and response
/// - `"GetCbor"`: `GET` request with URL-encoded arguments and CBOR response
/// - `req` and `res` specify the HTTP request and response types to be used on the server (these
/// should usually only be necessary if you are integrating with a server other than Actix/Axum)
/// ```rust,ignore
/// #[server(
/// name = SomeStructName,
/// prefix = "/my_api",
/// endpoint = "my_fn",
/// input = Cbor,
/// output = Json
/// )]
/// pub async fn my_wacky_server_fn(input: Vec<String>) -> Result<usize, ServerFnError> {
/// todo!()
/// }
///
/// // expands to
/// #[derive(Deserialize, Serialize)]
/// struct SomeStructName {
/// input: Vec<String>
/// }
///
/// impl ServerFn for SomeStructName {
/// const PATH: &'static str = "/my_api/my_fn";
///
/// // etc.
/// }
/// ```
#[proc_macro_attribute]
pub fn server(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
match server_macro_impl(
args.into(),
s.into(),
Some(syn::parse_quote!(server_fn)),
option_env!("SERVER_FN_PREFIX").unwrap_or("/api"),
None,
None,
) {
Err(e) => e.to_compile_error().into(),
Ok(s) => s.to_token_stream().into(),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/build.rs | leptos/build.rs | use rustc_version::{version_meta, Channel};
fn main() {
let target = std::env::var("TARGET").unwrap_or_default();
// Set cfg flags depending on release channel
if matches!(version_meta().unwrap().channel, Channel::Nightly) {
println!("cargo:rustc-cfg=rustc_nightly");
}
// Set cfg flag for getrandom wasm_js
if target == "wasm32-unknown-unknown" {
// Set a custom cfg flag for wasm builds
println!("cargo:rustc-cfg=getrandom_backend=\"wasm_js\"");
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/subsecond.rs | leptos/src/subsecond.rs | use dioxus_devtools::DevserverMsg;
use wasm_bindgen::{prelude::Closure, JsCast};
use web_sys::{js_sys::JsString, MessageEvent, WebSocket};
/// Sets up a websocket connect to the `dx` CLI, waiting for incoming hot-patching messages
/// and patching the WASM binary appropriately.
//
// Note: This is a stripped-down version of Dioxus's `make_ws` from `dioxus_web`
// It's essentially copy-pasted here because it's not pub there.
// Would love to just take a dependency on that to be able to use it and deduplicate.
//
// https://github.com/DioxusLabs/dioxus/blob/main/packages/web/src/devtools.rs#L36
pub fn connect_to_hot_patch_messages() {
// Get the location of the devserver, using the current location plus the /_dioxus path
// The idea here being that the devserver is always located on the /_dioxus behind a proxy
let location = web_sys::window().unwrap().location();
let url = format!(
"{protocol}//{host}/_dioxus?build_id={build_id}",
protocol = match location.protocol().unwrap() {
prot if prot == "https:" => "wss:",
_ => "ws:",
},
host = location.host().unwrap(),
build_id = dioxus_cli_config::build_id(),
);
let ws = WebSocket::new(&url).unwrap();
ws.set_onmessage(Some(
Closure::<dyn FnMut(MessageEvent)>::new(move |e: MessageEvent| {
let Ok(text) = e.data().dyn_into::<JsString>() else {
return;
};
// The devserver messages have some &'static strs in them, so we need to leak the source string
let string: String = text.into();
let string = Box::leak(string.into_boxed_str());
if let Ok(DevserverMsg::HotReload(msg)) =
serde_json::from_str::<DevserverMsg>(string)
{
if let Some(jump_table) = msg.jump_table.as_ref().cloned() {
if msg.for_build_id == Some(dioxus_cli_config::build_id()) {
let our_pid = if cfg!(target_family = "wasm") {
None
} else {
Some(std::process::id())
};
if msg.for_pid == our_pid {
unsafe { subsecond::apply_patch(jump_table) }
.unwrap();
}
}
}
}
})
.into_js_value()
.as_ref()
.unchecked_ref(),
));
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/animated_show.rs | leptos/src/animated_show.rs | use crate::{children::ChildrenFn, component, control_flow::Show, IntoView};
use core::time::Duration;
use leptos_dom::helpers::TimeoutHandle;
use leptos_macro::view;
use reactive_graph::{
effect::RenderEffect,
owner::{on_cleanup, StoredValue},
signal::RwSignal,
traits::{Get, GetUntracked, GetValue, Set, SetValue},
wrappers::read::Signal,
};
use tachys::prelude::*;
/// A component that will show its children when the `when` condition is `true`.
/// Additionally, you need to specify a `hide_delay`. If the `when` condition changes to `false`,
/// the unmounting of the children will be delayed by the specified Duration.
/// If you provide the optional `show_class` and `hide_class`, you can create very easy mount /
/// unmount animations.
///
/// ```rust
/// # use core::time::Duration;
/// # use leptos::prelude::*;
/// # #[component]
/// # pub fn App() -> impl IntoView {
/// let show = RwSignal::new(false);
///
/// view! {
/// <div
/// class="hover-me"
/// on:mouseenter=move |_| show.set(true)
/// on:mouseleave=move |_| show.set(false)
/// >
/// "Hover Me"
/// </div>
///
/// <AnimatedShow
/// when=show
/// show_class="fade-in-1000"
/// hide_class="fade-out-1000"
/// hide_delay=Duration::from_millis(1000)
/// >
/// <div class="here-i-am">
/// "Here I Am!"
/// </div>
/// </AnimatedShow>
/// }
/// # }
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
#[component]
pub fn AnimatedShow(
/// The components Show wraps
children: ChildrenFn,
/// If the component should show or not
#[prop(into)]
when: Signal<bool>,
/// Optional CSS class to apply if `when == true`
#[prop(optional)]
show_class: &'static str,
/// Optional CSS class to apply if `when == false`
#[prop(optional)]
hide_class: &'static str,
/// The timeout after which the component will be unmounted if `when == false`
hide_delay: Duration,
) -> impl IntoView {
let handle: StoredValue<Option<TimeoutHandle>> = StoredValue::new(None);
let cls = RwSignal::new(if when.get_untracked() {
show_class
} else {
hide_class
});
let show = RwSignal::new(when.get_untracked());
let eff = RenderEffect::new(move |_| {
if when.get() {
// clear any possibly active timer
if let Some(h) = handle.get_value() {
h.clear();
}
cls.set(show_class);
show.set(true);
} else {
cls.set(hide_class);
let h = leptos_dom::helpers::set_timeout_with_handle(
move || show.set(false),
hide_delay,
)
.expect("set timeout in AnimatedShow");
handle.set_value(Some(h));
}
});
on_cleanup(move || {
if let Some(Some(h)) = handle.try_get_value() {
h.clear();
}
drop(eff);
});
view! {
<Show when=move || show.get() fallback=|| ()>
<div class=move || cls.get()>{children()}</div>
</Show>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/lib.rs | leptos/src/lib.rs | #![deny(missing_docs)]
//! # About Leptos
//!
//! Leptos is a full-stack framework for building web applications in Rust. You can use it to build
//! - single-page apps (SPAs) rendered entirely in the browser, using client-side routing and loading
//! or mutating data via async requests to the server.
//! - multi-page apps (MPAs) rendered on the server, managing navigation, data, and mutations via
//! web-standard `<a>` and `<form>` tags.
//! - progressively-enhanced single-page apps that are rendered on the server and then hydrated on the client,
//! enhancing your `<a>` and `<form>` navigations and mutations seamlessly when WASM is available.
//!
//! And you can do all three of these **using the same Leptos code**.
//!
//! Take a look at the [Leptos Book](https://leptos-rs.github.io/leptos/) for a walkthrough of the framework.
//! Join us on our [Discord Channel](https://discord.gg/v38Eef6sWG) to see what the community is building.
//! Explore our [Examples](https://github.com/leptos-rs/leptos/tree/main/examples) to see Leptos in action.
//!
//! # Learning by Example
//!
//! If you want to see what Leptos is capable of, check out
//! the [examples](https://github.com/leptos-rs/leptos/tree/main/examples):
//!
//! - **[`counter`]** is the classic counter example, showing the basics of client-side rendering and reactive DOM updates.
//! - **[`counter_without_macros`]** adapts the counter example to use the builder pattern for the UI and avoids other macros,
//! instead showing the code that Leptos generates.
//! - **[`counters`]** introduces parent-child communication via contexts, and the [`<For/>`](leptos::prelude::For) component
//! for efficient keyed list updates.
//! - **[`error_boundary`]** shows how to use [`Result`] types to handle errors.
//! - **[`parent_child`]** shows four different ways a parent component can communicate with a child, including passing a closure,
//! context, and more.
//! - **[`fetch`]** introduces [`Resource`](leptos::prelude::Resource)s, which allow you to integrate arbitrary `async` code like an
//! HTTP request within your reactive code.
//! - **[`router`]** shows how to use Leptos’s nested router to enable client-side navigation and route-specific, reactive data loading.
//! - **[`slots`]** shows how to use slots on components.
//! - **[`spread`]** shows how the spread syntax can be used to spread data and/or event handlers onto elements.
//! - **[`counter_isomorphic`]** shows different methods of interaction with a stateful server, including server functions,
//! server actions, forms, and server-sent events (SSE).
//! - **[`todomvc`]** shows the basics of building an isomorphic web app. Both the server and the client import the same app code.
//! The server renders the app directly to an HTML string, and the client hydrates that HTML to make it interactive.
//! You might also want to see how we use [`Effect::new`](leptos::prelude::Effect) to
//! [serialize JSON to `localStorage`](https://github.com/leptos-rs/leptos/blob/20af4928b2fffe017408d3f4e7330db22cf68277/examples/todomvc/src/lib.rs#L191-L209)
//! and [reactively call DOM methods](https://github.com/leptos-rs/leptos/blob/16f084a71268ac325fbc4a5e50c260df185eadb6/examples/todomvc/src/lib.rs#L292-L296)
//! on [references to elements](https://github.com/leptos-rs/leptos/blob/20af4928b2fffe017408d3f4e7330db22cf68277/examples/todomvc/src/lib.rs#L228).
//! - **[`hackernews`]** and **[`hackernews_axum`]** integrate calls to a real external REST API, routing, server-side rendering and
//! hydration to create a fully-functional application that works as intended even before WASM has loaded and begun to run.
//! - **[`todo_app_sqlite`]** and **[`todo_app_sqlite_axum`]** show how to build a full-stack app using server functions and
//! database connections.
//! - **[`tailwind`]** shows how to integrate TailwindCSS with `trunk` for CSR.
//!
//! [`counter`]: https://github.com/leptos-rs/leptos/tree/main/examples/counter
//! [`counter_without_macros`]: https://github.com/leptos-rs/leptos/tree/main/examples/counter_without_macros
//! [`counters`]: https://github.com/leptos-rs/leptos/tree/main/examples/counters
//! [`error_boundary`]: https://github.com/leptos-rs/leptos/tree/main/examples/error_boundary
//! [`parent_child`]: https://github.com/leptos-rs/leptos/tree/main/examples/parent_child
//! [`fetch`]: https://github.com/leptos-rs/leptos/tree/main/examples/fetch
//! [`router`]: https://github.com/leptos-rs/leptos/tree/main/examples/router
//! [`slots`]: https://github.com/leptos-rs/leptos/tree/main/examples/slots
//! [`spread`]: https://github.com/leptos-rs/leptos/tree/main/examples/spread
//! [`counter_isomorphic`]: https://github.com/leptos-rs/leptos/tree/main/examples/counter_isomorphic
//! [`todomvc`]: https://github.com/leptos-rs/leptos/tree/main/examples/todomvc
//! [`hackernews`]: https://github.com/leptos-rs/leptos/tree/main/examples/hackernews
//! [`hackernews_axum`]: https://github.com/leptos-rs/leptos/tree/main/examples/hackernews_axum
//! [`todo_app_sqlite`]: https://github.com/leptos-rs/leptos/tree/main/examples/todo_app_sqlite
//! [`todo_app_sqlite_axum`]: https://github.com/leptos-rs/leptos/tree/main/examples/todo_app_sqlite_axum
//! [`tailwind`]: https://github.com/leptos-rs/leptos/tree/main/examples/tailwind_csr
//!
//! Details on how to run each example can be found in its README.
//!
//! # Quick Links
//!
//! Here are links to the most important sections of the docs:
//! - **Reactivity**: the [`reactive_graph`] overview, and more details in
//! + signals: [`signal`](leptos::prelude::signal), [`ReadSignal`](leptos::prelude::ReadSignal),
//! [`WriteSignal`](leptos::prelude::WriteSignal) and [`RwSignal`](leptos::prelude::RwSignal).
//! + computations: [`Memo`](leptos::prelude::Memo).
//! + `async` interop: [`Resource`](leptos::prelude::Resource) for loading data using `async` functions
//! and [`Action`](leptos::prelude::Action) to mutate data or imperatively call `async` functions.
//! + reactions: [`Effect`](leptos::prelude::Effect) and [`RenderEffect`](leptos::prelude::RenderEffect).
//! - **Templating/Views**: the [`view`] macro and [`IntoView`] trait.
//! - **Routing**: the [`leptos_router`](https://docs.rs/leptos_router/latest/leptos_router/) crate
//! - **Server Functions**: the [`server`](macro@leptos::prelude::server) macro and [`ServerAction`](leptos::prelude::ServerAction).
//!
//! # Feature Flags
//!
//! - **`nightly`**: On `nightly` Rust, enables the function-call syntax for signal getters and setters.
//! Also enables some experimental optimizations that improve the handling of static strings and
//! the performance of the `template! {}` macro.
//! - **`csr`** Client-side rendering: Generate DOM nodes in the browser.
//! - **`ssr`** Server-side rendering: Generate an HTML string (typically on the server).
//! - **`islands`** Activates “islands mode,” in which components are not made interactive on the
//! client unless they use the `#[island]` macro.
//! - **`hydrate`** Hydration: use this to add interactivity to an SSRed Leptos app.
//! - **`nonce`** Adds support for nonces to be added as part of a Content Security Policy.
//! - **`rkyv`** In SSR/hydrate mode, enables using [`rkyv`](https://docs.rs/rkyv/latest/rkyv/) to serialize resources.
//! - **`tracing`** Adds support for [`tracing`](https://docs.rs/tracing/latest/tracing/).
//! - **`trace-component-props`** Adds `tracing` support for component props.
//! - **`delegation`** Uses event delegation rather than the browser’s native event handling
//! system. (This improves the performance of creating large numbers of elements simultaneously,
//! in exchange for occasional edge cases in which events behave differently from native browser
//! events.)
//! - **`rustls`** Use `rustls` for server functions.
//!
//! **Important Note:** You must enable one of `csr`, `hydrate`, or `ssr` to tell Leptos
//! which mode your app is operating in. You should only enable one of these per build target,
//! i.e., you should not have both `hydrate` and `ssr` enabled for your server binary, only `ssr`.
//!
//! # A Simple Counter
//!
//! ```rust
//! use leptos::prelude::*;
//!
//! #[component]
//! pub fn SimpleCounter(initial_value: i32) -> impl IntoView {
//! // create a reactive signal with the initial value
//! let (value, set_value) = signal(initial_value);
//!
//! // create event handlers for our buttons
//! // note that `value` and `set_value` are `Copy`, so it's super easy to move them into closures
//! let clear = move |_| set_value.set(0);
//! let decrement = move |_| *set_value.write() -= 1;
//! let increment = move |_| *set_value.write() += 1;
//!
//! view! {
//! <div>
//! <button on:click=clear>"Clear"</button>
//! <button on:click=decrement>"-1"</button>
//! <span>"Value: " {value} "!"</span>
//! <button on:click=increment>"+1"</button>
//! </div>
//! }
//! }
//! ```
//!
//! Leptos is easy to use with [Trunk](https://trunkrs.dev/) (or with a simple wasm-bindgen setup):
//!
//! ```rust
//! use leptos::{mount::mount_to_body, prelude::*};
//!
//! #[component]
//! fn SimpleCounter(initial_value: i32) -> impl IntoView {
//! // ...
//! # _ = initial_value;
//! }
//!
//! pub fn main() {
//! # if false { // can't run in doctest
//! mount_to_body(|| view! { <SimpleCounter initial_value=3 /> })
//! # }
//! }
//! ```
#![cfg_attr(all(feature = "nightly", rustc_nightly), feature(fn_traits))]
#![cfg_attr(all(feature = "nightly", rustc_nightly), feature(unboxed_closures))]
extern crate self as leptos;
/// Exports all the core types of the library.
pub mod prelude {
// Traits
// These should always be exported from the prelude
pub use reactive_graph::prelude::*;
pub use tachys::prelude::*;
// Structs
// In the future, maybe we should remove this blanket export
// However, it is definitely useful relative to looking up every struct etc.
mod export_types {
#[cfg(feature = "nonce")]
pub use crate::nonce::*;
pub use crate::{
callback::*, children::*, component::*, control_flow::*, error::*,
form::*, hydration::*, into_view::*, mount::*, suspense::*,
text_prop::*,
};
pub use leptos_config::*;
pub use leptos_dom::helpers::*;
pub use leptos_macro::*;
pub use leptos_server::*;
pub use oco_ref::*;
pub use reactive_graph::{
actions::*,
computed::*,
effect::*,
graph::untrack,
owner::*,
signal::*,
wrappers::{read::*, write::*},
};
pub use server_fn::{
self,
error::{FromServerFnError, ServerFnError, ServerFnErrorErr},
};
pub use tachys::{
reactive_graph::{bind::BindAttribute, node_ref::*, Suspend},
view::{fragment::Fragment, template::ViewTemplate},
};
}
pub use export_types::*;
}
/// Components used for working with HTML forms, like `<ActionForm>`.
pub mod form;
/// A standard way to wrap functions and closures to pass them to components.
pub use reactive_graph::callback;
/// Types that can be passed as the `children` prop of a component.
pub mod children;
/// Wrapper for intercepting component attributes.
pub mod attribute_interceptor;
#[doc(hidden)]
/// Traits used to implement component constructors.
pub mod component;
mod error_boundary;
/// Tools for handling errors.
pub mod error {
pub use crate::error_boundary::*;
pub use throw_error::*;
}
/// Control-flow components like `<Show>`, `<For>`, and `<Await>`.
pub mod control_flow {
pub use crate::{
animated_show::*, await_::*, for_loop::*, show::*, show_let::*,
};
}
mod animated_show;
mod await_;
mod for_loop;
mod show;
mod show_let;
/// A component that allows rendering a component somewhere else.
pub mod portal;
/// Components to enable server-side rendering and client-side hydration.
pub mod hydration;
/// Utilities for exporting nonces to be used for a Content Security Policy.
#[cfg(feature = "nonce")]
pub mod nonce;
/// Components to load asynchronous data.
pub mod suspense {
pub use crate::{suspense_component::*, transition::*};
}
#[macro_use]
mod suspense_component;
/// Types for reactive string properties for components.
pub mod text_prop;
mod transition;
pub use leptos_macro::*;
#[doc(inline)]
pub use server_fn;
#[doc(hidden)]
pub use typed_builder;
#[doc(hidden)]
pub use typed_builder_macro;
mod into_view;
pub use into_view::IntoView;
#[doc(inline)]
pub use leptos_dom;
mod provider;
#[doc(inline)]
pub use tachys;
/// Tools to mount an application to the DOM, or to hydrate it from server-rendered HTML.
pub mod mount;
#[doc(inline)]
pub use leptos_config as config;
#[doc(inline)]
pub use oco_ref as oco;
mod from_form_data;
#[doc(inline)]
pub use either_of as either;
#[doc(inline)]
pub use reactive_graph as reactive;
/// Provide and access data along the reactive graph, sharing data without directly passing arguments.
pub mod context {
pub use crate::provider::*;
pub use reactive_graph::owner::{provide_context, use_context};
}
#[doc(inline)]
pub use leptos_server as server;
/// HTML attribute types.
#[doc(inline)]
pub use tachys::html::attribute as attr;
/// HTML element types.
#[doc(inline)]
pub use tachys::html::element as html;
/// HTML event types.
#[doc(no_inline)]
pub use tachys::html::event as ev;
/// MathML element types.
#[doc(inline)]
pub use tachys::mathml as math;
/// SVG element types.
#[doc(inline)]
pub use tachys::svg;
#[cfg(feature = "subsecond")]
/// Utilities for using binary hot-patching with [`subsecond`].
pub mod subsecond;
/// Utilities for simple isomorphic logging to the console or terminal.
pub mod logging {
pub use leptos_dom::{
debug_error, debug_log, debug_warn, error, log, warn,
};
}
/// Utilities for working with asynchronous tasks.
pub mod task {
use any_spawner::Executor;
use reactive_graph::computed::ScopedFuture;
use std::future::Future;
/// Spawns a thread-safe [`Future`].
///
/// This will be run with the current reactive owner and observer using a [`ScopedFuture`].
#[track_caller]
#[inline(always)]
pub fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
let fut = ScopedFuture::new(fut);
#[cfg(not(target_family = "wasm"))]
Executor::spawn(fut);
#[cfg(target_family = "wasm")]
Executor::spawn_local(fut);
}
/// Spawns a [`Future`] that cannot be sent across threads.
#[track_caller]
#[inline(always)]
pub fn spawn_local(fut: impl Future<Output = ()> + 'static) {
Executor::spawn_local(fut)
}
/// Waits until the next "tick" of the current async executor.
pub async fn tick() {
Executor::tick().await
}
pub use reactive_graph::{
spawn_local_scoped, spawn_local_scoped_with_cancellation,
};
}
// these reexports are used in islands
#[cfg(feature = "islands")]
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
pub use serde_json;
#[cfg(feature = "tracing")]
#[doc(hidden)]
pub use tracing;
#[doc(hidden)]
pub use wasm_bindgen;
#[doc(hidden)]
pub use wasm_split_helpers as wasm_split;
#[doc(hidden)]
pub use web_sys;
#[doc(hidden)]
pub mod __reexports {
pub use send_wrapper;
pub use wasm_bindgen_futures;
}
#[doc(hidden)]
#[derive(Clone, Debug, Default)]
pub struct PrefetchLazyFn(
pub reactive_graph::owner::ArcStoredValue<
std::collections::HashSet<&'static str>,
>,
);
#[doc(hidden)]
pub fn prefetch_lazy_fn_on_server(id: &'static str) {
use crate::context::use_context;
use reactive_graph::traits::WriteValue;
if let Some(prefetches) = use_context::<PrefetchLazyFn>() {
prefetches.0.write_value().insert(id);
}
}
#[doc(hidden)]
#[derive(Clone, Debug, Default)]
pub struct WasmSplitManifest(
pub reactive_graph::owner::ArcStoredValue<(
String, // the pkg root
std::collections::HashMap<String, Vec<String>>, // preloads
String, // the name of the __wasm_split.js file
)>,
);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/error_boundary.rs | leptos/src/error_boundary.rs | use crate::{children::TypedChildren, IntoView};
use futures::{channel::oneshot, future::join_all};
use hydration_context::{SerializedDataId, SharedContext};
use leptos_macro::component;
use or_poisoned::OrPoisoned;
use reactive_graph::{
computed::ArcMemo,
effect::RenderEffect,
owner::{provide_context, ArcStoredValue, Owner},
signal::ArcRwSignal,
traits::{Get, Update, With, WithUntracked, WriteValue},
};
use rustc_hash::FxHashMap;
use std::{
collections::VecDeque,
fmt::Debug,
mem,
sync::{Arc, Mutex},
};
use tachys::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
reactive_graph::OwnedView,
ssr::{StreamBuilder, StreamChunk},
view::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml,
},
};
use throw_error::{Error, ErrorHook, ErrorId};
/// When you render a `Result<_, _>` in your view, in the `Err` case it will
/// render nothing, and search up through the view tree for an `<ErrorBoundary/>`.
/// This component lets you define a fallback that should be rendered in that
/// error case, allowing you to handle errors within a section of the interface.
///
/// ```
/// # use leptos::prelude::*;
/// #[component]
/// pub fn ErrorBoundaryExample() -> impl IntoView {
/// let (value, set_value) = signal(Ok(0));
/// let on_input =
/// move |ev| set_value.set(event_target_value(&ev).parse::<i32>());
///
/// view! {
/// <input type="text" on:input=on_input/>
/// <ErrorBoundary
/// fallback=move |_| view! { <p class="error">"Enter a valid number."</p>}
/// >
/// <p>"Value is: " {move || value.get()}</p>
/// </ErrorBoundary>
/// }
/// }
/// ```
///
/// ## Beginner's Tip: ErrorBoundary Requires Your Error To Implement std::error::Error.
/// `ErrorBoundary` requires your `Result<T,E>` to implement [IntoView](https://docs.rs/leptos/latest/leptos/trait.IntoView.html).
/// `Result<T,E>` only implements `IntoView` if `E` implements [std::error::Error](https://doc.rust-lang.org/std/error/trait.Error.html).
/// So, for instance, if you pass a `Result<T,String>` where `T` implements [IntoView](https://docs.rs/leptos/latest/leptos/trait.IntoView.html)
/// and attempt to render the error for the purposes of `ErrorBoundary` you'll get a compiler error like this.
///
/// ```rust,ignore
/// error[E0599]: the method `into_view` exists for enum `Result<ViewableLoginFlow, String>`, but its trait bounds were not satisfied
/// --> src/login.rs:229:32
/// |
/// 229 | err => err.into_view(),
/// | ^^^^^^^^^ method cannot be called on `Result<ViewableLoginFlow, String>` due to unsatisfied trait bounds
/// |
/// = note: the following trait bounds were not satisfied:
/// `<&Result<ViewableLoginFlow, std::string::String> as FnOnce<()>>::Output = _`
/// which is required by `&Result<ViewableLoginFlow, std::string::String>: leptos::IntoView`
/// ... more notes here ...
/// ```
///
/// For more information about how to easily implement `Error` see
/// [thiserror](https://docs.rs/thiserror/latest/thiserror/)
#[component]
pub fn ErrorBoundary<FalFn, Fal, Chil>(
/// The elements that will be rendered, which may include one or more `Result<_>` types.
children: TypedChildren<Chil>,
/// A fallback that will be shown if an error occurs.
fallback: FalFn,
) -> impl IntoView
where
FalFn: FnMut(ArcRwSignal<Errors>) -> Fal + Send + 'static,
Fal: IntoView + Send + 'static,
Chil: IntoView + Send + 'static,
{
let sc = Owner::current_shared_context();
let boundary_id = sc.as_ref().map(|sc| sc.next_id()).unwrap_or_default();
let initial_errors =
sc.map(|sc| sc.errors(&boundary_id)).unwrap_or_default();
let hook = Arc::new(ErrorBoundaryErrorHook::new(
boundary_id.clone(),
initial_errors,
));
let errors = hook.errors.clone();
let errors_empty = ArcMemo::new({
let errors = errors.clone();
move |_| errors.with(|map| map.is_empty())
});
let hook = hook as Arc<dyn ErrorHook>;
let _guard = throw_error::set_error_hook(Arc::clone(&hook));
let suspended_children = ErrorBoundarySuspendedChildren::default();
let owner = Owner::new();
let children = owner.with(|| {
provide_context(Arc::clone(&hook));
provide_context(suspended_children.clone());
children.into_inner()()
});
OwnedView::new_with_owner(
ErrorBoundaryView {
hook,
boundary_id,
errors_empty,
children,
errors,
fallback,
suspended_children,
},
owner,
)
}
pub(crate) type ErrorBoundarySuspendedChildren =
ArcStoredValue<Vec<oneshot::Receiver<()>>>;
struct ErrorBoundaryView<Chil, FalFn> {
hook: Arc<dyn ErrorHook>,
boundary_id: SerializedDataId,
errors_empty: ArcMemo<bool>,
children: Chil,
fallback: FalFn,
errors: ArcRwSignal<Errors>,
suspended_children: ErrorBoundarySuspendedChildren,
}
struct ErrorBoundaryViewState<Chil, Fal> {
// the children are always present; we toggle between them and the fallback as needed
children: Chil,
fallback: Option<Fal>,
}
impl<Chil, Fal> Mountable for ErrorBoundaryViewState<Chil, Fal>
where
Chil: Mountable,
Fal: Mountable,
{
fn unmount(&mut self) {
if let Some(fallback) = &mut self.fallback {
fallback.unmount();
} else {
self.children.unmount();
}
}
fn mount(
&mut self,
parent: &tachys::renderer::types::Element,
marker: Option<&tachys::renderer::types::Node>,
) {
if let Some(fallback) = &mut self.fallback {
fallback.mount(parent, marker);
} else {
self.children.mount(parent, marker);
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
if let Some(fallback) = &self.fallback {
fallback.insert_before_this(child)
} else {
self.children.insert_before_this(child)
}
}
fn elements(&self) -> Vec<tachys::renderer::types::Element> {
if let Some(fallback) = &self.fallback {
fallback.elements()
} else {
self.children.elements()
}
}
}
impl<Chil, FalFn, Fal> Render for ErrorBoundaryView<Chil, FalFn>
where
Chil: Render + 'static,
FalFn: FnMut(ArcRwSignal<Errors>) -> Fal + Send + 'static,
Fal: Render + 'static,
{
type State = RenderEffect<ErrorBoundaryViewState<Chil::State, Fal::State>>;
fn build(mut self) -> Self::State {
let hook = Arc::clone(&self.hook);
let _hook = throw_error::set_error_hook(Arc::clone(&hook));
let mut children = Some(self.children.build());
RenderEffect::new(
move |prev: Option<
ErrorBoundaryViewState<Chil::State, Fal::State>,
>| {
let _hook = throw_error::set_error_hook(Arc::clone(&hook));
if let Some(mut state) = prev {
match (self.errors_empty.get(), &mut state.fallback) {
// no errors, and was showing fallback
(true, Some(fallback)) => {
fallback.insert_before_this(&mut state.children);
fallback.unmount();
state.fallback = None;
}
// yes errors, and was showing children
(false, None) => {
state.fallback = Some(
(self.fallback)(self.errors.clone()).build(),
);
state
.children
.insert_before_this(&mut state.fallback);
state.children.unmount();
}
// either there were no errors, and we were already showing the children
// or there are errors, but we were already showing the fallback
// in either case, rebuilding doesn't require us to do anything
_ => {}
}
state
} else {
let fallback = (!self.errors_empty.get())
.then(|| (self.fallback)(self.errors.clone()).build());
ErrorBoundaryViewState {
children: children.take().unwrap(),
fallback,
}
}
},
)
}
fn rebuild(self, state: &mut Self::State) {
let new = self.build();
let mut old = std::mem::replace(state, new);
old.insert_before_this(state);
old.unmount();
}
}
impl<Chil, FalFn, Fal> AddAnyAttr for ErrorBoundaryView<Chil, FalFn>
where
Chil: RenderHtml + 'static,
FalFn: FnMut(ArcRwSignal<Errors>) -> Fal + Send + 'static,
Fal: RenderHtml + Send + 'static,
{
type Output<SomeNewAttr: Attribute> =
ErrorBoundaryView<Chil::Output<SomeNewAttr::CloneableOwned>, FalFn>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let ErrorBoundaryView {
hook,
boundary_id,
errors_empty,
children,
fallback,
errors,
suspended_children,
} = self;
ErrorBoundaryView {
hook,
boundary_id,
errors_empty,
children: children.add_any_attr(attr.into_cloneable_owned()),
fallback,
errors,
suspended_children,
}
}
}
impl<Chil, FalFn, Fal> RenderHtml for ErrorBoundaryView<Chil, FalFn>
where
Chil: RenderHtml + Send + 'static,
FalFn: FnMut(ArcRwSignal<Errors>) -> Fal + Send + 'static,
Fal: RenderHtml + Send + 'static,
{
type AsyncOutput = ErrorBoundaryView<Chil::AsyncOutput, FalFn>;
type Owned = Self;
const MIN_LENGTH: usize = Chil::MIN_LENGTH;
fn dry_resolve(&mut self) {
self.children.dry_resolve();
}
async fn resolve(self) -> Self::AsyncOutput {
let ErrorBoundaryView {
hook,
boundary_id,
errors_empty,
children,
fallback,
errors,
suspended_children,
..
} = self;
ErrorBoundaryView {
hook,
boundary_id,
errors_empty,
children: children.resolve().await,
fallback,
errors,
suspended_children,
}
}
fn to_html_with_buf(
mut self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
// first, attempt to serialize the children to HTML, then check for errors
let _hook = throw_error::set_error_hook(self.hook);
let mut new_buf = String::with_capacity(Chil::MIN_LENGTH);
let mut new_pos = *position;
self.children.to_html_with_buf(
&mut new_buf,
&mut new_pos,
escape,
mark_branches,
extra_attrs.clone(),
);
// any thrown errors would've been caught here
if self.errors.with_untracked(|map| map.is_empty()) {
buf.push_str(&new_buf);
} else {
// otherwise, serialize the fallback instead
(self.fallback)(self.errors).to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
mut self,
buf: &mut StreamBuilder,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) where
Self: Sized,
{
let _hook = throw_error::set_error_hook(Arc::clone(&self.hook));
// first, attempt to serialize the children to HTML, then check for errors
let mut new_buf = StreamBuilder::new(buf.clone_id());
let mut new_pos = *position;
self.children.to_html_async_with_buf::<OUT_OF_ORDER>(
&mut new_buf,
&mut new_pos,
escape,
mark_branches,
extra_attrs.clone(),
);
let suspense_children =
mem::take(&mut *self.suspended_children.write_value());
// not waiting for any suspended children: just render
if suspense_children.is_empty() {
// any thrown errors would've been caught here
if self.errors.with_untracked(|map| map.is_empty()) {
buf.append(new_buf);
} else {
// otherwise, serialize the fallback instead
let mut fallback = String::with_capacity(Fal::MIN_LENGTH);
(self.fallback)(self.errors).to_html_with_buf(
&mut fallback,
position,
escape,
mark_branches,
extra_attrs,
);
buf.push_sync(&fallback);
}
} else {
let mut position = *position;
// if we're waiting for suspended children, we'll first wait for them to load
// in this implementation, an ErrorBoundary that *contains* Suspense essentially acts
// like a Suspense: it will wait for (all top-level) child Suspense to load before rendering anything
let mut view_buf = StreamBuilder::new(new_buf.clone_id());
view_buf.next_id();
let hook = Arc::clone(&self.hook);
view_buf.push_async(async move {
let _hook = throw_error::set_error_hook(Arc::clone(&hook));
let _ = join_all(suspense_children).await;
let mut my_chunks = VecDeque::new();
for chunk in new_buf.take_chunks() {
match chunk {
StreamChunk::Sync(data) => {
my_chunks.push_back(StreamChunk::Sync(data))
}
StreamChunk::Async { chunks } => {
let chunks = chunks.await;
my_chunks.extend(chunks);
}
StreamChunk::OutOfOrder { chunks } => {
let chunks = chunks.await;
my_chunks.push_back(StreamChunk::OutOfOrder {
chunks: Box::pin(async move { chunks }),
});
}
}
}
if self.errors.with_untracked(|map| map.is_empty()) {
// if no errors, just go ahead with the stream
my_chunks
} else {
// otherwise, serialize the fallback instead
let mut fallback = String::with_capacity(Fal::MIN_LENGTH);
(self.fallback)(self.errors).to_html_with_buf(
&mut fallback,
&mut position,
escape,
mark_branches,
extra_attrs,
);
my_chunks.clear();
my_chunks.push_back(StreamChunk::Sync(fallback));
my_chunks
}
});
buf.append(view_buf);
}
}
fn hydrate<const FROM_SERVER: bool>(
mut self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let mut children = Some(self.children);
let hook = Arc::clone(&self.hook);
let cursor = cursor.to_owned();
let position = position.to_owned();
RenderEffect::new(
move |prev: Option<
ErrorBoundaryViewState<Chil::State, Fal::State>,
>| {
let _hook = throw_error::set_error_hook(Arc::clone(&hook));
if let Some(mut state) = prev {
match (self.errors_empty.get(), &mut state.fallback) {
// no errors, and was showing fallback
(true, Some(fallback)) => {
fallback.insert_before_this(&mut state.children);
state.fallback.unmount();
state.fallback = None;
}
// yes errors, and was showing children
(false, None) => {
state.fallback = Some(
(self.fallback)(self.errors.clone()).build(),
);
state
.children
.insert_before_this(&mut state.fallback);
state.children.unmount();
}
// either there were no errors, and we were already showing the children
// or there are errors, but we were already showing the fallback
// in either case, rebuilding doesn't require us to do anything
_ => {}
}
state
} else {
let children = children.take().unwrap();
let (children, fallback) = if self.errors_empty.get() {
(
children.hydrate::<FROM_SERVER>(&cursor, &position),
None,
)
} else {
(
children.build(),
Some(
(self.fallback)(self.errors.clone())
.hydrate::<FROM_SERVER>(&cursor, &position),
),
)
};
ErrorBoundaryViewState { children, fallback }
}
},
)
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let mut children = Some(self.children);
let hook = Arc::clone(&self.hook);
let cursor = cursor.to_owned();
let position = position.to_owned();
let fallback_fn = Arc::new(Mutex::new(self.fallback));
let initial = {
let errors_empty = self.errors_empty.clone();
let errors = self.errors.clone();
let fallback_fn = Arc::clone(&fallback_fn);
async move {
let children = children.take().unwrap();
let (children, fallback) = if errors_empty.get() {
(children.hydrate_async(&cursor, &position).await, None)
} else {
let children = children.build();
let fallback =
(fallback_fn.lock().or_poisoned())(errors.clone());
let fallback =
fallback.hydrate_async(&cursor, &position).await;
(children, Some(fallback))
};
ErrorBoundaryViewState { children, fallback }
}
};
RenderEffect::new_with_async_value(
move |prev: Option<
ErrorBoundaryViewState<Chil::State, Fal::State>,
>| {
let _hook = throw_error::set_error_hook(Arc::clone(&hook));
if let Some(mut state) = prev {
match (self.errors_empty.get(), &mut state.fallback) {
// no errors, and was showing fallback
(true, Some(fallback)) => {
fallback.insert_before_this(&mut state.children);
state.fallback.unmount();
state.fallback = None;
}
// yes errors, and was showing children
(false, None) => {
state.fallback = Some(
(fallback_fn.lock().or_poisoned())(
self.errors.clone(),
)
.build(),
);
state
.children
.insert_before_this(&mut state.fallback);
state.children.unmount();
}
// either there were no errors, and we were already showing the children
// or there are errors, but we were already showing the fallback
// in either case, rebuilding doesn't require us to do anything
_ => {}
}
state
} else {
unreachable!()
}
},
initial,
)
.await
}
fn into_owned(self) -> Self::Owned {
self
}
}
#[derive(Debug)]
struct ErrorBoundaryErrorHook {
errors: ArcRwSignal<Errors>,
id: SerializedDataId,
shared_context: Option<Arc<dyn SharedContext + Send + Sync>>,
}
impl ErrorBoundaryErrorHook {
pub fn new(
id: SerializedDataId,
initial_errors: impl IntoIterator<Item = (ErrorId, Error)>,
) -> Self {
Self {
errors: ArcRwSignal::new(Errors(
initial_errors.into_iter().collect(),
)),
id,
shared_context: Owner::current_shared_context(),
}
}
}
impl ErrorHook for ErrorBoundaryErrorHook {
fn throw(&self, error: Error) -> ErrorId {
// generate a unique ID
let key: ErrorId = Owner::current_shared_context()
.map(|sc| sc.next_id())
.unwrap_or_default()
.into();
// register it with the shared context, so that it can be serialized from server to client
// as needed
if let Some(sc) = &self.shared_context {
sc.register_error(self.id.clone(), key.clone(), error.clone());
}
// add it to the reactive map of errors
self.errors.update(|map| {
map.insert(key.clone(), error);
});
// return the key, which will be owned by the Result being rendered and can be used to
// unregister this error if it is rebuilt
key
}
fn clear(&self, id: &throw_error::ErrorId) {
self.errors.update(|map| {
map.remove(id);
});
}
}
/// A struct to hold all the possible errors that could be provided by child Views
#[derive(Debug, Clone, Default)]
#[repr(transparent)]
pub struct Errors(FxHashMap<ErrorId, Error>);
impl Errors {
/// Returns `true` if there are no errors.
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Add an error to Errors that will be processed by `<ErrorBoundary/>`
pub fn insert<E>(&mut self, key: ErrorId, error: E)
where
E: Into<Error>,
{
self.0.insert(key, error.into());
}
/// Add an error with the default key for errors outside the reactive system
pub fn insert_with_default_key<E>(&mut self, error: E)
where
E: Into<Error>,
{
self.0.insert(Default::default(), error.into());
}
/// Remove an error to Errors that will be processed by `<ErrorBoundary/>`
pub fn remove(&mut self, key: &ErrorId) -> Option<Error> {
self.0.remove(key)
}
/// An iterator over all the errors, in arbitrary order.
#[inline(always)]
pub fn iter(&self) -> Iter<'_> {
Iter(self.0.iter())
}
}
impl IntoIterator for Errors {
type Item = (ErrorId, Error);
type IntoIter = IntoIter;
#[inline(always)]
fn into_iter(self) -> Self::IntoIter {
IntoIter(self.0.into_iter())
}
}
/// An owning iterator over all the errors contained in the [`Errors`] struct.
#[repr(transparent)]
pub struct IntoIter(std::collections::hash_map::IntoIter<ErrorId, Error>);
impl Iterator for IntoIter {
type Item = (ErrorId, Error);
#[inline(always)]
fn next(
&mut self,
) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
self.0.next()
}
}
/// An iterator over all the errors contained in the [`Errors`] struct.
#[repr(transparent)]
pub struct Iter<'a>(std::collections::hash_map::Iter<'a, ErrorId, Error>);
impl<'a> Iterator for Iter<'a> {
type Item = (&'a ErrorId, &'a Error);
#[inline(always)]
fn next(
&mut self,
) -> std::option::Option<<Self as std::iter::Iterator>::Item> {
self.0.next()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/portal.rs | leptos/src/portal.rs | use crate::{children::TypedChildrenFn, mount, IntoView};
use leptos_dom::helpers::document;
use leptos_macro::component;
use reactive_graph::{effect::Effect, graph::untrack, owner::Owner};
use std::sync::Arc;
/// Renders components somewhere else in the DOM.
///
/// Useful for inserting modals and tooltips outside of a cropping layout.
/// If no mount point is given, the portal is inserted in `document.body`;
/// it is wrapped in a `<div>` unless `is_svg` is `true` in which case it's wrapped in a `<g>`.
/// Setting `use_shadow` to `true` places the element in a shadow root to isolate styles.
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
#[component]
pub fn Portal<V>(
/// Target element where the children will be appended
#[prop(into, optional)]
mount: Option<web_sys::Element>,
/// Whether to use a shadow DOM inside `mount`. Defaults to `false`.
#[prop(optional)]
use_shadow: bool,
/// When using SVG this has to be set to `true`. Defaults to `false`.
#[prop(optional)]
is_svg: bool,
/// The children to teleport into the `mount` element
children: TypedChildrenFn<V>,
) -> impl IntoView
where
V: IntoView + 'static,
{
if cfg!(target_arch = "wasm32")
&& Owner::current_shared_context()
.map(|sc| sc.is_browser())
.unwrap_or(true)
{
use send_wrapper::SendWrapper;
use wasm_bindgen::JsCast;
let mount = mount.unwrap_or_else(|| {
document().body().expect("body to exist").unchecked_into()
});
let children = children.into_inner();
Effect::new(move |_| {
let container = if is_svg {
document()
.create_element_ns(Some("http://www.w3.org/2000/svg"), "g")
.expect("SVG element creation to work")
} else {
document()
.create_element("div")
.expect("HTML element creation to work")
};
let render_root = if use_shadow {
container
.attach_shadow(&web_sys::ShadowRootInit::new(
web_sys::ShadowRootMode::Open,
))
.map(|root| root.unchecked_into())
.unwrap_or(container.clone())
} else {
container.clone()
};
let _ = mount.append_child(&container);
let handle = SendWrapper::new((
mount::mount_to(render_root.unchecked_into(), {
let children = Arc::clone(&children);
move || untrack(|| children())
}),
mount.clone(),
container,
));
Owner::on_cleanup({
move || {
let (handle, mount, container) = handle.take();
drop(handle);
let _ = mount.remove_child(&container);
}
})
});
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/show_let.rs | leptos/src/show_let.rs | use crate::{children::ViewFn, IntoView};
use leptos_macro::component;
use reactive_graph::traits::Get;
use std::{marker::PhantomData, sync::Arc};
use tachys::either::Either;
/// Like `<Show>` but for `Option`. This is a shortcut for
///
/// ```ignore
/// value.map(|value| {
/// view! { ... }
/// })
/// ```
///
/// If you specify a `fallback` it is equvalent to
///
/// ```ignore
/// value
/// .map(
/// |value| children(value),
/// )
/// .unwrap_or_else(fallback)
/// ```
///
/// ## Example
///
/// ```
/// # use leptos::prelude::*;
/// #
/// # #[component]
/// # pub fn Example() -> impl IntoView {
/// let (opt_value, set_opt_value) = signal(None::<i32>);
///
/// view! {
/// <ShowLet some=opt_value let:value>
/// "We have a value: " {value}
/// </ShowLet>
/// }
/// # }
/// ```
///
/// You can also specify a fallback:
/// ```
/// # use leptos::prelude::*;
/// #
/// # #[component]
/// # pub fn Example() -> impl IntoView {
/// let (opt_value, set_opt_value) = signal(None::<i32>);
///
/// view! {
/// <ShowLet some=opt_value let:value fallback=|| "Got nothing">
/// "We have a value: " {value}
/// </ShowLet>
/// }
/// # }
/// ```
///
/// In addition to signals you can also use a closure that returns an `Option`:
///
/// ```
/// # use leptos::prelude::*;
/// #
/// # #[component]
/// # pub fn Example() -> impl IntoView {
/// let (opt_value, set_opt_value) = signal(None::<i32>);
///
/// view! {
/// <ShowLet some=move || opt_value.get().map(|v| v * 2) let:value>
/// "We have a value: " {value}
/// </ShowLet>
/// }
/// # }
/// ```
#[component]
pub fn ShowLet<T, ChFn, V, M>(
/// The children will be shown whenever `value` is `Some`.
///
/// They take the inner value as an argument. Use `let:` to bind the value to a variable.
children: ChFn,
/// A signal of type `Option` or a closure that returns an `Option`.
/// If the value is `Some`, the children will be shown.
/// Otherwise the fallback will be shown, if present.
some: impl IntoOptionGetter<T, M>,
/// A closure that returns what gets rendered when the value is `None`.
/// By default this is the empty view.
///
/// You can think of it as the closure inside `.unwrap_or_else(|| fallback())`.
#[prop(optional, into)]
fallback: ViewFn,
/// Marker for generic parameters. Ignore this.
#[prop(optional)]
_marker: PhantomData<(T, M)>,
) -> impl IntoView
where
ChFn: Fn(T) -> V + Send + Clone + 'static,
V: IntoView + 'static,
T: 'static,
{
let getter = some.into_option_getter();
move || {
let children = children.clone();
let fallback = fallback.clone();
getter
.run()
.map(move |t| Either::Left(children(t)))
.unwrap_or_else(move || Either::Right(fallback.run()))
}
}
/// Servers as a wrapper for both, an `Option` signal or a closure that returns an `Option`.
pub struct OptionGetter<T>(Arc<dyn Fn() -> Option<T> + Send + Sync + 'static>);
impl<T> Clone for OptionGetter<T> {
fn clone(&self) -> Self {
Self(Arc::clone(&self.0))
}
}
impl<T> OptionGetter<T> {
/// Runs the getter and returns the result.
pub fn run(&self) -> Option<T> {
(self.0)()
}
}
/// Conversion trait for creating an `OptionGetter` from a closure or a signal.
pub trait IntoOptionGetter<T, M> {
/// Converts the given value into an `OptionGetter`.
fn into_option_getter(self) -> OptionGetter<T>;
}
/// Marker type for creating an `OptionGetter` from a closure.
/// Used so that the compiler doesn't complain about double implementations of the trait `IntoOptionGetter`.
pub struct FunctionMarker;
impl<T, F> IntoOptionGetter<T, FunctionMarker> for F
where
F: Fn() -> Option<T> + Send + Sync + 'static,
{
fn into_option_getter(self) -> OptionGetter<T> {
OptionGetter(Arc::new(self))
}
}
/// Marker type for creating an `OptionGetter` from a signal.
/// Used so that the compiler doesn't complain about double implementations of the trait `IntoOptionGetter`.
pub struct SignalMarker;
impl<T, S> IntoOptionGetter<T, SignalMarker> for S
where
S: Get<Value = Option<T>> + Clone + Send + Sync + 'static,
{
fn into_option_getter(self) -> OptionGetter<T> {
let cloned = self.clone();
OptionGetter(Arc::new(move || cloned.get()))
}
}
/// Marker type for creating an `OptionGetter` from a static value.
/// Used so that the compiler doesn't complain about double implementations of the trait `IntoOptionGetter`.
pub struct StaticMarker;
impl<T> IntoOptionGetter<T, StaticMarker> for Option<T>
where
T: Clone + Send + Sync + 'static,
{
fn into_option_getter(self) -> OptionGetter<T> {
OptionGetter(Arc::new(move || self.clone()))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/nonce.rs | leptos/src/nonce.rs | use crate::context::{provide_context, use_context};
use base64::{
alphabet,
engine::{self, general_purpose},
Engine,
};
use rand::{rng, RngCore};
use std::{fmt::Display, ops::Deref, sync::Arc};
use tachys::html::attribute::AttributeValue;
/// A cryptographic nonce ("number used once") which can be
/// used by Content Security Policy to determine whether or not a given
/// resource will be allowed to load.
///
/// When the `nonce` feature is enabled on one of the server integrations,
/// a nonce is generated during server rendering and added to all inline
/// scripts used for HTML streaming and resource loading.
///
/// The nonce being used during the current server response can be
/// accessed using [`use_nonce`].
///
/// ```rust,ignore
/// #[component]
/// pub fn App() -> impl IntoView {
/// provide_meta_context;
///
/// view! {
/// // use `leptos_meta` to insert a <meta> tag with the CSP
/// <Meta
/// http_equiv="Content-Security-Policy"
/// content=move || {
/// // this will insert the CSP with nonce on the server, be empty on client
/// use_nonce()
/// .map(|nonce| {
/// format!(
/// "default-src 'self'; script-src 'strict-dynamic' 'nonce-{nonce}' \
/// 'wasm-unsafe-eval'; style-src 'nonce-{nonce}';"
/// )
/// })
/// .unwrap_or_default()
/// }
/// />
/// // manually insert nonce during SSR on inline script
/// <script nonce=use_nonce()>"console.log('Hello, world!');"</script>
/// // leptos_meta <Style/> and <Script/> automatically insert the nonce
/// <Style>"body { color: blue; }"</Style>
/// <p>"Test"</p>
/// }
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Nonce(pub(crate) Arc<str>);
impl Nonce {
/// Returns a reference to the inner reference-counted string slice representing the nonce.
pub fn as_inner(&self) -> &Arc<str> {
&self.0
}
}
impl Deref for Nonce {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Display for Nonce {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.0)
}
}
impl AttributeValue for Nonce {
type AsyncOutput = Self;
type State = <Arc<str> as AttributeValue>::State;
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
self.0.len()
}
fn to_html(self, key: &str, buf: &mut String) {
<Arc<str> as AttributeValue>::to_html(self.0, key, buf)
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &tachys::renderer::types::Element,
) -> Self::State {
<Arc<str> as AttributeValue>::hydrate::<FROM_SERVER>(self.0, key, el)
}
fn build(
self,
el: &tachys::renderer::types::Element,
key: &str,
) -> Self::State {
<Arc<str> as AttributeValue>::build(self.0, el, key)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
<Arc<str> as AttributeValue>::rebuild(self.0, key, state)
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
/// Accesses the nonce that has been generated during the current
/// server response. This can be added to inline `<script>` and
/// `<style>` tags for compatibility with a Content Security Policy.
///
/// ```rust,ignore
/// #[component]
/// pub fn App() -> impl IntoView {
/// provide_meta_context;
///
/// view! {
/// // use `leptos_meta` to insert a <meta> tag with the CSP
/// <Meta
/// http_equiv="Content-Security-Policy"
/// content=move || {
/// // this will insert the CSP with nonce on the server, be empty on client
/// use_nonce()
/// .map(|nonce| {
/// format!(
/// "default-src 'self'; script-src 'strict-dynamic' 'nonce-{nonce}' \
/// 'wasm-unsafe-eval'; style-src 'nonce-{nonce}';"
/// )
/// })
/// .unwrap_or_default()
/// }
/// />
/// // manually insert nonce during SSR on inline script
/// <script nonce=use_nonce()>"console.log('Hello, world!');"</script>
/// // leptos_meta <Style/> and <Script/> automatically insert the nonce
/// <Style>"body { color: blue; }"</Style>
/// <p>"Test"</p>
/// }
/// }
/// ```
pub fn use_nonce() -> Option<Nonce> {
use_context::<Nonce>()
}
/// Generates a nonce and provides it via context.
pub fn provide_nonce() {
provide_context(Nonce::new())
}
const NONCE_ENGINE: engine::GeneralPurpose =
engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);
impl Nonce {
/// Generates a new nonce from 16 bytes (128 bits) of random data.
pub fn new() -> Self {
let mut rng = rng();
let mut bytes = [0; 16];
rng.fill_bytes(&mut bytes);
Nonce(NONCE_ENGINE.encode(bytes).into())
}
}
impl Default for Nonce {
fn default() -> Self {
Self::new()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/into_view.rs | leptos/src/into_view.rs | use std::borrow::Cow;
use tachys::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr, Position, PositionState, Render, RenderHtml,
ToTemplate,
},
};
/// A wrapper for any kind of view.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct View<T>
where
T: Sized,
{
inner: T,
#[cfg(debug_assertions)]
view_marker: Option<Cow<'static, str>>,
}
impl<T> View<T> {
/// Wraps the view.
pub fn new(inner: T) -> Self {
Self {
inner,
#[cfg(debug_assertions)]
view_marker: None,
}
}
/// Unwraps the view, returning the inner type.
pub fn into_inner(self) -> T {
self.inner
}
/// Adds a view marker, which is used for hot-reloading and debug purposes.
#[inline(always)]
pub fn with_view_marker(
#[allow(unused_mut)] // used in debug
mut self,
#[allow(unused_variables)] // used in debug
view_marker: impl Into<Cow<'static, str>>,
) -> Self {
#[cfg(debug_assertions)]
{
self.view_marker = Some(view_marker.into());
}
self
}
}
/// A trait that is implemented for types that can be rendered.
pub trait IntoView
where
Self: Sized + Render + RenderHtml + Send,
{
/// Wraps the inner type.
fn into_view(self) -> View<Self>;
}
impl<T> IntoView for T
where
T: Sized + Render + RenderHtml + Send, //+ AddAnyAttr,
{
fn into_view(self) -> View<Self> {
View {
inner: self,
#[cfg(debug_assertions)]
view_marker: None,
}
}
}
impl<T: Render> Render for View<T> {
type State = T::State;
fn build(self) -> Self::State {
self.inner.build()
}
fn rebuild(self, state: &mut Self::State) {
self.inner.rebuild(state)
}
}
impl<T: RenderHtml> RenderHtml for View<T> {
type AsyncOutput = T::AsyncOutput;
type Owned = View<T::Owned>;
const MIN_LENGTH: usize = <T as RenderHtml>::MIN_LENGTH;
const EXISTS: bool = <T as RenderHtml>::EXISTS;
async fn resolve(self) -> Self::AsyncOutput {
self.inner.resolve().await
}
fn dry_resolve(&mut self) {
self.inner.dry_resolve();
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
#[cfg(debug_assertions)]
let vm = if option_env!("LEPTOS_WATCH").is_some() {
self.view_marker.to_owned()
} else {
None
};
#[cfg(debug_assertions)]
if let Some(vm) = vm.as_ref() {
buf.push_str(&format!("<!--hot-reload|{vm}|open-->"));
}
self.inner.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
#[cfg(debug_assertions)]
if let Some(vm) = vm.as_ref() {
buf.push_str(&format!("<!--hot-reload|{vm}|close-->"));
}
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) where
Self: Sized,
{
#[cfg(debug_assertions)]
let vm = if option_env!("LEPTOS_WATCH").is_some() {
self.view_marker.to_owned()
} else {
None
};
#[cfg(debug_assertions)]
if let Some(vm) = vm.as_ref() {
buf.push_sync(&format!("<!--hot-reload|{vm}|open-->"));
}
self.inner.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
#[cfg(debug_assertions)]
if let Some(vm) = vm.as_ref() {
buf.push_sync(&format!("<!--hot-reload|{vm}|close-->"));
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
self.inner.hydrate::<FROM_SERVER>(cursor, position)
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
self.inner.hydrate_async(cursor, position).await
}
fn into_owned(self) -> Self::Owned {
View {
inner: self.inner.into_owned(),
#[cfg(debug_assertions)]
view_marker: self.view_marker,
}
}
}
impl<T: ToTemplate> ToTemplate for View<T> {
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
T::to_template(buf, class, style, inner_html, position);
}
}
impl<T: AddAnyAttr> AddAnyAttr for View<T> {
type Output<SomeNewAttr: Attribute> = View<T::Output<SomeNewAttr>>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let View {
inner,
#[cfg(debug_assertions)]
view_marker,
} = self;
View {
inner: inner.add_any_attr(attr),
#[cfg(debug_assertions)]
view_marker,
}
}
}
/// Collects some iterator of views into a list, so they can be rendered.
///
/// This is a shorthand for `.collect::<Vec<_>>()`, and allows any iterator of renderable
/// items to be collected into a renderable collection.
pub trait CollectView {
/// The inner view type.
type View: IntoView;
/// Collects the iterator into a list of views.
fn collect_view(self) -> Vec<Self::View>;
}
impl<It, V> CollectView for It
where
It: IntoIterator<Item = V>,
V: IntoView,
{
type View = V;
fn collect_view(self) -> Vec<Self::View> {
self.into_iter().collect()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/form.rs | leptos/src/form.rs | use crate::{children::Children, component, prelude::*, IntoView};
use leptos_dom::helpers::window;
use leptos_server::{ServerAction, ServerMultiAction};
use serde::de::DeserializeOwned;
use server_fn::{
client::Client,
codec::PostUrl,
error::{IntoAppError, ServerFnErrorErr},
request::ClientReq,
Http, ServerFn,
};
use tachys::{
either::Either,
html::{
element::{form, Form},
event::submit,
},
reactive_graph::node_ref::NodeRef,
};
use thiserror::Error;
use wasm_bindgen::{JsCast, JsValue, UnwrapThrowExt};
use web_sys::{
Event, FormData, HtmlButtonElement, HtmlFormElement, HtmlInputElement,
SubmitEvent,
};
/// Automatically turns a server [Action](leptos_server::Action) into an HTML
/// [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
/// progressively enhanced to use client-side routing.
///
/// ## Encoding
/// **Note:** `<ActionForm/>` only works with server functions that use the
/// default `Url` encoding. This is to ensure that `<ActionForm/>` works correctly
/// both before and after WASM has loaded.
///
/// ## Complex Inputs
/// Server function arguments that are structs with nested serializable fields
/// should make use of indexing notation of `serde_qs`.
///
/// ```rust
/// # use leptos::prelude::*;
/// use leptos::form::ActionForm;
///
/// #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
/// struct HeftyData {
/// first_name: String,
/// last_name: String,
/// }
///
/// #[component]
/// fn ComplexInput() -> impl IntoView {
/// let submit = ServerAction::<VeryImportantFn>::new();
///
/// view! {
/// <ActionForm action=submit>
/// <input type="text" name="hefty_arg[first_name]" value="leptos"/>
/// <input
/// type="text"
/// name="hefty_arg[last_name]"
/// value="closures-everywhere"
/// />
/// <input type="submit"/>
/// </ActionForm>
/// }
/// }
///
/// #[server]
/// async fn very_important_fn(
/// hefty_arg: HeftyData,
/// ) -> Result<(), ServerFnError> {
/// assert_eq!(hefty_arg.first_name.as_str(), "leptos");
/// assert_eq!(hefty_arg.last_name.as_str(), "closures-everywhere");
/// Ok(())
/// }
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
#[component]
pub fn ActionForm<ServFn, OutputProtocol>(
/// The action from which to build the form.
action: ServerAction<ServFn>,
/// A [`NodeRef`] in which the `<form>` element should be stored.
#[prop(optional)]
node_ref: Option<NodeRef<Form>>,
/// Component children; should include the HTML of the form elements.
children: Children,
) -> impl IntoView
where
ServFn: DeserializeOwned
+ ServerFn<Protocol = Http<PostUrl, OutputProtocol>>
+ Clone
+ Send
+ Sync
+ 'static,
<<ServFn::Client as Client<ServFn::Error>>::Request as ClientReq<
ServFn::Error,
>>::FormData: From<FormData>,
ServFn: Send + Sync + 'static,
ServFn::Output: Send + Sync + 'static,
ServFn::Error: Send + Sync + 'static,
<ServFn as ServerFn>::Client: Client<<ServFn as ServerFn>::Error>,
{
// if redirect hook has not yet been set (by a router), defaults to a browser redirect
_ = server_fn::redirect::set_redirect_hook(|loc: &str| {
if let Some(url) = resolve_redirect_url(loc) {
_ = window().location().set_href(&url.href());
}
});
let version = action.version();
let value = action.value();
let on_submit = {
move |ev: SubmitEvent| {
if ev.default_prevented() {
return;
}
ev.prevent_default();
match ServFn::from_event(&ev) {
Ok(new_input) => {
action.dispatch(new_input);
}
Err(err) => {
crate::logging::error!(
"Error converting form field into server function \
arguments: {err:?}"
);
value.set(Some(Err(ServerFnErrorErr::Serialization(
err.to_string(),
)
.into_app_error())));
version.update(|n| *n += 1);
}
}
}
};
let action_form = form()
.action(ServFn::url())
.method("post")
.on(submit, on_submit)
.child(children());
if let Some(node_ref) = node_ref {
Either::Left(action_form.node_ref(node_ref))
} else {
Either::Right(action_form)
}
}
/// Automatically turns a server [MultiAction](leptos_server::MultiAction) into an HTML
/// [`form`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form)
/// progressively enhanced to use client-side routing.
#[component]
pub fn MultiActionForm<ServFn, OutputProtocol>(
/// The action from which to build the form.
action: ServerMultiAction<ServFn>,
/// A [`NodeRef`] in which the `<form>` element should be stored.
#[prop(optional)]
node_ref: Option<NodeRef<Form>>,
/// Component children; should include the HTML of the form elements.
children: Children,
) -> impl IntoView
where
ServFn: Send
+ Sync
+ Clone
+ DeserializeOwned
+ ServerFn<Protocol = Http<PostUrl, OutputProtocol>>
+ 'static,
ServFn::Output: Send + Sync + 'static,
<<ServFn::Client as Client<ServFn::Error>>::Request as ClientReq<
ServFn::Error,
>>::FormData: From<FormData>,
ServFn::Error: Send + Sync + 'static,
<ServFn as ServerFn>::Client: Client<<ServFn as ServerFn>::Error>,
{
// if redirect hook has not yet been set (by a router), defaults to a browser redirect
_ = server_fn::redirect::set_redirect_hook(|loc: &str| {
if let Some(url) = resolve_redirect_url(loc) {
_ = window().location().set_href(&url.href());
}
});
let on_submit = move |ev: SubmitEvent| {
if ev.default_prevented() {
return;
}
ev.prevent_default();
match ServFn::from_event(&ev) {
Ok(new_input) => {
action.dispatch(new_input);
}
Err(err) => {
action.dispatch_sync(Err(ServerFnErrorErr::Serialization(
err.to_string(),
)
.into_app_error()));
}
}
};
let action_form = form()
.action(ServFn::url())
.method("post")
.attr("method", "post")
.on(submit, on_submit)
.child(children());
if let Some(node_ref) = node_ref {
Either::Left(action_form.node_ref(node_ref))
} else {
Either::Right(action_form)
}
}
/// Resolves a redirect location to an (absolute) URL.
pub(crate) fn resolve_redirect_url(loc: &str) -> Option<web_sys::Url> {
let origin = match window().location().origin() {
Ok(origin) => origin,
Err(e) => {
leptos::logging::error!("Failed to get origin: {:#?}", e);
return None;
}
};
// TODO: Use server function's URL as base instead.
let base = origin;
match web_sys::Url::new_with_base(loc, &base) {
Ok(url) => Some(url),
Err(e) => {
leptos::logging::error!(
"Invalid redirect location: {}",
e.as_string().unwrap_or_default(),
);
None
}
}
}
/// Tries to deserialize a type from form data. This can be used for client-side
/// validation during form submission.
pub trait FromFormData
where
Self: Sized + serde::de::DeserializeOwned,
{
/// Tries to deserialize the data, given only the `submit` event.
fn from_event(ev: &web_sys::Event) -> Result<Self, FromFormDataError>;
/// Tries to deserialize the data, given the actual form data.
fn from_form_data(
form_data: &web_sys::FormData,
) -> Result<Self, serde_qs::Error>;
}
/// Errors that can arise when converting from an HTML event or form into a Rust data type.
#[derive(Error, Debug)]
pub enum FromFormDataError {
/// Could not find a `<form>` connected to the event.
#[error("Could not find <form> connected to event.")]
MissingForm(Event),
/// Could not create `FormData` from the form.
#[error("Could not create FormData from <form>: {0:?}")]
FormData(JsValue),
/// Failed to deserialize this Rust type from the form data.
#[error("Deserialization error: {0:?}")]
Deserialization(serde_qs::Error),
}
impl<T> FromFormData for T
where
T: serde::de::DeserializeOwned,
{
fn from_event(ev: &Event) -> Result<Self, FromFormDataError> {
let submit_ev = ev.unchecked_ref();
let form_data = form_data_from_event(submit_ev)?;
Self::from_form_data(&form_data)
.map_err(FromFormDataError::Deserialization)
}
fn from_form_data(
form_data: &web_sys::FormData,
) -> Result<Self, serde_qs::Error> {
let data =
web_sys::UrlSearchParams::new_with_str_sequence_sequence(form_data)
.unwrap_throw();
let data = data.to_string().as_string().unwrap_or_default();
serde_qs::Config::new(5, false).deserialize_str::<Self>(&data)
}
}
fn form_data_from_event(
ev: &SubmitEvent,
) -> Result<FormData, FromFormDataError> {
let submitter = ev.submitter();
let mut submitter_name_value = None;
let opt_form = match &submitter {
Some(el) => {
if let Some(form) = el.dyn_ref::<HtmlFormElement>() {
Some(form.clone())
} else if let Some(input) = el.dyn_ref::<HtmlInputElement>() {
submitter_name_value = Some((input.name(), input.value()));
Some(ev.target().unwrap().unchecked_into())
} else if let Some(button) = el.dyn_ref::<HtmlButtonElement>() {
submitter_name_value = Some((button.name(), button.value()));
Some(ev.target().unwrap().unchecked_into())
} else {
None
}
}
None => ev.target().map(|form| form.unchecked_into()),
};
match opt_form.as_ref().map(FormData::new_with_form) {
None => Err(FromFormDataError::MissingForm(ev.clone().into())),
Some(Err(e)) => Err(FromFormDataError::FormData(e)),
Some(Ok(form_data)) => {
if let Some((name, value)) = submitter_name_value {
form_data
.append_with_str(&name, &value)
.map_err(FromFormDataError::FormData)?;
}
Ok(form_data)
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/transition.rs | leptos/src/transition.rs | use crate::{
children::{TypedChildren, ViewFnOnce},
error::ErrorBoundarySuspendedChildren,
suspense_component::SuspenseBoundary,
IntoView,
};
use leptos_macro::component;
use reactive_graph::{
computed::{suspense::SuspenseContext, ArcMemo},
effect::Effect,
owner::{provide_context, use_context, Owner},
signal::ArcRwSignal,
traits::{Get, Set, Track, With, WithUntracked},
wrappers::write::SignalSetter,
};
use slotmap::{DefaultKey, SlotMap};
use std::sync::Arc;
use tachys::reactive_graph::OwnedView;
/// If any [`Resource`](crate::prelude::Resource) is read in the `children` of this
/// component, it will show the `fallback` while they are loading. Once all are resolved,
/// it will render the `children`.
///
/// Unlike [`Suspense`](crate::prelude::Suspense), this will not fall
/// back to the `fallback` state if there are further changes after the initial load.
///
/// Note that the `children` will be rendered initially (in order to capture the fact that
/// those resources are read under the suspense), so you cannot assume that resources read
/// synchronously have
/// `Some` value in `children`. However, you can read resources asynchronously by using
/// [Suspend](crate::prelude::Suspend).
///
/// ```
/// # use leptos::prelude::*;
/// # if false { // don't run in doctests
/// async fn fetch_cats(how_many: u32) -> Vec<String> { vec![] }
///
/// let (cat_count, set_cat_count) = signal::<u32>(1);
///
/// let cats = Resource::new(move || cat_count.get(), |count| fetch_cats(count));
///
/// view! {
/// <div>
/// <Transition fallback=move || view! { <p>"Loading (Suspense Fallback)..."</p> }>
/// // you can access a resource synchronously
/// {move || {
/// cats.get().map(|data| {
/// data
/// .into_iter()
/// .map(|src| {
/// view! {
/// <img src={src}/>
/// }
/// })
/// .collect_view()
/// })
/// }
/// }
/// // or you can use `Suspend` to read resources asynchronously
/// {move || Suspend::new(async move {
/// cats.await
/// .into_iter()
/// .map(|src| {
/// view! {
/// <img src={src}/>
/// }
/// })
/// .collect_view()
/// })}
/// </Transition>
/// </div>
/// }
/// # ;}
/// ```
#[component]
pub fn Transition<Chil>(
/// Will be displayed while resources are pending. By default this is the empty view.
#[prop(optional, into)]
fallback: ViewFnOnce,
/// A function that will be called when the component transitions into or out of
/// the `pending` state, with its argument indicating whether it is pending (`true`)
/// or not pending (`false`).
#[prop(optional, into)]
set_pending: Option<SignalSetter<bool>>,
children: TypedChildren<Chil>,
) -> impl IntoView
where
Chil: IntoView + Send + 'static,
{
let error_boundary_parent = use_context::<ErrorBoundarySuspendedChildren>();
let owner = Owner::new();
owner.with(|| {
let (starts_local, id) = {
Owner::current_shared_context()
.map(|sc| {
let id = sc.next_id();
(sc.get_incomplete_chunk(&id), id)
})
.unwrap_or_else(|| (false, Default::default()))
};
let fallback = fallback.run();
let children = children.into_inner()();
let tasks = ArcRwSignal::new(SlotMap::<DefaultKey, ()>::new());
provide_context(SuspenseContext {
tasks: tasks.clone(),
});
let none_pending = ArcMemo::new({
let tasks = tasks.clone();
move |prev: Option<&bool>| {
tasks.track();
if prev.is_none() && starts_local {
false
} else {
tasks.with(SlotMap::is_empty)
}
}
});
let has_tasks =
Arc::new(move || !tasks.with_untracked(SlotMap::is_empty));
if let Some(set_pending) = set_pending {
Effect::new_isomorphic({
let none_pending = none_pending.clone();
move |_| {
set_pending.set(!none_pending.get());
}
});
}
OwnedView::new(SuspenseBoundary::<true, _, _> {
id,
none_pending,
fallback,
children,
error_boundary_parent,
has_tasks,
})
})
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/for_loop.rs | leptos/src/for_loop.rs | use crate::into_view::IntoView;
use leptos_macro::component;
use reactive_graph::{
owner::Owner,
signal::{ArcRwSignal, ReadSignal},
traits::Set,
};
use std::hash::Hash;
use tachys::{
reactive_graph::OwnedView,
view::keyed::{keyed, SerializableKey},
};
/// Iterates over children and displays them, keyed by the `key` function given.
///
/// This is much more efficient than naively iterating over nodes with `.iter().map(|n| view! { ... })...`,
/// as it avoids re-creating DOM nodes that are not being changed.
///
/// ```
/// # use leptos::prelude::*;
///
/// #[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// struct Counter {
/// id: usize,
/// count: RwSignal<i32>
/// }
///
/// #[component]
/// fn Counters() -> impl IntoView {
/// let (counters, set_counters) = create_signal::<Vec<Counter>>(vec![]);
///
/// view! {
/// <div>
/// <For
/// // a function that returns the items we're iterating over; a signal is fine
/// each=move || counters.get()
/// // a unique key for each item
/// key=|counter| counter.id
/// // renders each item to a view
/// children=move |counter: Counter| {
/// view! {
/// <button>"Value: " {move || counter.count.get()}</button>
/// }
/// }
/// />
/// </div>
/// }
/// }
/// ```
///
/// For convenience, you can also choose to write template code directly in the `<For>`
/// component, using the `let` syntax:
///
/// ```
/// # use leptos::prelude::*;
///
/// # #[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// # struct Counter {
/// # id: usize,
/// # count: RwSignal<i32>
/// # }
/// #
/// # #[component]
/// # fn Counters() -> impl IntoView {
/// # let (counters, set_counters) = create_signal::<Vec<Counter>>(vec![]);
/// #
/// view! {
/// <div>
/// <For
/// each=move || counters.get()
/// key=|counter| counter.id
/// let(counter)
/// >
/// <button>"Value: " {move || counter.count.get()}</button>
/// </For>
/// </div>
/// }
/// # }
/// ```
///
/// The `let` syntax also supports destructuring the pattern of your data.
/// `let((one, two))` in the case of tuples, and `let(Struct { field_one, field_two })`
/// in the case of structs.
///
/// ```
/// # use leptos::prelude::*;
///
/// # #[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// # struct Counter {
/// # id: usize,
/// # count: RwSignal<i32>
/// # }
/// #
/// # #[component]
/// # fn Counters() -> impl IntoView {
/// # let (counters, set_counters) = create_signal::<Vec<Counter>>(vec![]);
/// #
/// view! {
/// <div>
/// <For
/// each=move || counters.get()
/// key=|counter| counter.id
/// let(Counter { id, count })
/// >
/// <button>"Value: " {move || count.get()}</button>
/// </For>
/// </div>
/// }
/// # }
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
#[component]
pub fn For<IF, I, T, EF, N, KF, K>(
/// Items over which the component should iterate.
each: IF,
/// A key function that will be applied to each item.
key: KF,
/// A function that takes the item, and returns the view that will be displayed for each item.
children: EF,
) -> impl IntoView
where
IF: Fn() -> I + Send + 'static,
I: IntoIterator<Item = T> + Send + 'static,
EF: Fn(T) -> N + Send + Clone + 'static,
N: IntoView + 'static,
KF: Fn(&T) -> K + Send + Clone + 'static,
K: Eq + Hash + SerializableKey + 'static,
T: Send + 'static,
{
// this takes the owner of the For itself
// this will end up with N + 1 children
// 1) the effect for the `move || keyed(...)` updates
// 2) an owner for each child
//
// this means
// a) the reactive owner for each row will not be cleared when the whole list updates
// b) context provided in each row will not wipe out the others
let parent = Owner::current().expect("no reactive owner");
let children = move |_, child| {
let owner = parent.with(Owner::new);
let view = owner.with(|| children(child));
(|_| {}, OwnedView::new_with_owner(view, owner))
};
move || keyed(each(), key.clone(), children.clone())
}
/// Iterates over children and displays them, keyed by the `key` function given.
///
/// Compared with For, it has an additional index parameter, which can be used to obtain the current index in real time.
///
/// This is much more efficient than naively iterating over nodes with `.iter().map(|n| view! { ... })...`,
/// as it avoids re-creating DOM nodes that are not being changed.
///
/// ```
/// # use leptos::prelude::*;
///
/// #[derive(Copy, Clone, Debug, PartialEq, Eq)]
/// struct Counter {
/// id: usize,
/// count: RwSignal<i32>
/// }
///
/// #[component]
/// fn Counters() -> impl IntoView {
/// let (counters, set_counters) = create_signal::<Vec<Counter>>(vec![]);
///
/// view! {
/// <div>
/// <ForEnumerate
/// // a function that returns the items we're iterating over; a signal is fine
/// each=move || counters.get()
/// // a unique key for each item
/// key=|counter| counter.id
/// // renders each item to a view
/// children={move |index: ReadSignal<usize>, counter: Counter| {
/// view! {
/// <button>{move || index.get()} ". Value: " {move || counter.count.get()}</button>
/// }
/// }}
/// />
/// </div>
/// }
/// }
/// ```
#[cfg_attr(feature = "tracing", tracing::instrument(level = "trace", skip_all))]
#[component]
pub fn ForEnumerate<IF, I, T, EF, N, KF, K>(
/// Items over which the component should iterate.
each: IF,
/// A key function that will be applied to each item.
key: KF,
/// A function that takes the index and the item, and returns the view that will be displayed for each item.
children: EF,
) -> impl IntoView
where
IF: Fn() -> I + Send + 'static,
I: IntoIterator<Item = T> + Send + 'static,
EF: Fn(ReadSignal<usize>, T) -> N + Send + Clone + 'static,
N: IntoView + 'static,
KF: Fn(&T) -> K + Send + Clone + 'static,
K: Eq + Hash + SerializableKey + 'static,
T: Send + 'static,
{
// this takes the owner of the For itself
// this will end up with N + 1 children
// 1) the effect for the `move || keyed(...)` updates
// 2) an owner for each child
//
// this means
// a) the reactive owner for each row will not be cleared when the whole list updates
// b) context provided in each row will not wipe out the others
let parent = Owner::current().expect("no reactive owner");
let children = move |index, child| {
let owner = parent.with(Owner::new);
let (index, set_index) = ArcRwSignal::new(index).split();
let view = owner.with(|| children(index.into(), child));
(
move |index| set_index.set(index),
OwnedView::new_with_owner(view, owner),
)
};
move || keyed(each(), key.clone(), children.clone())
}
/*
#[cfg(test)]
mod tests {
use crate::prelude::*;
use leptos_macro::view;
use tachys::{html::element::HtmlElement, prelude::ElementChild};
#[test]
fn creates_list() {
Owner::new().with(|| {
let values = RwSignal::new(vec![1, 2, 3, 4, 5]);
let list: View<HtmlElement<_, _, _>> = view! {
<ol>
<For each=move || values.get() key=|i| *i let:i>
<li>{i}</li>
</For>
</ol>
};
assert_eq!(
list.to_html(),
"<ol><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><!></\
ol>"
);
});
}
#[test]
fn creates_list_enumerate() {
Owner::new().with(|| {
let values = RwSignal::new(vec![1, 2, 3, 4, 5]);
let list: View<HtmlElement<_, _, _>> = view! {
<ol>
<ForEnumerate each=move || values.get() key=|i| *i let(index, i)>
<li>{move || index.get()}"-"{i}</li>
</ForEnumerate>
</ol>
};
assert_eq!(
list.to_html(),
"<ol><li>0<!>-<!>1</li><li>1<!>-<!>2</li><li>2<!>-<!>3</li><li>3\
<!>-<!>4</li><li>4<!>-<!>5</li><!></ol>"
);
let list: View<HtmlElement<_, _, _>> = view! {
<ol>
<ForEnumerate each=move || values.get() key=|i| *i let(index, i)>
<li>{move || index.get()}"-"{i}</li>
</ForEnumerate>
</ol>
};
values.set(vec![5, 4, 1, 2, 3]);
assert_eq!(
list.to_html(),
"<ol><li>0<!>-<!>5</li><li>1<!>-<!>4</li><li>2<!>-<!>1</li><li>3\
<!>-<!>2</li><li>4<!>-<!>3</li><!></ol>"
);
});
}
}
*/
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/from_form_data.rs | leptos/src/from_form_data.rs | rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false | |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/await_.rs | leptos/src/await_.rs | use crate::{prelude::Suspend, suspense_component::Suspense, IntoView};
use leptos_macro::{component, view};
use leptos_server::ArcOnceResource;
use reactive_graph::prelude::ReadUntracked;
use serde::{de::DeserializeOwned, Serialize};
#[component]
/// Allows you to inline the data loading for an `async` block or
/// server function directly into your view. This is the equivalent of combining a
/// [`create_resource`] that only loads once (i.e., with a source signal `|| ()`) with
/// a [`Suspense`] with no `fallback`.
///
/// Adding `let:{variable name}` to the props makes the data available in the children
/// that variable name, when resolved.
/// ```
/// # use leptos::prelude::*;
/// # if false {
/// async fn fetch_monkeys(monkey: i32) -> i32 {
/// // do some expensive work
/// 3
/// }
///
/// view! {
/// <Await
/// future=fetch_monkeys(3)
/// let:data
/// >
/// <p>{*data} " little monkeys, jumping on the bed."</p>
/// </Await>
/// }
/// # ;
/// # }
/// ```
pub fn Await<T, Fut, Chil, V>(
/// A [`Future`](std::future::Future) that will the component will `.await`
/// before rendering.
future: Fut,
/// If `true`, the component will create a blocking resource, preventing
/// the HTML stream from returning anything before `future` has resolved.
#[prop(optional)]
blocking: bool,
/// A function that takes a reference to the resolved data from the `future`
/// renders a view.
///
/// ## Syntax
/// This can be passed in the `view` children of the `<Await/>` by using the
/// `let:` syntax to specify the name for the data variable.
///
/// ```rust
/// # use leptos::prelude::*;
/// # if false {
/// # async fn fetch_monkeys(monkey: i32) -> i32 {
/// # 3
/// # }
/// view! {
/// <Await
/// future=fetch_monkeys(3)
/// let:data
/// >
/// <p>{*data} " little monkeys, jumping on the bed."</p>
/// </Await>
/// }
/// # ;
/// # }
/// ```
/// is the same as
/// ```rust
/// # use leptos::prelude::*;
/// # if false {
/// # async fn fetch_monkeys(monkey: i32) -> i32 {
/// # 3
/// # }
/// view! {
/// <Await
/// future=fetch_monkeys(3)
/// children=|data| view! {
/// <p>{*data} " little monkeys, jumping on the bed."</p>
/// }
/// />
/// }
/// # ;
/// # }
/// ```
children: Chil,
) -> impl IntoView
where
T: Send + Sync + Serialize + DeserializeOwned + 'static,
Fut: std::future::Future<Output = T> + Send + 'static,
Chil: FnOnce(&T) -> V + Send + 'static,
V: IntoView + 'static,
{
let res = ArcOnceResource::<T>::new_with_options(future, blocking);
let ready = res.ready();
view! {
<Suspense fallback=|| ()>
{Suspend::new(async move {
ready.await;
children(res.read_untracked().as_ref().unwrap())
})}
</Suspense>
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/children.rs | leptos/src/children.rs | use crate::into_view::{IntoView, View};
use std::{
fmt::{self, Debug},
sync::Arc,
};
use tachys::view::{
any_view::{AnyView, IntoAny},
fragment::{Fragment, IntoFragment},
RenderHtml,
};
/// The most common type for the `children` property on components,
/// which can only be called once.
///
/// This does not support iterating over individual nodes within the children.
/// To iterate over children, use [`ChildrenFragment`].
pub type Children = Box<dyn FnOnce() -> AnyView + Send>;
/// A type for the `children` property on components that can be called only once,
/// and provides a collection of all the children passed to this component.
pub type ChildrenFragment = Box<dyn FnOnce() -> Fragment + Send>;
/// A type for the `children` property on components that can be called
/// more than once.
pub type ChildrenFn = Arc<dyn Fn() -> AnyView + Send + Sync>;
/// A type for the `children` property on components that can be called more than once,
/// and provides a collection of all the children passed to this component.
pub type ChildrenFragmentFn = Arc<dyn Fn() -> Fragment + Send>;
/// A type for the `children` property on components that can be called
/// more than once, but may mutate the children.
pub type ChildrenFnMut = Box<dyn FnMut() -> AnyView + Send>;
/// A type for the `children` property on components that can be called more than once,
/// but may mutate the children, and provides a collection of all the children
/// passed to this component.
pub type ChildrenFragmentMut = Box<dyn FnMut() -> Fragment + Send>;
// This is to still support components that accept `Box<dyn Fn() -> AnyView>` as a children.
type BoxedChildrenFn = Box<dyn Fn() -> AnyView + Send>;
/// This trait can be used when constructing a component that takes children without needing
/// to know exactly what children type the component expects. This is used internally by the
/// `view!` macro implementation, and can also be used explicitly when using the builder syntax.
///
///
/// Different component types take different types for their `children` prop, some of which cannot
/// be directly constructed. Using `ToChildren` allows the component user to pass children without
/// explicitly constructing the correct type.
///
/// ## Examples
///
/// ```
/// # use leptos::prelude::*;
/// # use leptos::html::p;
/// # use leptos::IntoView;
/// # use leptos_macro::component;
/// # use leptos::children::ToChildren;
/// use leptos::context::{Provider, ProviderProps};
/// use leptos::control_flow::{Show, ShowProps};
///
/// #[component]
/// fn App() -> impl IntoView {
/// (
/// Provider(
/// ProviderProps::builder()
/// .children(ToChildren::to_children(|| {
/// p().child("Foo")
/// }))
/// // ...
/// .value("Foo")
/// .build(),
/// ),
/// Show(
/// ShowProps::builder()
/// .children(ToChildren::to_children(|| {
/// p().child("Foo")
/// }))
/// // ...
/// .when(|| true)
/// .fallback(|| p().child("foo"))
/// .build(),
/// )
/// )
/// }
pub trait ToChildren<F> {
/// Convert the provided type (generally a closure) to Self (generally a "children" type,
/// e.g., [Children]). See the implementations to see exactly which input types are supported
/// and which "children" type they are converted to.
fn to_children(f: F) -> Self;
}
/// Compiler optimisation, can be used with certain type to avoid unique closures in the view!{} macro.
pub struct ChildrenOptContainer<T>(pub T);
impl<F, C> ToChildren<F> for Children
where
F: FnOnce() -> C + Send + 'static,
C: RenderHtml + Send + 'static,
{
#[inline]
fn to_children(f: F) -> Self {
Box::new(move || f().into_any())
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for Children
where
T: IntoAny + Send + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
Box::new(move || t.0.into_any())
}
}
impl<F, C> ToChildren<F> for ChildrenFn
where
F: Fn() -> C + Send + Sync + 'static,
C: RenderHtml + Send + 'static,
{
#[inline]
fn to_children(f: F) -> Self {
Arc::new(move || f().into_any())
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for ChildrenFn
where
T: IntoAny + Clone + Send + Sync + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
Arc::new(move || t.0.clone().into_any())
}
}
impl<F, C> ToChildren<F> for ChildrenFnMut
where
F: Fn() -> C + Send + 'static,
C: RenderHtml + Send + 'static,
{
#[inline]
fn to_children(f: F) -> Self {
Box::new(move || f().into_any())
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for ChildrenFnMut
where
T: IntoAny + Clone + Send + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
Box::new(move || t.0.clone().into_any())
}
}
impl<F, C> ToChildren<F> for BoxedChildrenFn
where
F: Fn() -> C + Send + 'static,
C: RenderHtml + Send + 'static,
{
#[inline]
fn to_children(f: F) -> Self {
Box::new(move || f().into_any())
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for BoxedChildrenFn
where
T: IntoAny + Clone + Send + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
Box::new(move || t.0.clone().into_any())
}
}
impl<F, C> ToChildren<F> for ChildrenFragment
where
F: FnOnce() -> C + Send + 'static,
C: IntoFragment,
{
#[inline]
fn to_children(f: F) -> Self {
Box::new(move || f().into_fragment())
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for ChildrenFragment
where
T: IntoAny + Send + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
Box::new(move || Fragment::new(vec![t.0.into_any()]))
}
}
impl<F, C> ToChildren<F> for ChildrenFragmentFn
where
F: Fn() -> C + Send + 'static,
C: IntoFragment,
{
#[inline]
fn to_children(f: F) -> Self {
Arc::new(move || f().into_fragment())
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for ChildrenFragmentFn
where
T: IntoAny + Clone + Send + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
Arc::new(move || Fragment::new(vec![t.0.clone().into_any()]))
}
}
impl<F, C> ToChildren<F> for ChildrenFragmentMut
where
F: FnMut() -> C + Send + 'static,
C: IntoFragment,
{
#[inline]
fn to_children(mut f: F) -> Self {
Box::new(move || f().into_fragment())
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for ChildrenFragmentMut
where
T: IntoAny + Clone + Send + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
Box::new(move || Fragment::new(vec![t.0.clone().into_any()]))
}
}
/// New-type wrapper for a function that returns a view with `From` and `Default` traits implemented
/// to enable optional props in for example `<Show>` and `<Suspense>`.
#[derive(Clone)]
pub struct ViewFn(Arc<dyn Fn() -> AnyView + Send + Sync + 'static>);
impl Default for ViewFn {
fn default() -> Self {
Self(Arc::new(|| ().into_any()))
}
}
impl<F, C> From<F> for ViewFn
where
F: Fn() -> C + Send + Sync + 'static,
C: RenderHtml + Send + 'static,
{
fn from(value: F) -> Self {
Self(Arc::new(move || value().into_any()))
}
}
impl<C> From<View<C>> for ViewFn
where
C: Clone + Send + Sync + 'static,
View<C>: IntoAny,
{
fn from(value: View<C>) -> Self {
Self(Arc::new(move || value.clone().into_any()))
}
}
impl ViewFn {
/// Execute the wrapped function
pub fn run(&self) -> AnyView {
(self.0)()
}
}
/// New-type wrapper for a function, which will only be called once and returns a view with `From` and
/// `Default` traits implemented to enable optional props in for example `<Show>` and `<Suspense>`.
pub struct ViewFnOnce(Box<dyn FnOnce() -> AnyView + Send + 'static>);
impl Default for ViewFnOnce {
fn default() -> Self {
Self(Box::new(|| ().into_any()))
}
}
impl<F, C> From<F> for ViewFnOnce
where
F: FnOnce() -> C + Send + 'static,
C: RenderHtml + Send + 'static,
{
fn from(value: F) -> Self {
Self(Box::new(move || value().into_any()))
}
}
impl<C> From<View<C>> for ViewFnOnce
where
C: Send + Sync + 'static,
View<C>: IntoAny,
{
fn from(value: View<C>) -> Self {
Self(Box::new(move || value.into_any()))
}
}
impl ViewFnOnce {
/// Execute the wrapped function
pub fn run(self) -> AnyView {
(self.0)()
}
}
/// A typed equivalent to [`Children`], which takes a generic but preserves type information to
/// allow the compiler to optimize the view more effectively.
pub struct TypedChildren<T>(Box<dyn FnOnce() -> View<T> + Send>);
impl<T> TypedChildren<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> impl FnOnce() -> View<T> + Send {
self.0
}
}
impl<F, C> ToChildren<F> for TypedChildren<C>
where
F: FnOnce() -> C + Send + 'static,
C: IntoView,
C::AsyncOutput: Send,
{
#[inline]
fn to_children(f: F) -> Self {
TypedChildren(Box::new(move || f().into_view()))
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for TypedChildren<T>
where
T: IntoView + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
TypedChildren(Box::new(move || t.0.into_view()))
}
}
/// A typed equivalent to [`ChildrenFnMut`], which takes a generic but preserves type information to
/// allow the compiler to optimize the view more effectively.
pub struct TypedChildrenMut<T>(Box<dyn FnMut() -> View<T> + Send>);
impl<T> Debug for TypedChildrenMut<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("TypedChildrenMut").finish()
}
}
impl<T> TypedChildrenMut<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> impl FnMut() -> View<T> + Send {
self.0
}
}
impl<F, C> ToChildren<F> for TypedChildrenMut<C>
where
F: FnMut() -> C + Send + 'static,
C: IntoView,
C::AsyncOutput: Send,
{
#[inline]
fn to_children(mut f: F) -> Self {
TypedChildrenMut(Box::new(move || f().into_view()))
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for TypedChildrenMut<T>
where
T: IntoView + Clone + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
TypedChildrenMut(Box::new(move || t.0.clone().into_view()))
}
}
/// A typed equivalent to [`ChildrenFn`], which takes a generic but preserves type information to
/// allow the compiler to optimize the view more effectively.
pub struct TypedChildrenFn<T>(Arc<dyn Fn() -> View<T> + Send + Sync>);
impl<T> Debug for TypedChildrenFn<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("TypedChildrenFn").finish()
}
}
impl<T> Clone for TypedChildrenFn<T> {
// Manual implementation to avoid the `T: Clone` bound.
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> TypedChildrenFn<T> {
/// Extracts the inner `children` function.
pub fn into_inner(self) -> Arc<dyn Fn() -> View<T> + Send + Sync> {
self.0
}
}
impl<F, C> ToChildren<F> for TypedChildrenFn<C>
where
F: Fn() -> C + Send + Sync + 'static,
C: IntoView,
C::AsyncOutput: Send,
{
#[inline]
fn to_children(f: F) -> Self {
TypedChildrenFn(Arc::new(move || f().into_view()))
}
}
impl<T> ToChildren<ChildrenOptContainer<T>> for TypedChildrenFn<T>
where
T: IntoView + Clone + Sync + 'static,
{
#[inline]
fn to_children(t: ChildrenOptContainer<T>) -> Self {
TypedChildrenFn(Arc::new(move || t.0.clone().into_view()))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/attribute_interceptor.rs | leptos/src/attribute_interceptor.rs | use crate::attr::{
any_attribute::{AnyAttribute, IntoAnyAttribute},
Attribute, NextAttribute,
};
use leptos::prelude::*;
/// Function stored to build/rebuild the wrapped children when attributes are added.
type ChildBuilder<T> = dyn Fn(AnyAttribute) -> T + Send + Sync + 'static;
/// Intercepts attributes passed to your component, allowing passing them to any element.
///
/// By default, Leptos passes any attributes passed to your component (e.g. `<MyComponent
/// attr:class="some-class"/>`) to the top-level element in the view returned by your component.
/// [`AttributeInterceptor`] allows you to intercept this behavior and pass it onto any element in
/// your component instead.
///
/// Must be the top level element in your component's view.
///
/// ## Example
///
/// Any attributes passed to MyComponent will be passed to the #inner element.
///
/// ```
/// # use leptos::prelude::*;
/// use leptos::attribute_interceptor::AttributeInterceptor;
///
/// #[component]
/// pub fn MyComponent() -> impl IntoView {
/// view! {
/// <AttributeInterceptor let:attrs>
/// <div id="wrapper">
/// <div id="inner" {..attrs} />
/// </div>
/// </AttributeInterceptor>
/// }
/// }
/// ```
#[component(transparent)]
pub fn AttributeInterceptor<Chil, T>(
/// The elements that will be rendered, with the attributes this component received as a
/// parameter.
children: Chil,
) -> impl IntoView
where
Chil: Fn(AnyAttribute) -> T + Send + Sync + 'static,
T: IntoView + 'static,
{
AttributeInterceptorInner::new(children)
}
/// Wrapper to intercept attributes passed to a component so you can apply them to a different
/// element.
struct AttributeInterceptorInner<T: IntoView, A> {
children_builder: Box<ChildBuilder<T>>,
children: T,
attributes: A,
}
impl<T: IntoView> AttributeInterceptorInner<T, ()> {
/// Use this as the returned view from your component to collect the attributes that are passed
/// to your component so you can manually handle them.
pub fn new<F>(children: F) -> Self
where
F: Fn(AnyAttribute) -> T + Send + Sync + 'static,
{
let children_builder = Box::new(children);
let children = children_builder(().into_any_attr());
Self {
children_builder,
children,
attributes: (),
}
}
}
impl<T: IntoView, A: Attribute> Render for AttributeInterceptorInner<T, A> {
type State = <T as Render>::State;
fn build(self) -> Self::State {
self.children.build()
}
fn rebuild(self, state: &mut Self::State) {
self.children.rebuild(state);
}
}
impl<T: IntoView + 'static, A> AddAnyAttr for AttributeInterceptorInner<T, A>
where
A: Attribute,
{
type Output<SomeNewAttr: leptos::attr::Attribute> =
AttributeInterceptorInner<T, <<A as NextAttribute>::Output<SomeNewAttr> as Attribute>::CloneableOwned>;
fn add_any_attr<NewAttr: leptos::attr::Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let attributes =
self.attributes.add_any_attr(attr).into_cloneable_owned();
let children =
(self.children_builder)(attributes.clone().into_any_attr());
AttributeInterceptorInner {
children_builder: self.children_builder,
children,
attributes,
}
}
}
impl<T: IntoView + 'static, A: Attribute> RenderHtml
for AttributeInterceptorInner<T, A>
{
type AsyncOutput = T::AsyncOutput;
type Owned = AttributeInterceptorInner<T, A::CloneableOwned>;
const MIN_LENGTH: usize = T::MIN_LENGTH;
fn dry_resolve(&mut self) {
self.children.dry_resolve()
}
fn resolve(
self,
) -> impl std::future::Future<Output = Self::AsyncOutput> + Send {
self.children.resolve()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut leptos::tachys::view::Position,
escape: bool,
mark_branches: bool,
_extra_attrs: Vec<AnyAttribute>,
) {
self.children.to_html_with_buf(
buf,
position,
escape,
mark_branches,
vec![],
)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &leptos::tachys::hydration::Cursor,
position: &leptos::tachys::view::PositionState,
) -> Self::State {
self.children.hydrate::<FROM_SERVER>(cursor, position)
}
async fn hydrate_async(
self,
cursor: &leptos::tachys::hydration::Cursor,
position: &leptos::tachys::view::PositionState,
) -> Self::State {
self.children.hydrate_async(cursor, position).await
}
fn into_owned(self) -> Self::Owned {
AttributeInterceptorInner {
children_builder: self.children_builder,
children: self.children,
attributes: self.attributes.into_cloneable_owned(),
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/show.rs | leptos/src/show.rs | use crate::{
children::{TypedChildrenFn, ViewFn},
IntoView,
};
use leptos_macro::component;
use reactive_graph::{computed::ArcMemo, traits::Get};
use tachys::either::Either;
#[component]
pub fn Show<W, C>(
/// The children will be shown whenever the condition in the `when` closure returns `true`.
children: TypedChildrenFn<C>,
/// A closure that returns a bool that determines whether this thing runs
when: W,
/// A closure that returns what gets rendered if the when statement is false. By default this is the empty view.
#[prop(optional, into)]
fallback: ViewFn,
) -> impl IntoView
where
W: Fn() -> bool + Send + Sync + 'static,
C: IntoView + 'static,
{
let memoized_when = ArcMemo::new(move |_| when());
let children = children.into_inner();
move || match memoized_when.get() {
true => Either::Left(children()),
false => Either::Right(fallback.run()),
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/logging.rs | leptos/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 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)*) => {
{
#[cfg(debug_assertions)]
{
$crate::warn!($($x)*)
}
#[cfg(not(debug_assertions))]
{
($($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 `println!()` (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 `println!()` (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 an error 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_warn(s: &str) {
#[cfg(debug_assertions)]
{
if log_to_stdout() {
eprintln!("{s}");
} else {
web_sys::console::warn_1(&JsValue::from_str(s));
}
}
#[cfg(not(debug_assertions))]
{
let _ = s;
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/suspense_component.rs | leptos/src/suspense_component.rs | use crate::{
children::{TypedChildren, ViewFnOnce},
error::ErrorBoundarySuspendedChildren,
IntoView,
};
use futures::{channel::oneshot, select, FutureExt};
use hydration_context::SerializedDataId;
use leptos_macro::component;
use or_poisoned::OrPoisoned;
use reactive_graph::{
computed::{
suspense::{LocalResourceNotifier, SuspenseContext},
ArcMemo, ScopedFuture,
},
effect::RenderEffect,
owner::{provide_context, use_context, Owner},
signal::ArcRwSignal,
traits::{
Dispose, Get, Read, ReadUntracked, Track, With, WithUntracked,
WriteValue,
},
};
use slotmap::{DefaultKey, SlotMap};
use std::sync::{Arc, Mutex};
use tachys::{
either::Either,
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
reactive_graph::{OwnedView, OwnedViewState},
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr,
either::{EitherKeepAlive, EitherKeepAliveState},
Mountable, Position, PositionState, Render, RenderHtml,
},
};
use throw_error::ErrorHookFuture;
/// If any [`Resource`](crate::prelude::Resource) is read in the `children` of this
/// component, it will show the `fallback` while they are loading. Once all are resolved,
/// it will render the `children`.
///
/// Each time one of the resources is loading again, it will fall back. To keep the current
/// children instead, use [Transition](crate::prelude::Transition).
///
/// Note that the `children` will be rendered initially (in order to capture the fact that
/// those resources are read under the suspense), so you cannot assume that resources read
/// synchronously have
/// `Some` value in `children`. However, you can read resources asynchronously by using
/// [Suspend](crate::prelude::Suspend).
///
/// ```
/// # use leptos::prelude::*;
/// # if false { // don't run in doctests
/// async fn fetch_cats(how_many: u32) -> Vec<String> { vec![] }
///
/// let (cat_count, set_cat_count) = signal::<u32>(1);
///
/// let cats = Resource::new(move || cat_count.get(), |count| fetch_cats(count));
///
/// view! {
/// <div>
/// <Suspense fallback=move || view! { <p>"Loading (Suspense Fallback)..."</p> }>
/// // you can access a resource synchronously
/// {move || {
/// cats.get().map(|data| {
/// data
/// .into_iter()
/// .map(|src| {
/// view! {
/// <img src={src}/>
/// }
/// })
/// .collect_view()
/// })
/// }
/// }
/// // or you can use `Suspend` to read resources asynchronously
/// {move || Suspend::new(async move {
/// cats.await
/// .into_iter()
/// .map(|src| {
/// view! {
/// <img src={src}/>
/// }
/// })
/// .collect_view()
/// })}
/// </Suspense>
/// </div>
/// }
/// # ;}
/// ```
#[component]
pub fn Suspense<Chil>(
/// A function that returns a fallback that will be shown while resources are still loading.
/// By default this is an empty view.
#[prop(optional, into)]
fallback: ViewFnOnce,
/// Children will be rendered once initially to catch any resource reads, then hidden until all
/// data have loaded.
children: TypedChildren<Chil>,
) -> impl IntoView
where
Chil: IntoView + Send + 'static,
{
let error_boundary_parent = use_context::<ErrorBoundarySuspendedChildren>();
let owner = Owner::new();
owner.with(|| {
let (starts_local, id) = {
Owner::current_shared_context()
.map(|sc| {
let id = sc.next_id();
(sc.get_incomplete_chunk(&id), id)
})
.unwrap_or_else(|| (false, Default::default()))
};
let fallback = fallback.run();
let children = children.into_inner()();
let tasks = ArcRwSignal::new(SlotMap::<DefaultKey, ()>::new());
provide_context(SuspenseContext {
tasks: tasks.clone(),
});
let none_pending = ArcMemo::new({
let tasks = tasks.clone();
move |prev: Option<&bool>| {
tasks.track();
if prev.is_none() && starts_local {
false
} else {
tasks.with(SlotMap::is_empty)
}
}
});
let has_tasks =
Arc::new(move || !tasks.with_untracked(SlotMap::is_empty));
OwnedView::new(SuspenseBoundary::<false, _, _> {
id,
none_pending,
fallback,
children,
error_boundary_parent,
has_tasks,
})
})
}
fn nonce_or_not() -> Option<Arc<str>> {
#[cfg(feature = "nonce")]
{
use crate::nonce::Nonce;
use_context::<Nonce>().map(|n| n.0)
}
#[cfg(not(feature = "nonce"))]
{
None
}
}
pub(crate) struct SuspenseBoundary<const TRANSITION: bool, Fal, Chil> {
pub id: SerializedDataId,
pub none_pending: ArcMemo<bool>,
pub fallback: Fal,
pub children: Chil,
pub error_boundary_parent: Option<ErrorBoundarySuspendedChildren>,
pub has_tasks: Arc<dyn Fn() -> bool + Send + Sync>,
}
impl<const TRANSITION: bool, Fal, Chil> Render
for SuspenseBoundary<TRANSITION, Fal, Chil>
where
Fal: Render + Send + 'static,
Chil: Render + Send + 'static,
{
type State = RenderEffect<
OwnedViewState<EitherKeepAliveState<Chil::State, Fal::State>>,
>;
fn build(self) -> Self::State {
let mut children = Some(self.children);
let mut fallback = Some(self.fallback);
let none_pending = self.none_pending;
let mut nth_run = 0;
let outer_owner = Owner::new();
RenderEffect::new(move |prev| {
// show the fallback if
// 1) there are pending futures, and
// 2) we are either in a Suspense (not Transition), or it's the first fallback
// (because we initially render the children to register Futures, the "first
// fallback" is probably the 2nd run
let show_b = !none_pending.get() && (!TRANSITION || nth_run < 2);
nth_run += 1;
let this = OwnedView::new_with_owner(
EitherKeepAlive {
a: children.take(),
b: fallback.take(),
show_b,
},
outer_owner.clone(),
);
let state = if let Some(mut state) = prev {
this.rebuild(&mut state);
state
} else {
this.build()
};
if nth_run == 1 && !(self.has_tasks)() {
// if this is the first run, and there are no pending resources at this point,
// it means that there were no actually-async resources read while rendering the children
// this means that we're effectively on the settled second run: none_pending
// won't change false => true and cause this to rerender (and therefore increment nth_run)
//
// we increment it manually here so that future resource changes won't cause the transition fallback
// to be displayed for the first time
// see https://github.com/leptos-rs/leptos/issues/3868, https://github.com/leptos-rs/leptos/issues/4492
nth_run += 1;
}
state
})
}
fn rebuild(self, state: &mut Self::State) {
let new = self.build();
let mut old = std::mem::replace(state, new);
old.insert_before_this(state);
old.unmount();
}
}
impl<const TRANSITION: bool, Fal, Chil> AddAnyAttr
for SuspenseBoundary<TRANSITION, Fal, Chil>
where
Fal: RenderHtml + Send + 'static,
Chil: RenderHtml + Send + 'static,
{
type Output<SomeNewAttr: Attribute> = SuspenseBoundary<
TRANSITION,
Fal,
Chil::Output<SomeNewAttr::CloneableOwned>,
>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let attr = attr.into_cloneable_owned();
let SuspenseBoundary {
id,
none_pending,
fallback,
children,
error_boundary_parent,
has_tasks,
} = self;
SuspenseBoundary {
id,
none_pending,
fallback,
children: children.add_any_attr(attr),
error_boundary_parent,
has_tasks,
}
}
}
impl<const TRANSITION: bool, Fal, Chil> RenderHtml
for SuspenseBoundary<TRANSITION, Fal, Chil>
where
Fal: RenderHtml + Send + 'static,
Chil: RenderHtml + Send + 'static,
{
// i.e., if this is the child of another Suspense during SSR, don't wait for it: it will handle
// itself
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = Chil::MIN_LENGTH;
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
self.fallback.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
mut self,
buf: &mut StreamBuilder,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) where
Self: Sized,
{
buf.next_id();
let suspense_context = use_context::<SuspenseContext>().unwrap();
let owner = Owner::current().unwrap();
let mut notify_error_boundary =
self.error_boundary_parent.map(|children| {
let (tx, rx) = oneshot::channel();
children.write_value().push(rx);
tx
});
// we need to wait for one of two things: either
// 1. all tasks are finished loading, or
// 2. we read from a local resource, meaning this Suspense can never resolve on the server
// first, create listener for tasks
let tasks = suspense_context.tasks.clone();
let (tasks_tx, mut tasks_rx) =
futures::channel::oneshot::channel::<()>();
let mut tasks_tx = Some(tasks_tx);
// now, create listener for local resources
let (local_tx, mut local_rx) =
futures::channel::oneshot::channel::<()>();
provide_context(LocalResourceNotifier::from(local_tx));
// walk over the tree of children once to make sure that all resource loads are registered
self.children.dry_resolve();
let children = Arc::new(Mutex::new(Some(self.children)));
// check the set of tasks to see if it is empty, now or later
let eff = reactive_graph::effect::Effect::new_isomorphic({
let children = Arc::clone(&children);
move |double_checking: Option<bool>| {
// on the first run, always track the tasks
if double_checking.is_none() {
tasks.track();
}
if let Some(curr_tasks) = tasks.try_read_untracked() {
if curr_tasks.is_empty() {
if double_checking == Some(true) {
// we have finished loading, and checking the children again told us there are
// no more pending tasks. so we can render both the children and the error boundary
if let Some(tx) = tasks_tx.take() {
// If the receiver has dropped, it means the ScopedFuture has already
// dropped, so it doesn't matter if we manage to send this.
_ = tx.send(());
}
if let Some(tx) = notify_error_boundary.take() {
_ = tx.send(());
}
} else {
// release the read guard on tasks, as we'll be updating it again
drop(curr_tasks);
// check the children for additional pending tasks
// the will catch additional resource reads nested inside a conditional depending on initial resource reads
if let Some(children) =
children.lock().or_poisoned().as_mut()
{
children.dry_resolve();
}
if tasks
.try_read()
.map(|n| n.is_empty())
.unwrap_or(false)
{
// there are no additional pending tasks, and we can simply return
if let Some(tx) = tasks_tx.take() {
// If the receiver has dropped, it means the ScopedFuture has already
// dropped, so it doesn't matter if we manage to send this.
_ = tx.send(());
}
if let Some(tx) = notify_error_boundary.take() {
_ = tx.send(());
}
}
// tell ourselves that we're just double-checking
return true;
}
} else {
tasks.track();
}
}
false
}
});
let mut fut = Box::pin(ScopedFuture::new(ErrorHookFuture::new(
async move {
// race the local resource notifier against the set of tasks
//
// if there are local resources, we just return the fallback immediately
//
// otherwise, we want to wait for resources to load before trying to resolve the body
//
// this is *less efficient* than just resolving the body
// however, it means that you can use reactive accesses to resources/async derived
// inside component props, at any level, and have those picked up by Suspense, and
// that it will wait for those to resolve
select! {
// if there are local resources, bail
// this will only have fired by this point for local resources accessed
// *synchronously*
_ = local_rx => {
let sc = Owner::current_shared_context().expect("no shared context");
sc.set_incomplete_chunk(self.id);
None
}
_ = tasks_rx => {
let children = {
let mut children_lock = children.lock().or_poisoned();
children_lock.take().expect("children should not be removed until we render here")
};
// if we ran this earlier, reactive reads would always be registered as None
// this is fine in the case where we want to use Suspend and .await on some future
// but in situations like a <For each=|| some_resource.snapshot()/> we actually
// want to be able to 1) synchronously read a resource's value, but still 2) wait
// for it to load before we render everything
let mut children = Box::pin(children.resolve().fuse());
// we continue racing the children against the "do we have any local
// resources?" Future
select! {
_ = local_rx => {
let sc = Owner::current_shared_context().expect("no shared context");
sc.set_incomplete_chunk(self.id);
None
}
children = children => {
// clean up the (now useless) effect
eff.dispose();
Some(OwnedView::new_with_owner(children, owner))
}
}
}
}
},
)));
match fut.as_mut().now_or_never() {
Some(Some(resolved)) => {
Either::<Fal, _>::Right(resolved)
.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
Some(None) => {
Either::<_, Chil>::Left(self.fallback)
.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
None => {
let id = buf.clone_id();
// out-of-order streams immediately push fallback,
// wrapped by suspense markers
if OUT_OF_ORDER {
let mut fallback_position = *position;
buf.push_fallback(
self.fallback,
&mut fallback_position,
mark_branches,
extra_attrs.clone(),
);
buf.push_async_out_of_order_with_nonce(
fut,
position,
mark_branches,
nonce_or_not(),
extra_attrs,
);
} else {
// calling this will walk over the tree, removing all event listeners
// and other single-threaded values from the view tree. this needs to be
// done because the fallback can be shifted to another thread in push_async below.
self.fallback.dry_resolve();
buf.push_async({
let mut position = *position;
async move {
let value = match fut.await {
None => Either::Left(self.fallback),
Some(value) => Either::Right(value),
};
let mut builder = StreamBuilder::new(id);
value.to_html_async_with_buf::<OUT_OF_ORDER>(
&mut builder,
&mut position,
escape,
mark_branches,
extra_attrs,
);
builder.finish().take_chunks()
}
});
*position = Position::NextChild;
}
}
};
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let cursor = cursor.to_owned();
let position = position.to_owned();
let mut children = Some(self.children);
let mut fallback = Some(self.fallback);
let none_pending = self.none_pending;
let mut nth_run = 0;
let outer_owner = Owner::new();
RenderEffect::new(move |prev| {
// show the fallback if
// 1) there are pending futures, and
// 2) we are either in a Suspense (not Transition), or it's the first fallback
// (because we initially render the children to register Futures, the "first
// fallback" is probably the 2nd run
let show_b = !none_pending.get() && (!TRANSITION || nth_run < 1);
nth_run += 1;
let this = OwnedView::new_with_owner(
EitherKeepAlive {
a: children.take(),
b: fallback.take(),
show_b,
},
outer_owner.clone(),
);
if let Some(mut state) = prev {
this.rebuild(&mut state);
state
} else {
this.hydrate::<FROM_SERVER>(&cursor, &position)
}
})
}
fn into_owned(self) -> Self::Owned {
self
}
}
/// A wrapper that prevents [`Suspense`] from waiting for any resource reads that happen inside
/// `Unsuspend`.
pub struct Unsuspend<T>(Box<dyn FnOnce() -> T + Send>);
impl<T> Unsuspend<T> {
/// Wraps the given function, such that it is not called until all resources are ready.
pub fn new(fun: impl FnOnce() -> T + Send + 'static) -> Self {
Self(Box::new(fun))
}
}
impl<T> Render for Unsuspend<T>
where
T: Render,
{
type State = T::State;
fn build(self) -> Self::State {
(self.0)().build()
}
fn rebuild(self, state: &mut Self::State) {
(self.0)().rebuild(state);
}
}
impl<T> AddAnyAttr for Unsuspend<T>
where
T: AddAnyAttr + 'static,
{
type Output<SomeNewAttr: Attribute> =
Unsuspend<T::Output<SomeNewAttr::CloneableOwned>>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let attr = attr.into_cloneable_owned();
Unsuspend::new(move || (self.0)().add_any_attr(attr))
}
}
impl<T> RenderHtml for Unsuspend<T>
where
T: RenderHtml + 'static,
{
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = T::MIN_LENGTH;
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
(self.0)().to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
self,
buf: &mut StreamBuilder,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) where
Self: Sized,
{
(self.0)().to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
(self.0)().hydrate::<FROM_SERVER>(cursor, position)
}
fn into_owned(self) -> Self::Owned {
self
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/provider.rs | leptos/src/provider.rs | use crate::{children::TypedChildren, component, IntoView};
use reactive_graph::owner::{provide_context, Owner};
use tachys::reactive_graph::OwnedView;
#[component]
/// Uses the context API to [`provide_context`] to its children and descendants,
/// without overwriting any contexts of the same type in its own reactive scope.
///
/// This prevents issues related to “context shadowing.”
///
/// ```rust
/// use leptos::{context::Provider, prelude::*};
///
/// #[component]
/// pub fn App() -> impl IntoView {
/// // each Provider will only provide the value to its children
/// view! {
/// <Provider value=1u8>
/// // correctly gets 1 from context
/// {use_context::<u8>().unwrap_or(0)}
/// </Provider>
/// <Provider value=2u8>
/// // correctly gets 2 from context
/// {use_context::<u8>().unwrap_or(0)}
/// </Provider>
/// // does not find any u8 in context
/// {use_context::<u8>().unwrap_or(0)}
/// }
/// }
/// ```
pub fn Provider<T, Chil>(
/// The value to be provided via context.
value: T,
children: TypedChildren<Chil>,
) -> impl IntoView
where
T: Send + Sync + 'static,
Chil: IntoView + 'static,
{
let owner = Owner::current()
.expect("no current reactive Owner found")
.child();
let children = children.into_inner();
let children = owner.with(|| {
provide_context(value);
children()
});
OwnedView::new_with_owner(children, owner)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/text_prop.rs | leptos/src/text_prop.rs | use oco_ref::Oco;
use std::sync::Arc;
use tachys::prelude::IntoAttributeValue;
/// Describes a value that is either a static or a reactive string, i.e.,
/// a [`String`], a [`&str`], a `Signal` or a reactive `Fn() -> String`.
#[derive(Clone)]
pub struct TextProp(Arc<dyn Fn() -> Oco<'static, str> + Send + Sync>);
impl TextProp {
/// Accesses the current value of the property.
#[inline(always)]
pub fn get(&self) -> Oco<'static, str> {
(self.0)()
}
}
impl core::fmt::Debug for TextProp {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("TextProp").finish()
}
}
impl From<String> for TextProp {
fn from(s: String) -> Self {
let s: Oco<'_, str> = Oco::Counted(Arc::from(s));
TextProp(Arc::new(move || s.clone()))
}
}
impl From<&'static str> for TextProp {
fn from(s: &'static str) -> Self {
let s: Oco<'_, str> = s.into();
TextProp(Arc::new(move || s.clone()))
}
}
impl From<Arc<str>> for TextProp {
fn from(s: Arc<str>) -> Self {
let s: Oco<'_, str> = s.into();
TextProp(Arc::new(move || s.clone()))
}
}
impl From<Oco<'static, str>> for TextProp {
fn from(s: Oco<'static, str>) -> Self {
TextProp(Arc::new(move || s.clone()))
}
}
// TODO
/*impl<T> From<T> for MaybeProp<TextProp>
where
T: Into<Oco<'static, str>>,
{
fn from(s: T) -> Self {
Self(Some(MaybeSignal::from(Some(s.into().into()))))
}
}*/
impl<F, S> From<F> for TextProp
where
F: Fn() -> S + 'static + Send + Sync,
S: Into<Oco<'static, str>>,
{
#[inline(always)]
fn from(s: F) -> Self {
TextProp(Arc::new(move || s().into()))
}
}
impl Default for TextProp {
fn default() -> Self {
Self(Arc::new(|| Oco::Borrowed("")))
}
}
impl IntoAttributeValue for TextProp {
type Output = Arc<dyn Fn() -> Oco<'static, str> + Send + Sync>;
fn into_attribute_value(self) -> Self::Output {
self.0
}
}
macro_rules! textprop_reactive {
($name:ident, <$($gen:ident),*>, $v:ty, $( $where_clause:tt )*) =>
{
#[allow(deprecated)]
impl<$($gen),*> From<$name<$($gen),*>> for TextProp
where
$v: Into<Oco<'static, str>> + Clone + Send + Sync + 'static,
$($where_clause)*
{
#[inline(always)]
fn from(s: $name<$($gen),*>) -> Self {
TextProp(Arc::new(move || s.get().into()))
}
}
};
}
#[cfg(not(feature = "nightly"))]
mod stable {
use super::TextProp;
use oco_ref::Oco;
#[allow(deprecated)]
use reactive_graph::wrappers::read::MaybeSignal;
use reactive_graph::{
computed::{ArcMemo, Memo},
owner::Storage,
signal::{ArcReadSignal, ArcRwSignal, ReadSignal, RwSignal},
traits::Get,
wrappers::read::{ArcSignal, Signal},
};
use std::sync::Arc;
textprop_reactive!(
RwSignal,
<V, S>,
V,
RwSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
textprop_reactive!(
ReadSignal,
<V, S>,
V,
ReadSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
textprop_reactive!(
Memo,
<V, S>,
V,
Memo<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
textprop_reactive!(
Signal,
<V, S>,
V,
Signal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
textprop_reactive!(
MaybeSignal,
<V, S>,
V,
MaybeSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
textprop_reactive!(ArcRwSignal, <V>, V, ArcRwSignal<V>: Get<Value = V>);
textprop_reactive!(ArcReadSignal, <V>, V, ArcReadSignal<V>: Get<Value = V>);
textprop_reactive!(ArcMemo, <V>, V, ArcMemo<V>: Get<Value = V>);
textprop_reactive!(ArcSignal, <V>, V, ArcSignal<V>: Get<Value = V>);
}
/// Extension trait for `Option<TextProp>`
pub trait OptionTextPropExt {
/// Accesses the current value of the `Option<TextProp>` as an `Option<Oco<'static, str>>`.
fn get(&self) -> Option<Oco<'static, str>>;
}
impl OptionTextPropExt for Option<TextProp> {
fn get(&self) -> Option<Oco<'static, str>> {
self.as_ref().map(|text_prop| text_prop.get())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/mount.rs | leptos/src/mount.rs | #[cfg(debug_assertions)]
use crate::logging;
use crate::IntoView;
use any_spawner::Executor;
use reactive_graph::owner::Owner;
#[cfg(debug_assertions)]
use std::cell::Cell;
use tachys::{
dom::body,
view::{Mountable, Render},
};
#[cfg(feature = "hydrate")]
use tachys::{
hydration::Cursor,
view::{PositionState, RenderHtml},
};
#[cfg(feature = "hydrate")]
use wasm_bindgen::JsCast;
use web_sys::HtmlElement;
#[cfg(feature = "hydrate")]
/// Hydrates the app described by the provided function, starting at `<body>`.
pub fn hydrate_body<F, N>(f: F)
where
F: FnOnce() -> N + 'static,
N: IntoView,
{
let owner = hydrate_from(body(), f);
owner.forget();
}
#[cfg(feature = "hydrate")]
/// Hydrates the app described by the provided function, starting at `<body>`, with support
/// for lazy-loaded routes and components.
pub fn hydrate_lazy<F, N>(f: F)
where
F: FnOnce() -> N + 'static,
N: IntoView,
{
// use wasm-bindgen-futures to drive the reactive system
// we ignore the return value because an Err here just means the wasm-bindgen executor is
// already initialized, which is not an issue
_ = Executor::init_wasm_bindgen();
crate::task::spawn_local(async move {
let owner = hydrate_from_async(body(), f).await;
owner.forget();
})
}
#[cfg(debug_assertions)]
thread_local! {
static FIRST_CALL: Cell<bool> = const { Cell::new(true) };
}
#[cfg(feature = "hydrate")]
/// Runs the provided closure and mounts the result to the provided element.
pub fn hydrate_from<F, N>(parent: HtmlElement, f: F) -> UnmountHandle<N::State>
where
F: FnOnce() -> N + 'static,
N: IntoView,
{
use hydration_context::HydrateSharedContext;
use std::sync::Arc;
// use wasm-bindgen-futures to drive the reactive system
// we ignore the return value because an Err here just means the wasm-bindgen executor is
// already initialized, which is not an issue
_ = Executor::init_wasm_bindgen();
#[cfg(debug_assertions)]
{
if !cfg!(feature = "hydrate") && FIRST_CALL.get() {
logging::warn!(
"It seems like you're trying to use Leptos in hydration mode, \
but the `hydrate` feature is not enabled on the `leptos` \
crate. Add `features = [\"hydrate\"]` to your Cargo.toml for \
the crate to work properly.\n\nNote that hydration and \
client-side rendering now use separate functions from \
leptos::mount: you are calling a hydration function."
);
}
FIRST_CALL.set(false);
}
// create a new reactive owner and use it as the root node to run the app
let owner = Owner::new_root(Some(Arc::new(HydrateSharedContext::new())));
let mountable = owner.with(move || {
let view = f().into_view();
view.hydrate::<true>(
&Cursor::new(parent.unchecked_into()),
&PositionState::default(),
)
});
if let Some(sc) = Owner::current_shared_context() {
sc.hydration_complete();
}
// returns a handle that owns the owner
// when this is dropped, it will clean up the reactive system and unmount the view
UnmountHandle { owner, mountable }
}
#[cfg(feature = "hydrate")]
/// Runs the provided closure and mounts the result to the provided element.
pub async fn hydrate_from_async<F, N>(
parent: HtmlElement,
f: F,
) -> UnmountHandle<N::State>
where
F: FnOnce() -> N + 'static,
N: IntoView,
{
use hydration_context::HydrateSharedContext;
use std::sync::Arc;
// use wasm-bindgen-futures to drive the reactive system
// we ignore the return value because an Err here just means the wasm-bindgen executor is
// already initialized, which is not an issue
_ = Executor::init_wasm_bindgen();
#[cfg(debug_assertions)]
{
if !cfg!(feature = "hydrate") && FIRST_CALL.get() {
logging::warn!(
"It seems like you're trying to use Leptos in hydration mode, \
but the `hydrate` feature is not enabled on the `leptos` \
crate. Add `features = [\"hydrate\"]` to your Cargo.toml for \
the crate to work properly.\n\nNote that hydration and \
client-side rendering now use separate functions from \
leptos::mount: you are calling a hydration function."
);
}
FIRST_CALL.set(false);
}
// create a new reactive owner and use it as the root node to run the app
let owner = Owner::new_root(Some(Arc::new(HydrateSharedContext::new())));
let mountable = owner
.with(move || {
use reactive_graph::computed::ScopedFuture;
ScopedFuture::new(async move {
let view = f().into_view();
view.hydrate_async(
&Cursor::new(parent.unchecked_into()),
&PositionState::default(),
)
.await
})
})
.await;
if let Some(sc) = Owner::current_shared_context() {
sc.hydration_complete();
}
// returns a handle that owns the owner
// when this is dropped, it will clean up the reactive system and unmount the view
UnmountHandle { owner, mountable }
}
/// Runs the provided closure and mounts the result to the `<body>`.
pub fn mount_to_body<F, N>(f: F)
where
F: FnOnce() -> N + 'static,
N: IntoView,
{
let owner = mount_to(body(), f);
owner.forget();
}
/// Runs the provided closure and mounts the result to the provided element.
pub fn mount_to<F, N>(parent: HtmlElement, f: F) -> UnmountHandle<N::State>
where
F: FnOnce() -> N + 'static,
N: IntoView,
{
// use wasm-bindgen-futures to drive the reactive system
// we ignore the return value because an Err here just means the wasm-bindgen executor is
// already initialized, which is not an issue
_ = Executor::init_wasm_bindgen();
#[cfg(debug_assertions)]
{
if !cfg!(feature = "csr") && FIRST_CALL.get() {
logging::warn!(
"It seems like you're trying to use Leptos in client-side \
rendering mode, but the `csr` feature is not enabled on the \
`leptos` crate. Add `features = [\"csr\"]` to your \
Cargo.toml for the crate to work properly.\n\nNote that \
hydration and client-side rendering now use different \
functions from leptos::mount. You are using a client-side \
rendering mount function."
);
}
FIRST_CALL.set(false);
}
// create a new reactive owner and use it as the root node to run the app
let owner = Owner::new();
let mountable = owner.with(move || {
let view = f().into_view();
let mut mountable = view.build();
mountable.mount(&parent, None);
mountable
});
// returns a handle that owns the owner
// when this is dropped, it will clean up the reactive system and unmount the view
UnmountHandle { owner, mountable }
}
/// Runs the provided closure and mounts the result to the provided element.
pub fn mount_to_renderer<F, N>(
parent: &tachys::renderer::types::Element,
f: F,
) -> UnmountHandle<N::State>
where
F: FnOnce() -> N + 'static,
N: Render,
{
// use wasm-bindgen-futures to drive the reactive system
// we ignore the return value because an Err here just means the wasm-bindgen executor is
// already initialized, which is not an issue
_ = Executor::init_wasm_bindgen();
// create a new reactive owner and use it as the root node to run the app
let owner = Owner::new();
let mountable = owner.with(move || {
let view = f();
let mut mountable = view.build();
mountable.mount(parent, None);
mountable
});
// returns a handle that owns the owner
// when this is dropped, it will clean up the reactive system and unmount the view
UnmountHandle { owner, mountable }
}
/// Hydrates any islands that are currently present on the page.
#[cfg(feature = "hydrate")]
pub fn hydrate_islands() {
use hydration_context::{HydrateSharedContext, SharedContext};
use std::sync::Arc;
// use wasm-bindgen-futures to drive the reactive system
// we ignore the return value because an Err here just means the wasm-bindgen executor is
// already initialized, which is not an issue
_ = Executor::init_wasm_bindgen();
#[cfg(debug_assertions)]
FIRST_CALL.set(false);
// create a new reactive owner and use it as the root node to run the app
let sc = HydrateSharedContext::new();
sc.set_is_hydrating(false); // islands mode starts in "not hydrating"
let owner = Owner::new_root(Some(Arc::new(sc)));
owner.set();
std::mem::forget(owner);
}
/// On drop, this will clean up the reactive [`Owner`] and unmount the view created by
/// [`mount_to`].
///
/// If you are using it to create the root of an application, you should use
/// [`UnmountHandle::forget`] to leak it.
#[must_use = "Dropping an `UnmountHandle` will unmount the view and cancel the \
reactive system. You should either call `.forget()` to keep the \
view permanently mounted, or store the `UnmountHandle` somewhere \
and drop it when you'd like to unmount the view."]
pub struct UnmountHandle<M>
where
M: Mountable,
{
#[allow(dead_code)]
owner: Owner,
mountable: M,
}
impl<M> UnmountHandle<M>
where
M: Mountable,
{
/// Leaks the handle, preventing the reactive system from being cleaned up and the view from
/// being unmounted. This should always be called when [`mount_to`] is used for the root of an
/// application that should live for the long term.
pub fn forget(self) {
std::mem::forget(self);
}
}
impl<M> Drop for UnmountHandle<M>
where
M: Mountable,
{
fn drop(&mut self) {
self.mountable.unmount();
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/component.rs | leptos/src/component.rs | //! Utility traits and functions that allow building components,
//! as either functions of their props or functions with no arguments,
//! without knowing the name of the props struct.
pub trait Component<P> {}
pub trait Props {
type Builder;
fn builder() -> Self::Builder;
}
#[doc(hidden)]
pub trait PropsOrNoPropsBuilder {
type Builder;
fn builder_or_not() -> Self::Builder;
}
#[doc(hidden)]
#[derive(Copy, Clone, Debug, Default)]
pub struct EmptyPropsBuilder {}
impl EmptyPropsBuilder {
pub fn build(self) {}
}
impl<P: Props> PropsOrNoPropsBuilder for P {
type Builder = <P as Props>::Builder;
fn builder_or_not() -> Self::Builder {
Self::builder()
}
}
impl PropsOrNoPropsBuilder for EmptyPropsBuilder {
type Builder = EmptyPropsBuilder;
fn builder_or_not() -> Self::Builder {
EmptyPropsBuilder {}
}
}
impl<F, R> Component<EmptyPropsBuilder> for F where F: FnOnce() -> R {}
impl<P, F, R> Component<P> for F
where
F: FnOnce(P) -> R,
P: Props,
{
}
pub fn component_props_builder<P: PropsOrNoPropsBuilder>(
_f: &impl Component<P>,
) -> <P as PropsOrNoPropsBuilder>::Builder {
<P as PropsOrNoPropsBuilder>::builder_or_not()
}
pub fn component_view<P, T>(f: impl ComponentConstructor<P, T>, props: P) -> T {
f.construct(props)
}
pub trait ComponentConstructor<P, T> {
fn construct(self, props: P) -> T;
}
impl<Func, T> ComponentConstructor<(), T> for Func
where
Func: FnOnce() -> T,
{
fn construct(self, (): ()) -> T {
(self)()
}
}
impl<Func, T, P> ComponentConstructor<P, T> for Func
where
Func: FnOnce(P) -> T,
P: PropsOrNoPropsBuilder,
{
fn construct(self, props: P) -> T {
(self)(props)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/src/hydration/mod.rs | leptos/src/hydration/mod.rs | #![allow(clippy::needless_lifetimes)]
use crate::{prelude::*, WasmSplitManifest};
use leptos_config::LeptosOptions;
use leptos_macro::{component, view};
use std::{path::PathBuf, sync::OnceLock};
/// Inserts auto-reloading code used in `cargo-leptos`.
///
/// This should be included in the `<head>` of your application shell during development.
#[component]
pub fn AutoReload(
/// Whether the file-watching feature should be disabled.
#[prop(optional)]
disable_watch: bool,
/// Configuration options for this project.
options: LeptosOptions,
) -> impl IntoView {
(!disable_watch && std::env::var("LEPTOS_WATCH").is_ok()).then(|| {
#[cfg(feature = "nonce")]
let nonce = crate::nonce::use_nonce();
#[cfg(not(feature = "nonce"))]
let nonce = None::<()>;
let reload_port = match options.reload_external_port {
Some(val) => val,
None => options.reload_port,
};
let protocol = match options.reload_ws_protocol {
leptos_config::ReloadWSProtocol::WS => "'ws://'",
leptos_config::ReloadWSProtocol::WSS => "'wss://'",
};
let script = format!(
"(function (reload_port, protocol) {{ {} {} }})({reload_port:?}, \
{protocol})",
leptos_hot_reload::HOT_RELOAD_JS,
include_str!("reload_script.js")
);
view! { <script nonce=nonce>{script}</script> }
})
}
/// Inserts hydration scripts that add interactivity to your server-rendered HTML.
///
/// This should be included in the `<head>` of your application shell.
#[component]
pub fn HydrationScripts(
/// Configuration options for this project.
options: LeptosOptions,
/// Should be `true` to hydrate in `islands` mode.
#[prop(optional)]
islands: bool,
/// Should be `true` to add the “islands router,” which enables limited client-side routing
/// when running in islands mode.
#[prop(optional)]
islands_router: bool,
/// A base url, not including a trailing slash
#[prop(optional, into)]
root: Option<String>,
) -> impl IntoView {
static SPLIT_MANIFEST: OnceLock<Option<WasmSplitManifest>> =
OnceLock::new();
if let Some(splits) = SPLIT_MANIFEST.get_or_init(|| {
let root = root.clone().unwrap_or_default();
let (wasm_split_js, wasm_split_manifest) = if options.hash_files {
let hash_path = std::env::current_exe()
.map(|path| {
path.parent().map(|p| p.to_path_buf()).unwrap_or_default()
})
.unwrap_or_default()
.join(options.hash_file.as_ref());
let hashes = std::fs::read_to_string(&hash_path)
.expect("failed to read hash file");
let mut split =
"__wasm_split.______________________.js".to_string();
let mut manifest = "__wasm_split_manifest.json".to_string();
for line in hashes.lines() {
let line = line.trim();
if !line.is_empty() {
if let Some((file, hash)) = line.split_once(':') {
if file == "manifest" {
manifest.clear();
manifest.push_str("__wasm_split_manifest.");
manifest.push_str(hash.trim());
manifest.push_str(".json");
}
if file == "split" {
split.clear();
split.push_str("__wasm_split.");
split.push_str(hash.trim());
split.push_str(".js");
}
}
}
}
(split, manifest)
} else {
(
"__wasm_split.______________________.js".to_string(),
"__wasm_split_manifest.json".to_string(),
)
};
let site_dir = &options.site_root;
let pkg_dir = &options.site_pkg_dir;
let path = PathBuf::from(site_dir.to_string());
let path = path.join(pkg_dir.to_string()).join(wasm_split_manifest);
let file = std::fs::read_to_string(path).ok()?;
let manifest = WasmSplitManifest(ArcStoredValue::new((
format!("{root}/{pkg_dir}"),
serde_json::from_str(&file).expect("could not read manifest file"),
wasm_split_js,
)));
Some(manifest)
}) {
provide_context(splits.clone());
}
let mut js_file_name = options.output_name.to_string();
let mut wasm_file_name = options.output_name.to_string();
if options.hash_files {
let hash_path = std::env::current_exe()
.map(|path| {
path.parent().map(|p| p.to_path_buf()).unwrap_or_default()
})
.unwrap_or_default()
.join(options.hash_file.as_ref());
if hash_path.exists() {
let hashes = std::fs::read_to_string(&hash_path)
.expect("failed to read hash file");
for line in hashes.lines() {
let line = line.trim();
if !line.is_empty() {
if let Some((file, hash)) = line.split_once(':') {
if file == "js" {
js_file_name.push_str(&format!(".{}", hash.trim()));
} else if file == "wasm" {
wasm_file_name
.push_str(&format!(".{}", hash.trim()));
}
}
}
}
} else {
leptos::logging::error!(
"File hashing is active but no hash file was found"
);
}
} else if std::option_env!("LEPTOS_OUTPUT_NAME").is_none() {
wasm_file_name.push_str("_bg");
}
let pkg_path = &options.site_pkg_dir;
#[cfg(feature = "nonce")]
let nonce = crate::nonce::use_nonce();
#[cfg(not(feature = "nonce"))]
let nonce = None::<String>;
let script = if islands {
if let Some(sc) = Owner::current_shared_context() {
sc.set_is_hydrating(false);
}
include_str!("./island_script.js")
} else {
include_str!("./hydration_script.js")
};
let islands_router = islands_router
.then_some(include_str!("./islands_routing.js"))
.unwrap_or_default();
let root = root.unwrap_or_default();
view! {
<link rel="modulepreload" href=format!("{root}/{pkg_path}/{js_file_name}.js") crossorigin=nonce.clone()/>
<link
rel="preload"
href=format!("{root}/{pkg_path}/{wasm_file_name}.wasm")
r#as="fetch"
r#type="application/wasm"
crossorigin=nonce.clone().unwrap_or_default()
/>
<script type="module" nonce=nonce>
{format!("{script}({root:?}, {pkg_path:?}, {js_file_name:?}, {wasm_file_name:?});{islands_router}")}
</script>
}
}
/// If this is provided via context, it means that you are using the islands router and
/// this is a subsequent navigation, made from the client.
///
/// This should be provided automatically by a server integration if it detects that the
/// header `Islands-Router` is present in the request.
///
/// This is used to determine how much of the hydration script to include in the page.
/// If it is present, then the contents of the `<HydrationScripts>` component will not be
/// included, as they only need to be sent to the client once.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IslandsRouterNavigation;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/tests/pr_4061.rs | leptos/tests/pr_4061.rs | #[cfg(feature = "ssr")]
mod imports {
pub use any_spawner::Executor;
pub use futures::StreamExt;
pub use leptos::prelude::*;
}
#[cfg(feature = "ssr")]
#[tokio::test]
async fn chain_await_resource() {
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let (rs, ws) = signal(0);
let source = Resource::new(
|| (),
move |_| async move {
#[cfg(feature = "ssr")]
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
1
},
);
let consuming = Resource::new(
|| (),
move |_| async move {
let result = source.await;
ws.update(|s| *s += 1);
result
},
);
let app = view! {
<Suspense>{
move || {
Suspend::new(async move {
consuming.await;
rs.get()
})
}
}</Suspense>
};
assert_eq!(app.to_html_stream_in_order().collect::<String>().await, "1");
}
#[cfg(feature = "ssr")]
#[tokio::test]
async fn chain_no_await_resource() {
use imports::*;
_ = Executor::init_tokio();
let owner = Owner::new();
owner.set();
let (rs, ws) = signal(0);
let source = Resource::new(|| (), move |_| async move { 1 });
let consuming = Resource::new(
|| (),
move |_| async move {
let result = source.await;
ws.update(|s| *s += 1);
result
},
);
let app = view! {
<Suspense>{
move || {
Suspend::new(async move {
consuming.await;
rs.get()
})
}
}</Suspense>
};
assert_eq!(app.to_html_stream_in_order().collect::<String>().await, "1");
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/leptos/tests/ssr.rs | leptos/tests/ssr.rs | #[cfg(feature = "ssr")]
use leptos::html::HtmlElement;
#[cfg(feature = "ssr")]
#[test]
fn simple_ssr_test() {
use leptos::prelude::*;
let (value, set_value) = signal(0);
let rendered: View<HtmlElement<_, _, _>> = view! {
<div>
<button on:click=move |_| set_value.update(|value| *value -= 1)>"-1"</button>
<span>"Value: " {move || value.get().to_string()} "!"</span>
<button on:click=move |_| set_value.update(|value| *value += 1)>"+1"</button>
</div>
};
assert_eq!(
rendered.to_html(),
"<div><button>-1</button><span>Value: \
<!>0<!>!</span><button>+1</button></div>"
);
}
#[cfg(feature = "ssr")]
#[test]
fn ssr_test_with_components() {
use leptos::prelude::*;
#[component]
fn Counter(initial_value: i32) -> impl IntoView {
let (value, set_value) = signal(initial_value);
view! {
<div>
<button on:click=move |_| set_value.update(|value| *value -= 1)>"-1"</button>
<span>"Value: " {move || value.get().to_string()} "!"</span>
<button on:click=move |_| set_value.update(|value| *value += 1)>"+1"</button>
</div>
}
}
let rendered: View<HtmlElement<_, _, _>> = view! {
<div class="counters">
<Counter initial_value=1/>
<Counter initial_value=2/>
</div>
};
assert_eq!(
rendered.to_html(),
"<div class=\"counters\"><div><button>-1</button><span>Value: \
<!>1<!>!</span><button>+1</button></div><div><button>-1</\
button><span>Value: <!>2<!>!</span><button>+1</button></div></div>"
);
}
#[cfg(feature = "ssr")]
#[test]
fn ssr_test_with_snake_case_components() {
use leptos::prelude::*;
#[component]
fn snake_case_counter(initial_value: i32) -> impl IntoView {
let (value, set_value) = signal(initial_value);
view! {
<div>
<button on:click=move |_| set_value.update(|value| *value -= 1)>"-1"</button>
<span>"Value: " {move || value.get().to_string()} "!"</span>
<button on:click=move |_| set_value.update(|value| *value += 1)>"+1"</button>
</div>
}
}
let rendered: View<HtmlElement<_, _, _>> = view! {
<div class="counters">
<SnakeCaseCounter initial_value=1/>
<SnakeCaseCounter initial_value=2/>
</div>
};
assert_eq!(
rendered.to_html(),
"<div class=\"counters\"><div><button>-1</button><span>Value: \
<!>1<!>!</span><button>+1</button></div><div><button>-1</\
button><span>Value: <!>2<!>!</span><button>+1</button></div></div>"
);
}
#[cfg(feature = "ssr")]
#[test]
fn test_classes() {
use leptos::prelude::*;
let (value, _set_value) = signal(5);
let rendered: View<HtmlElement<_, _, _>> = view! {
<div
class="my big"
class:a=move || { value.get() > 10 }
class:red=true
class:car=move || { value.get() > 1 }
></div>
};
assert_eq!(rendered.to_html(), "<div class=\"my big red car\"></div>");
}
#[cfg(feature = "ssr")]
#[test]
fn test_class_with_class_directive_merge() {
use leptos::prelude::*;
// class= followed by class: should merge
let rendered: View<HtmlElement<_, _, _>> = view! {
<div class="foo" class:bar=true></div>
};
assert_eq!(rendered.to_html(), "<div class=\"foo bar\"></div>");
}
#[cfg(feature = "ssr")]
#[test]
fn test_solo_class_directive() {
use leptos::prelude::*;
// Solo class: directive should work without class attribute
let rendered: View<HtmlElement<_, _, _>> = view! {
<div class:foo=true></div>
};
assert_eq!(rendered.to_html(), "<div class=\"foo\"></div>");
}
#[cfg(feature = "ssr")]
#[test]
fn test_class_directive_with_static_class() {
use leptos::prelude::*;
// class:foo comes after class= due to macro sorting
// The class= clears buffer, then class:foo appends
let rendered: View<HtmlElement<_, _, _>> = view! {
<div class:foo=true class="bar"></div>
};
// After macro sorting: class="bar" class:foo=true
// Expected: "bar foo"
assert_eq!(rendered.to_html(), "<div class=\"bar foo\"></div>");
}
#[cfg(feature = "ssr")]
#[test]
fn test_global_class_applied() {
use leptos::prelude::*;
// Test that a global class is properly applied
let rendered: View<HtmlElement<_, _, _>> = view! { class="global",
<div></div>
};
assert_eq!(rendered.to_html(), "<div class=\"global\"></div>");
}
#[cfg(feature = "ssr")]
#[test]
fn test_multiple_class_attributes_overwrite() {
use leptos::prelude::*;
// When multiple class attributes are applied, the last one should win (browser behavior)
// This simulates what happens when attributes are combined programmatically
let el = leptos::html::div().class("first").class("second");
let html = el.to_html();
// The second class attribute should overwrite the first
assert_eq!(html, "<div class=\"second\"></div>");
}
#[cfg(feature = "ssr")]
#[test]
fn ssr_with_styles() {
use leptos::prelude::*;
let (_, set_value) = signal(0);
let styles = "myclass";
let rendered: View<HtmlElement<_, _, _>> = view! { class=styles,
<div>
<button class="btn" on:click=move |_| set_value.update(|value| *value -= 1)>
"-1"
</button>
</div>
};
assert_eq!(
rendered.to_html(),
"<div class=\"myclass\"><button class=\"btn \
myclass\">-1</button></div>"
);
}
#[cfg(feature = "ssr")]
#[test]
fn ssr_option() {
use leptos::prelude::*;
let (_, _) = signal(0);
let rendered: View<HtmlElement<_, _, _>> = view! { <option></option> };
assert_eq!(rendered.to_html(), "<option></option>");
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/build.rs | reactive_graph/build.rs | use rustc_version::{version_meta, Channel};
fn main() {
// Set cfg flags depending on release channel
if matches!(version_meta().unwrap().channel, Channel::Nightly) {
println!("cargo:rustc-cfg=rustc_nightly");
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/effect.rs | reactive_graph/src/effect.rs | //! Side effects that run in response to changes in the reactive values they read from.
#[allow(clippy::module_inception)]
mod effect;
mod effect_function;
mod immediate;
mod inner;
mod render_effect;
pub use effect::*;
pub use effect_function::*;
pub use immediate::*;
pub use render_effect::*;
/// Creates a new render effect, which immediately runs `fun`.
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `RenderEffect::new()` instead."]
pub fn create_render_effect<T>(
fun: impl FnMut(Option<T>) -> T + 'static,
) -> RenderEffect<T>
where
T: 'static,
{
RenderEffect::new(fun)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/serde.rs | reactive_graph/src/serde.rs | #[allow(deprecated)]
use crate::wrappers::read::{MaybeProp, MaybeSignal};
use crate::{
computed::{ArcMemo, Memo},
owner::Storage,
signal::{ArcReadSignal, ArcRwSignal, ReadSignal, RwSignal},
traits::With,
wrappers::read::{Signal, SignalTypes},
};
use serde::{Deserialize, Serialize};
impl<T, St> Serialize for ReadSignal<T, St>
where
T: Serialize + 'static,
St: Storage<ArcReadSignal<T>>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
impl<T, St> Serialize for RwSignal<T, St>
where
T: Serialize + 'static,
St: Storage<ArcRwSignal<T>>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
impl<T, St> Serialize for Memo<T, St>
where
T: Serialize + 'static,
St: Storage<ArcMemo<T, St>> + Storage<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
impl<T: Serialize + 'static> Serialize for ArcReadSignal<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
impl<T: Serialize + 'static> Serialize for ArcRwSignal<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
impl<T: Serialize + 'static, St: Storage<T>> Serialize for ArcMemo<T, St> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
#[allow(deprecated)]
impl<T, St> Serialize for MaybeSignal<T, St>
where
T: Clone + Send + Sync + Serialize,
St: Storage<SignalTypes<T, St>> + Storage<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
impl<T, St> Serialize for MaybeProp<T, St>
where
T: Send + Sync + Serialize,
St: Storage<SignalTypes<Option<T>, St>> + Storage<Option<T>>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match &self.0 {
None => None::<T>.serialize(serializer),
Some(signal) => signal.with(|value| value.serialize(serializer)),
}
}
}
impl<T, St> Serialize for Signal<T, St>
where
T: Send + Sync + Serialize + 'static,
St: Storage<SignalTypes<T, St>> + Storage<T>,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.with(|value| value.serialize(serializer))
}
}
/* Deserialization for signal types */
impl<'de, T, S> Deserialize<'de> for RwSignal<T, S>
where
T: Send + Sync + Deserialize<'de> + 'static,
S: Storage<ArcRwSignal<T>>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(RwSignal::new_with_storage)
}
}
impl<'de, T: Deserialize<'de>> Deserialize<'de> for ArcRwSignal<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(ArcRwSignal::new)
}
}
#[allow(deprecated)]
impl<'de, T: Deserialize<'de>, St> Deserialize<'de> for MaybeSignal<T, St>
where
St: Storage<T>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(MaybeSignal::Static)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/wrappers.rs | reactive_graph/src/wrappers.rs | //! Types to abstract over different kinds of readable or writable reactive values.
/// Types that abstract over signals with values that can be read.
pub mod read {
use crate::{
computed::{ArcMemo, Memo},
graph::untrack,
owner::{
ArcStoredValue, ArenaItem, FromLocal, LocalStorage, Storage,
SyncStorage,
},
signal::{
guards::{Mapped, Plain, ReadGuard},
ArcMappedSignal, ArcReadSignal, ArcRwSignal, MappedSignal,
ReadSignal, RwSignal,
},
traits::{
DefinedAt, Dispose, Get, Read, ReadUntracked, ReadValue, Track,
},
unwrap_signal,
};
use send_wrapper::SendWrapper;
use std::{
borrow::Borrow,
fmt::Display,
ops::Deref,
panic::Location,
sync::{Arc, RwLock},
};
/// Possibilities for the inner type of a [`Signal`].
pub enum SignalTypes<T, S = SyncStorage>
where
S: Storage<T>,
{
/// A readable signal.
ReadSignal(ArcReadSignal<T>),
/// A memo.
Memo(ArcMemo<T, S>),
/// A derived signal.
DerivedSignal(Arc<dyn Fn() -> T + Send + Sync>),
/// A static, stored value.
Stored(ArcStoredValue<T>),
}
impl<T, S> Clone for SignalTypes<T, S>
where
S: Storage<T>,
{
fn clone(&self) -> Self {
match self {
Self::ReadSignal(arg0) => Self::ReadSignal(arg0.clone()),
Self::Memo(arg0) => Self::Memo(arg0.clone()),
Self::DerivedSignal(arg0) => Self::DerivedSignal(arg0.clone()),
Self::Stored(arg0) => Self::Stored(arg0.clone()),
}
}
}
impl<T, S> core::fmt::Debug for SignalTypes<T, S>
where
S: Storage<T>,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::ReadSignal(arg0) => {
f.debug_tuple("ReadSignal").field(arg0).finish()
}
Self::Memo(arg0) => f.debug_tuple("Memo").field(arg0).finish(),
Self::DerivedSignal(_) => {
f.debug_tuple("DerivedSignal").finish()
}
Self::Stored(arg0) => {
f.debug_tuple("Static").field(arg0).finish()
}
}
}
}
impl<T, S> PartialEq for SignalTypes<T, S>
where
S: Storage<T>,
{
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::ReadSignal(l0), Self::ReadSignal(r0)) => l0 == r0,
(Self::Memo(l0), Self::Memo(r0)) => l0 == r0,
(Self::DerivedSignal(l0), Self::DerivedSignal(r0)) => {
std::ptr::eq(l0, r0)
}
_ => false,
}
}
}
/// A wrapper for any kind of reference-counted reactive signal:
/// an [`ArcReadSignal`], [`ArcMemo`], [`ArcRwSignal`], or derived signal closure,
/// or a plain value of the same type
///
/// This allows you to create APIs that take `T` or any reactive value that returns `T`
/// as an argument, rather than adding a generic `F: Fn() -> T`.
///
/// Values can be accessed with the same function call, `read()`, `with()`, and `get()`
/// APIs as other signals.
///
/// ## Important Notes about Derived Signals
///
/// `Signal::derive()` is simply a way to box and type-erase a “derived signal,” which
/// is a plain closure that accesses one or more signals. It does *not* cache the value
/// of that computation. Accessing the value of a `Signal<_>` that is created using `Signal::derive()`
/// will run the closure again every time you call `.read()`, `.with()`, or `.get()`.
///
/// If you want the closure to run the minimal number of times necessary to update its state,
/// and then to cache its value, you should use a [`Memo`] (and convert it into a `Signal<_>`)
/// rather than using `Signal::derive()`.
///
/// Note that for many computations, it is nevertheless less expensive to use a derived signal
/// than to create a separate memo and to cache the value: creating a new reactive node and
/// taking the lock on that cached value whenever you access the signal is *more* expensive than
/// simply re-running the calculation in many cases.
pub struct ArcSignal<T: 'static, S = SyncStorage>
where
S: Storage<T>,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: SignalTypes<T, S>,
}
impl<T, S> Clone for ArcSignal<T, S>
where
S: Storage<T>,
{
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
inner: self.inner.clone(),
}
}
}
impl<T, S> core::fmt::Debug for ArcSignal<T, S>
where
S: Storage<T>,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut s = f.debug_struct("ArcSignal");
s.field("inner", &self.inner);
#[cfg(any(debug_assertions, leptos_debuginfo))]
s.field("defined_at", &self.defined_at);
s.finish()
}
}
impl<T, S> Eq for ArcSignal<T, S> where S: Storage<T> {}
impl<T, S> PartialEq for ArcSignal<T, S>
where
S: Storage<T>,
{
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T> ArcSignal<T, SyncStorage>
where
SyncStorage: Storage<T>,
{
/// Wraps a derived signal, i.e., any computation that accesses one or more
/// reactive signals.
/// ```rust
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::wrappers::read::ArcSignal;
/// # use reactive_graph::prelude::*;
/// let (count, set_count) = arc_signal(2);
/// let double_count = ArcSignal::derive({
/// let count = count.clone();
/// move || count.get() * 2
/// });
///
/// // this function takes any kind of wrapped signal
/// fn above_3(arg: &ArcSignal<i32>) -> bool {
/// arg.get() > 3
/// }
///
/// assert_eq!(above_3(&count.into()), false);
/// assert_eq!(above_3(&double_count), true);
/// ```
#[track_caller]
pub fn derive(
derived_signal: impl Fn() -> T + Send + Sync + 'static,
) -> Self {
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
let derived_signal = move || {
#[cfg(feature = "tracing")]
let _guard = span.enter();
derived_signal()
};
Self {
inner: SignalTypes::DerivedSignal(Arc::new(derived_signal)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
/// Moves a static, nonreactive value into a signal, backed by [`ArcStoredValue`].
#[track_caller]
pub fn stored(value: T) -> Self {
Self {
inner: SignalTypes::Stored(ArcStoredValue::new(value)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> ArcSignal<T, LocalStorage>
where
T: 'static,
{
/// Wraps a derived signal. Works like [`Signal::derive`] but uses [`LocalStorage`].
#[track_caller]
pub fn derive_local(derived_signal: impl Fn() -> T + 'static) -> Self {
Signal::derive_local(derived_signal).into()
}
/// Moves a static, nonreactive value into a signal, backed by [`ArcStoredValue`].
/// Works like [`Signal::stored`] but uses [`LocalStorage`].
#[track_caller]
pub fn stored_local(value: T) -> Self {
Signal::stored_local(value).into()
}
}
impl<T> Default for ArcSignal<T, SyncStorage>
where
T: Default + Send + Sync + 'static,
{
fn default() -> Self {
Self::stored(Default::default())
}
}
impl<T: Send + Sync> From<ArcReadSignal<T>> for ArcSignal<T, SyncStorage> {
#[track_caller]
fn from(value: ArcReadSignal<T>) -> Self {
Self {
inner: SignalTypes::ReadSignal(value),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T, S> From<ReadSignal<T, S>> for ArcSignal<T, S>
where
S: Storage<ArcReadSignal<T>> + Storage<T>,
{
#[track_caller]
fn from(value: ReadSignal<T, S>) -> Self {
Self {
inner: SignalTypes::ReadSignal(value.into()),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T: Send + Sync> From<ArcRwSignal<T>> for ArcSignal<T, SyncStorage> {
#[track_caller]
fn from(value: ArcRwSignal<T>) -> Self {
Self {
inner: SignalTypes::ReadSignal(value.read_only()),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T, S> From<RwSignal<T, S>> for ArcSignal<T, S>
where
S: Storage<ArcRwSignal<T>> + Storage<ArcReadSignal<T>> + Storage<T>,
{
#[track_caller]
fn from(value: RwSignal<T, S>) -> Self {
Self {
inner: SignalTypes::ReadSignal(value.read_only().into()),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T, S> From<ArcMemo<T, S>> for ArcSignal<T, S>
where
S: Storage<T>,
{
#[track_caller]
fn from(value: ArcMemo<T, S>) -> Self {
Self {
inner: SignalTypes::Memo(value),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T, S> From<Memo<T, S>> for ArcSignal<T, S>
where
S: Storage<ArcMemo<T, S>> + Storage<T>,
{
#[track_caller]
fn from(value: Memo<T, S>) -> Self {
Self {
inner: SignalTypes::Memo(value.into()),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<S> From<&'static str> for ArcSignal<String, S>
where
S: Storage<&'static str> + Storage<String>,
{
#[track_caller]
fn from(value: &'static str) -> Self {
Self {
inner: SignalTypes::Stored(ArcStoredValue::new(
value.to_string(),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T, S> DefinedAt for ArcSignal<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 ArcSignal<T, S>
where
S: Storage<T>,
{
fn track(&self) {
match &self.inner {
SignalTypes::ReadSignal(i) => {
i.track();
}
SignalTypes::Memo(i) => {
i.track();
}
SignalTypes::DerivedSignal(i) => {
i();
}
// Doesn't change.
SignalTypes::Stored(_) => {}
}
}
}
impl<T, S> ReadUntracked for ArcSignal<T, S>
where
S: Storage<T>,
{
type Value = ReadGuard<T, SignalReadGuard<T, S>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
match &self.inner {
SignalTypes::ReadSignal(i) => {
i.try_read_untracked().map(SignalReadGuard::Read)
}
SignalTypes::Memo(i) => {
i.try_read_untracked().map(SignalReadGuard::Memo)
}
SignalTypes::DerivedSignal(i) => {
Some(SignalReadGuard::Owned(untrack(|| i())))
}
SignalTypes::Stored(i) => {
i.try_read_value().map(SignalReadGuard::Read)
}
}
.map(ReadGuard::new)
}
/// Overriding the default auto implemented [`Read::try_read`] to combine read and track,
/// to avoid 2 clones and just have 1 in the [`SignalTypes::DerivedSignal`].
fn custom_try_read(&self) -> Option<Option<Self::Value>> {
Some(
match &self.inner {
SignalTypes::ReadSignal(i) => {
i.try_read().map(SignalReadGuard::Read)
}
SignalTypes::Memo(i) => {
i.try_read().map(SignalReadGuard::Memo)
}
SignalTypes::DerivedSignal(i) => {
Some(SignalReadGuard::Owned(i()))
}
SignalTypes::Stored(i) => {
i.try_read_value().map(SignalReadGuard::Read)
}
}
.map(ReadGuard::new),
)
}
}
/// A wrapper for any kind of arena-allocated reactive signal:
/// a [`ReadSignal`], [`Memo`], [`RwSignal`], or derived signal closure,
/// or a plain value of the same type
///
/// This allows you to create APIs that take `T` or any reactive value that returns `T`
/// as an argument, rather than adding a generic `F: Fn() -> T`.
///
/// Values can be accessed with the same function call, `read()`, `with()`, and `get()`
/// APIs as other signals.
///
/// ## Important Notes about Derived Signals
///
/// `Signal::derive()` is simply a way to box and type-erase a “derived signal,” which
/// is a plain closure that accesses one or more signals. It does *not* cache the value
/// of that computation. Accessing the value of a `Signal<_>` that is created using `Signal::derive()`
/// will run the closure again every time you call `.read()`, `.with()`, or `.get()`.
///
/// If you want the closure to run the minimal number of times necessary to update its state,
/// and then to cache its value, you should use a [`Memo`] (and convert it into a `Signal<_>`)
/// rather than using `Signal::derive()`.
///
/// Note that for many computations, it is nevertheless less expensive to use a derived signal
/// than to create a separate memo and to cache the value: creating a new reactive node and
/// taking the lock on that cached value whenever you access the signal is *more* expensive than
/// simply re-running the calculation in many cases.
pub struct Signal<T, S = SyncStorage>
where
S: Storage<T>,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: ArenaItem<SignalTypes<T, S>, S>,
}
impl<T, S> Dispose for Signal<T, S>
where
S: Storage<T>,
{
fn dispose(self) {
self.inner.dispose()
}
}
impl<T, S> Clone for Signal<T, S>
where
S: Storage<T>,
{
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Copy for Signal<T, S> where S: Storage<T> {}
impl<T, S> core::fmt::Debug for Signal<T, S>
where
S: std::fmt::Debug + Storage<T>,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut s = f.debug_struct("Signal");
s.field("inner", &self.inner);
#[cfg(any(debug_assertions, leptos_debuginfo))]
s.field("defined_at", &self.defined_at);
s.finish()
}
}
impl<T, S> Eq for Signal<T, S> where S: Storage<T> {}
impl<T, S> PartialEq for Signal<T, S>
where
S: Storage<T>,
{
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, S> DefinedAt for Signal<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 Signal<T, S>
where
T: 'static,
S: Storage<T> + Storage<SignalTypes<T, S>>,
{
fn track(&self) {
let inner = self
.inner
// clone the inner Arc type and release the lock
// prevents deadlocking if the derived value includes taking a lock on the arena
.try_with_value(Clone::clone)
.unwrap_or_else(unwrap_signal!(self));
match inner {
SignalTypes::ReadSignal(i) => {
i.track();
}
SignalTypes::Memo(i) => {
i.track();
}
SignalTypes::DerivedSignal(i) => {
i();
}
// Doesn't change.
SignalTypes::Stored(_) => {}
}
}
}
impl<T, S> ReadUntracked for Signal<T, S>
where
T: 'static,
S: Storage<SignalTypes<T, S>> + Storage<T>,
{
type Value = ReadGuard<T, SignalReadGuard<T, S>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.inner
// clone the inner Arc type and release the lock
// prevents deadlocking if the derived value includes taking a lock on the arena
.try_with_value(Clone::clone)
.and_then(|inner| {
match &inner {
SignalTypes::ReadSignal(i) => {
i.try_read_untracked().map(SignalReadGuard::Read)
}
SignalTypes::Memo(i) => {
i.try_read_untracked().map(SignalReadGuard::Memo)
}
SignalTypes::DerivedSignal(i) => {
Some(SignalReadGuard::Owned(untrack(|| i())))
}
SignalTypes::Stored(i) => {
i.try_read_value().map(SignalReadGuard::Read)
}
}
.map(ReadGuard::new)
})
}
/// Overriding the default auto implemented [`Read::try_read`] to combine read and track,
/// to avoid 2 clones and just have 1 in the [`SignalTypes::DerivedSignal`].
fn custom_try_read(&self) -> Option<Option<Self::Value>> {
Some(
self.inner
// clone the inner Arc type and release the lock
// prevents deadlocking if the derived value includes taking a lock on the arena
.try_with_value(Clone::clone)
.and_then(|inner| {
match &inner {
SignalTypes::ReadSignal(i) => {
i.try_read().map(SignalReadGuard::Read)
}
SignalTypes::Memo(i) => {
i.try_read().map(SignalReadGuard::Memo)
}
SignalTypes::DerivedSignal(i) => {
Some(SignalReadGuard::Owned(i()))
}
SignalTypes::Stored(i) => {
i.try_read_value().map(SignalReadGuard::Read)
}
}
.map(ReadGuard::new)
}),
)
}
}
impl<T> Signal<T>
where
T: Send + Sync + 'static,
{
/// Wraps a derived signal, i.e., any computation that accesses one or more
/// reactive signals.
/// ```rust
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::wrappers::read::Signal;
/// # use reactive_graph::prelude::*;
/// let (count, set_count) = signal(2);
/// let double_count = Signal::derive(move || count.get() * 2);
///
/// // this function takes any kind of wrapped signal
/// fn above_3(arg: &Signal<i32>) -> bool {
/// arg.get() > 3
/// }
///
/// assert_eq!(above_3(&count.into()), false);
/// assert_eq!(above_3(&double_count), true);
/// ```
#[track_caller]
pub fn derive(
derived_signal: impl Fn() -> T + Send + Sync + 'static,
) -> Self {
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
let derived_signal = move || {
#[cfg(feature = "tracing")]
let _guard = span.enter();
derived_signal()
};
Self {
inner: ArenaItem::new_with_storage(SignalTypes::DerivedSignal(
Arc::new(derived_signal),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
/// Moves a static, nonreactive value into a signal, backed by [`ArcStoredValue`].
#[track_caller]
pub fn stored(value: T) -> Self {
Self {
inner: ArenaItem::new_with_storage(SignalTypes::Stored(
ArcStoredValue::new(value),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> Signal<T, LocalStorage>
where
T: 'static,
{
/// Wraps a derived signal. Works like [`Signal::derive`] but uses [`LocalStorage`].
#[track_caller]
pub fn derive_local(derived_signal: impl Fn() -> T + 'static) -> Self {
let derived_signal = SendWrapper::new(derived_signal);
#[cfg(feature = "tracing")]
let span = ::tracing::Span::current();
let derived_signal = move || {
#[cfg(feature = "tracing")]
let _guard = span.enter();
derived_signal()
};
Self {
inner: ArenaItem::new_local(SignalTypes::DerivedSignal(
Arc::new(derived_signal),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
/// Moves a static, nonreactive value into a signal, backed by [`ArcStoredValue`].
/// Works like [`Signal::stored`] but uses [`LocalStorage`].
#[track_caller]
pub fn stored_local(value: T) -> Self {
Self {
inner: ArenaItem::new_local(SignalTypes::Stored(
ArcStoredValue::new(value),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> Default for Signal<T>
where
T: Send + Sync + Default + 'static,
{
fn default() -> Self {
Self::stored(Default::default())
}
}
impl<T> Default for Signal<T, LocalStorage>
where
T: Default + 'static,
{
fn default() -> Self {
Self::stored_local(Default::default())
}
}
impl<T: Send + Sync + 'static> From<T> for ArcSignal<T, SyncStorage> {
#[track_caller]
fn from(value: T) -> Self {
ArcSignal::stored(value)
}
}
impl<T> From<T> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: T) -> Self {
Self::stored(value)
}
}
impl<T> From<T> for Signal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from(value: T) -> Self {
Self::stored_local(value)
}
}
impl<T> From<ArcSignal<T, SyncStorage>> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcSignal<T, SyncStorage>) -> Self {
Signal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new(value.inner),
}
}
}
impl<T> FromLocal<ArcSignal<T, LocalStorage>> for Signal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from_local(value: ArcSignal<T, LocalStorage>) -> Self {
Signal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_local(value.inner),
}
}
}
impl<T, S> From<Signal<T, S>> for ArcSignal<T, S>
where
S: Storage<SignalTypes<T, S>> + Storage<T>,
{
#[track_caller]
fn from(value: Signal<T, S>) -> Self {
ArcSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: value
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(value)),
}
}
}
impl<T> From<ReadSignal<T>> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ReadSignal<T>) -> Self {
Self {
inner: ArenaItem::new(SignalTypes::ReadSignal(value.into())),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<ReadSignal<T, LocalStorage>> for Signal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from(value: ReadSignal<T, LocalStorage>) -> Self {
Self {
inner: ArenaItem::new_local(SignalTypes::ReadSignal(
value.into(),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<ArcReadSignal<T>> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcReadSignal<T>) -> Self {
Self {
inner: ArenaItem::new(SignalTypes::ReadSignal(value)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<ArcReadSignal<T>> for Signal<T, LocalStorage>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcReadSignal<T>) -> Self {
Self {
inner: ArenaItem::new_local(SignalTypes::ReadSignal(value)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<RwSignal<T>> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: RwSignal<T>) -> Self {
Self {
inner: ArenaItem::new(SignalTypes::ReadSignal(
value.read_only().into(),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<MappedSignal<T>> for Signal<T>
where
T: Clone + Send + Sync + 'static,
{
#[track_caller]
fn from(value: MappedSignal<T>) -> Self {
Self::derive(move || value.get())
}
}
impl<T> From<RwSignal<T, LocalStorage>> for Signal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from(value: RwSignal<T, LocalStorage>) -> Self {
Self {
inner: ArenaItem::new_local(SignalTypes::ReadSignal(
value.read_only().into(),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<ArcRwSignal<T>> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcRwSignal<T>) -> Self {
Self {
inner: ArenaItem::new(SignalTypes::ReadSignal(
value.read_only(),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<ArcMappedSignal<T>> for Signal<T>
where
T: Clone + Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcMappedSignal<T>) -> Self {
MappedSignal::from(value).into()
}
}
impl<T> From<ArcRwSignal<T>> for Signal<T, LocalStorage>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcRwSignal<T>) -> Self {
Self {
inner: ArenaItem::new_local(SignalTypes::ReadSignal(
value.read_only(),
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<Memo<T>> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: Memo<T>) -> Self {
Self {
inner: ArenaItem::new(SignalTypes::Memo(value.into())),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<Memo<T, LocalStorage>> for Signal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from(value: Memo<T, LocalStorage>) -> Self {
Self {
inner: ArenaItem::new_local(SignalTypes::Memo(value.into())),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<ArcMemo<T>> for Signal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcMemo<T>) -> Self {
Self {
inner: ArenaItem::new(SignalTypes::Memo(value)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<ArcMemo<T, LocalStorage>> for Signal<T, LocalStorage>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcMemo<T, LocalStorage>) -> Self {
Self {
inner: ArenaItem::new_local(SignalTypes::Memo(value)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
}
}
}
impl<T> From<T> for Signal<Option<T>>
where
T: Send + Sync + 'static,
{
#[track_caller]
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/diagnostics.rs | reactive_graph/src/diagnostics.rs | //! By default, attempting to [`Track`](crate::traits::Track) a signal when you are not in a
//! reactive tracking context will cause a warning when you are in debug mode.
//!
//! In some cases, this warning is a false positive. For example, inside an event listener in a
//! user interface, you never want to read from a signal reactively; the event listener should run
//! when the event fires, not when a signal read in the event listener changes.
//!
//! This module provides utilities to suppress those warnings by entering a
//! [`SpecialNonReactiveZone`].
/// Marks an execution block that is known not to be reactive, and suppresses warnings.
#[derive(Debug)]
pub struct SpecialNonReactiveZone;
/// Exits the "special non-reactive zone" when dropped.
#[derive(Debug)]
pub struct SpecialNonReactiveZoneGuard(bool);
use pin_project_lite::pin_project;
use std::{
cell::Cell,
future::Future,
pin::Pin,
task::{Context, Poll},
};
thread_local! {
static IS_SPECIAL_ZONE: Cell<bool> = const { Cell::new(false) };
}
impl SpecialNonReactiveZone {
/// Suppresses warnings about non-reactive accesses until the guard is dropped.
pub fn enter() -> SpecialNonReactiveZoneGuard {
let prev = IS_SPECIAL_ZONE.replace(true);
SpecialNonReactiveZoneGuard(prev)
}
#[cfg(all(debug_assertions, feature = "effects"))]
#[inline(always)]
pub(crate) fn is_inside() -> bool {
if cfg!(debug_assertions) {
IS_SPECIAL_ZONE.get()
} else {
false
}
}
}
impl Drop for SpecialNonReactiveZoneGuard {
fn drop(&mut self) {
IS_SPECIAL_ZONE.set(self.0);
}
}
pin_project! {
#[doc(hidden)]
pub struct SpecialNonReactiveFuture<Fut> {
#[pin]
inner: Fut
}
}
impl<Fut> SpecialNonReactiveFuture<Fut> {
pub fn new(inner: Fut) -> Self {
Self { inner }
}
}
impl<Fut> Future for SpecialNonReactiveFuture<Fut>
where
Fut: Future,
{
type Output = Fut::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
#[cfg(debug_assertions)]
let _rw = SpecialNonReactiveZone::enter();
let this = self.project();
this.inner.poll(cx)
}
}
thread_local! {
static SUPPRESS_RESOURCE_LOAD: Cell<bool> = const { Cell::new(false) };
}
#[doc(hidden)]
pub fn suppress_resource_load(suppress: bool) {
SUPPRESS_RESOURCE_LOAD.with(|w| w.set(suppress));
}
#[doc(hidden)]
pub fn is_suppressing_resource_load() -> bool {
SUPPRESS_RESOURCE_LOAD.with(|w| w.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/lib.rs | reactive_graph/src/lib.rs | //! An implementation of a fine-grained reactive system.
//!
//! Fine-grained reactivity is an approach to modeling the flow of data through an interactive
//! application by composing together three categories of reactive primitives:
//! 1. **Signals**: atomic units of state, which can be directly mutated.
//! 2. **Computations**: derived values, which cannot be mutated directly but update whenever the signals
//! they depend on change. These include both synchronous and asynchronous derived values.
//! 3. **Effects**: side effects that synchronize the reactive system with the non-reactive world
//! outside it.
//!
//! Signals and computations are "source" nodes in the reactive graph, because an observer can
//! subscribe to them to respond to changes in their values. Effects and computations are "subscriber"
//! nodes, because they can listen to changes in other values.
//!
//! ```rust
//! # any_spawner::Executor::init_futures_executor();
//! # let owner = reactive_graph::owner::Owner::new(); owner.set();
//! use reactive_graph::{
//! computed::ArcMemo,
//! effect::Effect,
//! prelude::{Read, Set},
//! signal::ArcRwSignal,
//! };
//!
//! let count = ArcRwSignal::new(1);
//! let double_count = ArcMemo::new({
//! let count = count.clone();
//! move |_| *count.read() * 2
//! });
//!
//! // the effect will run once initially
//! Effect::new(move |_| {
//! println!("double_count = {}", *double_count.read());
//! });
//!
//! // updating `count` will propagate changes to the dependencies,
//! // causing the effect to run again
//! count.set(2);
//! ```
//!
//! This reactivity is called "fine grained" because updating the value of a signal only affects
//! the effects and computations that depend on its value, without requiring any diffing or update
//! calculations for other values.
//!
//! This model is especially suitable for building user interfaces, i.e., long-lived systems in
//! which changes can begin from many different entry points. It is not particularly useful in
//! "run-once" programs like a CLI.
//!
//! ## Design Principles and Assumptions
//! - **Effects are expensive.** The library is built on the assumption that the side effects
//! (making a network request, rendering something to the DOM, writing to disk) are orders of
//! magnitude more expensive than propagating signal updates. As a result, the algorithm is
//! designed to avoid re-running side effects unnecessarily, and is willing to sacrifice a small
//! amount of raw update speed to that goal.
//! - **Automatic dependency tracking.** Dependencies are not specified as a compile-time list, but
//! tracked at runtime. This in turn enables **dynamic dependency tracking**: subscribers
//! unsubscribe from their sources between runs, which means that a subscriber that contains a
//! condition branch will not re-run when dependencies update that are only used in the inactive
//! branch.
//! - **Asynchronous effect scheduling.** Effects are spawned as asynchronous tasks. This means
//! that while updating a signal will immediately update its value, effects that depend on it
//! will not run until the next "tick" of the async runtime. (This in turn means that the
//! reactive system is *async runtime agnostic*: it can be used in the browser with
//! `wasm-bindgen-futures`, in a native binary with `tokio`, in a GTK application with `glib`,
//! etc.)
//!
//! The reactive-graph algorithm used in this crate is based on that of
//! [Reactively](https://github.com/modderme123/reactively), as described
//! [in this article](https://dev.to/modderme123/super-charging-fine-grained-reactive-performance-47ph).
#![cfg_attr(all(feature = "nightly", rustc_nightly), feature(unboxed_closures))]
#![cfg_attr(all(feature = "nightly", rustc_nightly), feature(fn_traits))]
#![deny(missing_docs)]
use std::{fmt::Arguments, future::Future};
pub mod actions;
pub(crate) mod channel;
pub mod computed;
pub mod diagnostics;
pub mod effect;
pub mod graph;
pub mod owner;
pub mod send_wrapper_ext;
#[cfg(feature = "serde")]
mod serde;
pub mod signal;
mod trait_options;
pub mod traits;
pub mod transition;
pub mod wrappers;
mod into_reactive_value;
pub use into_reactive_value::*;
/// A standard way to wrap functions and closures to pass them to components.
pub mod callback;
use computed::ScopedFuture;
#[cfg(all(feature = "nightly", rustc_nightly))]
mod nightly;
/// Reexports frequently-used traits.
pub mod prelude {
pub use crate::{
into_reactive_value::IntoReactiveValue, owner::FromLocal, traits::*,
};
}
// TODO remove this, it's just useful while developing
#[allow(unused)]
#[doc(hidden)]
pub fn log_warning(text: Arguments) {
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
{
web_sys::console::warn_1(&text.to_string().into());
}
#[cfg(all(
not(feature = "tracing"),
not(all(target_arch = "wasm32", target_os = "unknown"))
))]
{
eprintln!("{text}");
}
}
/// Calls [`Executor::spawn`](any_spawner::Executor::spawn) on non-wasm targets and [`Executor::spawn_local`](any_spawner::Executor::spawn_local) on wasm targets, but ensures that the task also runs in the current arena, if
/// multithreaded arena sandboxing is enabled.
pub fn spawn(task: impl Future<Output = ()> + Send + 'static) {
#[cfg(feature = "sandboxed-arenas")]
let task = owner::Sandboxed::new(task);
#[cfg(not(target_family = "wasm"))]
any_spawner::Executor::spawn(task);
#[cfg(target_family = "wasm")]
any_spawner::Executor::spawn_local(task);
}
/// Calls [`Executor::spawn_local`](any_spawner::Executor::spawn_local), but ensures that the task also runs in the current arena, if
/// multithreaded arena sandboxing is enabled.
pub fn spawn_local(task: impl Future<Output = ()> + 'static) {
#[cfg(feature = "sandboxed-arenas")]
let task = owner::Sandboxed::new(task);
any_spawner::Executor::spawn_local(task);
}
/// Calls [`Executor::spawn_local`](any_spawner::Executor), but ensures that the task runs under the current reactive [`Owner`](crate::owner::Owner) and observer.
///
/// Does not cancel the task if the owner is cleaned up.
pub fn spawn_local_scoped(task: impl Future<Output = ()> + 'static) {
let task = ScopedFuture::new(task);
#[cfg(feature = "sandboxed-arenas")]
let task = owner::Sandboxed::new(task);
any_spawner::Executor::spawn_local(task);
}
/// Calls [`Executor::spawn_local`](any_spawner::Executor), but ensures that the task runs under the current reactive [`Owner`](crate::owner::Owner) and observer.
///
/// Cancels the task if the owner is cleaned up.
pub fn spawn_local_scoped_with_cancellation(
task: impl Future<Output = ()> + 'static,
) {
use crate::owner::on_cleanup;
use futures::future::{AbortHandle, Abortable};
let (abort_handle, abort_registration) = AbortHandle::new_pair();
on_cleanup(move || abort_handle.abort());
let task = Abortable::new(task, abort_registration);
let task = ScopedFuture::new(task);
#[cfg(feature = "sandboxed-arenas")]
let task = owner::Sandboxed::new(task);
any_spawner::Executor::spawn_local(async move {
_ = task.await;
});
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/trait_options.rs | reactive_graph/src/trait_options.rs | use crate::{
traits::{
DefinedAt, Get, GetUntracked, Read, ReadUntracked, Track, With,
WithUntracked,
},
unwrap_signal,
};
use std::panic::Location;
impl<T> DefinedAt for Option<T>
where
T: DefinedAt,
{
fn defined_at(&self) -> Option<&'static Location<'static>> {
self.as_ref().map(DefinedAt::defined_at).unwrap_or(None)
}
}
impl<T> Track for Option<T>
where
T: Track,
{
fn track(&self) {
if let Some(signal) = self {
signal.track();
}
}
}
/// An alternative [`ReadUntracked`](crate) trait that works with `Option<Readable>` types.
pub trait ReadUntrackedOptional: Sized + DefinedAt {
/// The guard type that will be returned, which can be dereferenced to the value.
type Value;
/// Returns the guard, or `None` if the signal has already been disposed.
#[track_caller]
fn try_read_untracked(&self) -> Option<Self::Value>;
/// Returns the guard.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn read_untracked(&self) -> Self::Value {
self.try_read_untracked()
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> ReadUntrackedOptional for Option<T>
where
Self: DefinedAt,
T: ReadUntracked,
{
type Value = Option<<T as ReadUntracked>::Value>;
fn try_read_untracked(&self) -> Option<Self::Value> {
Some(if let Some(signal) = self {
Some(signal.try_read_untracked()?)
} else {
None
})
}
}
/// An alternative [`Read`](crate) trait that works with `Option<Readable>` types.
pub trait ReadOptional: DefinedAt {
/// The guard type that will be returned, which can be dereferenced to the value.
type Value;
/// Subscribes to the signal, and returns the guard, or `None` if the signal has already been disposed.
#[track_caller]
fn try_read(&self) -> Option<Self::Value>;
/// Subscribes to the signal, and returns the guard.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn read(&self) -> Self::Value {
self.try_read().unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> ReadOptional for Option<T>
where
Self: DefinedAt,
T: Read,
{
type Value = Option<<T as Read>::Value>;
fn try_read(&self) -> Option<Self::Value> {
Some(if let Some(readable) = self {
Some(readable.try_read()?)
} else {
None
})
}
}
/// An alternative [`WithUntracked`](crate) trait that works with `Option<Withable>` types.
pub trait WithUntrackedOptional: DefinedAt {
/// The type of the value contained in the signal.
type Value: ?Sized;
/// Applies the closure to the value, and returns the result,
/// or `None` if the signal has already been disposed.
#[track_caller]
fn try_with_untracked<U>(
&self,
fun: impl FnOnce(Option<&Self::Value>) -> U,
) -> Option<U>;
/// Applies the closure to the value, and returns the result.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn with_untracked<U>(
&self,
fun: impl FnOnce(Option<&Self::Value>) -> U,
) -> U {
self.try_with_untracked(fun)
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> WithUntrackedOptional for Option<T>
where
Self: DefinedAt,
T: WithUntracked,
<T as WithUntracked>::Value: Sized,
{
type Value = <T as WithUntracked>::Value;
fn try_with_untracked<U>(
&self,
fun: impl FnOnce(Option<&Self::Value>) -> U,
) -> Option<U> {
if let Some(signal) = self {
Some(signal.try_with_untracked(|val| fun(Some(val)))?)
} else {
Some(fun(None))
}
}
}
/// An alternative [`With`](crate) trait that works with `Option<Withable>` types.
pub trait WithOptional: DefinedAt {
/// The type of the value contained in the signal.
type Value: ?Sized;
/// Subscribes to the signal, applies the closure to the value, and returns the result,
/// or `None` if the signal has already been disposed.
#[track_caller]
fn try_with<U>(
&self,
fun: impl FnOnce(Option<&Self::Value>) -> U,
) -> Option<U>;
/// Subscribes to the signal, applies the closure to the value, and returns the result.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn with<U>(&self, fun: impl FnOnce(Option<&Self::Value>) -> U) -> U {
self.try_with(fun).unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> WithOptional for Option<T>
where
Self: DefinedAt,
T: With,
<T as With>::Value: Sized,
{
type Value = <T as With>::Value;
fn try_with<U>(
&self,
fun: impl FnOnce(Option<&Self::Value>) -> U,
) -> Option<U> {
if let Some(signal) = self {
Some(signal.try_with(|val| fun(Some(val)))?)
} else {
Some(fun(None))
}
}
}
impl<T> GetUntracked for Option<T>
where
Self: DefinedAt,
T: GetUntracked,
{
type Value = Option<<T as GetUntracked>::Value>;
fn try_get_untracked(&self) -> Option<Self::Value> {
Some(if let Some(signal) = self {
Some(signal.try_get_untracked()?)
} else {
None
})
}
}
impl<T> Get for Option<T>
where
Self: DefinedAt,
T: Get,
{
type Value = Option<<T as Get>::Value>;
fn try_get(&self) -> Option<Self::Value> {
Some(if let Some(signal) = self {
Some(signal.try_get()?)
} else {
None
})
}
}
/// Helper trait to implement flatten() on `Option<&Option<T>>`.
pub trait FlattenOptionRefOption {
/// The type of the value contained in the double option.
type Value;
/// Converts from `Option<&Option<T>>` to `Option<&T>`.
fn flatten(&self) -> Option<&Self::Value>;
}
impl<'a, T> FlattenOptionRefOption for Option<&'a Option<T>> {
type Value = T;
fn flatten(&self) -> Option<&'a T> {
self.map(Option::as_ref).flatten()
}
}
| 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.rs | reactive_graph/src/signal.rs | //! Reactive primitives for root values that can be changed, notifying other nodes in the reactive
//! graph.
mod arc_read;
mod arc_rw;
mod arc_trigger;
mod arc_write;
pub mod guards;
mod mapped;
mod read;
mod rw;
mod subscriber_traits;
mod trigger;
mod write;
use crate::owner::LocalStorage;
pub use arc_read::*;
pub use arc_rw::*;
pub use arc_trigger::*;
pub use arc_write::*;
pub use mapped::*;
pub use read::*;
pub use rw::*;
pub use trigger::*;
pub use write::*;
/// Creates a reference-counted signal.
///
/// 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 updating.
///
/// Takes the initial value as an argument, and returns a tuple containing an
/// [`ArcReadSignal`] and an [`ArcWriteSignal`].
///
/// This returns reference-counted signals, which are `Clone` but not `Copy`. For arena-allocated
/// `Copy` signals, use [`signal`].
///
/// ```
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let (count, set_count) = arc_signal(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
/// set_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
/// set_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 = move || count.get() * 2;
/// set_count.set(0);
/// assert_eq!(double_count(), 0);
/// set_count.set(1);
/// assert_eq!(double_count(), 2);
/// ```
#[inline(always)]
#[track_caller]
pub fn arc_signal<T>(value: T) -> (ArcReadSignal<T>, ArcWriteSignal<T>) {
ArcRwSignal::new(value).split()
}
/// Creates an arena-allocated signal, the basic reactive primitive.
///
/// 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 updating.
///
/// Takes the initial value as an argument, and returns a tuple containing a
/// [`ReadSignal`] and a [`WriteSignal`].
///
/// This returns 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 [`arc_signal`].
/// ```
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let (count, set_count) = signal(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
/// set_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
/// set_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 = move || count.get() * 2; // signals are `Copy` so you can `move` them anywhere
/// set_count.set(0);
/// assert_eq!(double_count(), 0);
/// set_count.set(1);
/// assert_eq!(double_count(), 2);
/// ```
#[inline(always)]
#[track_caller]
pub fn signal<T: Send + Sync + 'static>(
value: T,
) -> (ReadSignal<T>, WriteSignal<T>) {
let (r, w) = arc_signal(value);
(r.into(), w.into())
}
/// Creates an arena-allocated signal.
///
/// Unlike [`signal`], this does not require the value to be `Send + Sync`. Instead, it is stored
/// on a local arena. Accessing either of the returned signals from another thread will panic.
#[inline(always)]
#[track_caller]
pub fn signal_local<T: 'static>(
value: T,
) -> (ReadSignal<T, LocalStorage>, WriteSignal<T, LocalStorage>) {
RwSignal::new_local(value).split()
}
/// Creates an arena-allocated signal, the basic reactive primitive.
///
/// 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 updating.
///
/// Takes the initial value as an argument, and returns a tuple containing a
/// [`ReadSignal`] and a [`WriteSignal`].
///
/// This returns 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 [`arc_signal`].
/// ```
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let (count, set_count) = create_signal(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
/// set_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
/// set_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 = move || count.get() * 2; // signals are `Copy` so you can `move` them anywhere
/// set_count.set(0);
/// assert_eq!(double_count(), 0);
/// set_count.set(1);
/// assert_eq!(double_count(), 2);
/// ```
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being renamed to `signal()` to conform to \
Rust idioms."]
pub fn create_signal<T: Send + Sync + 'static>(
value: T,
) -> (ReadSignal<T>, WriteSignal<T>) {
signal(value)
}
/// Creates a reactive signal with the getter and setter unified in one value.
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `RwSignal::new()` instead."]
pub fn create_rw_signal<T: Send + Sync + 'static>(value: T) -> RwSignal<T> {
RwSignal::new(value)
}
/// A trigger is a data-less signal with the sole purpose of notifying other reactive code of a change.
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `ArcTrigger::new()` instead."]
pub fn create_trigger() -> ArcTrigger {
ArcTrigger::new()
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/callback.rs | reactive_graph/src/callback.rs | //! Callbacks define a standard way to store functions and closures. They are useful
//! for component properties, because they can be used to define optional callback functions,
//! which generic props don’t support.
//!
//! The callback types implement [`Copy`], so they can easily be moved into and out of other closures, just like signals.
//!
//! # Types
//! This modules implements 2 callback types:
//! - [`Callback`](reactive_graph::callback::Callback)
//! - [`UnsyncCallback`](reactive_graph::callback::UnsyncCallback)
//!
//! Use `SyncCallback` if the function is not `Sync` and `Send`.
use crate::{
owner::{LocalStorage, StoredValue},
traits::{Dispose, WithValue},
IntoReactiveValue,
};
use std::{fmt, rc::Rc, sync::Arc};
/// A wrapper trait for calling callbacks.
pub trait Callable<In: 'static, Out: 'static = ()> {
/// calls the callback with the specified argument.
///
/// Returns None if the callback has been disposed
fn try_run(&self, input: In) -> Option<Out>;
/// calls the callback with the specified argument.
///
/// # Panics
/// Panics if you try to run a callback that has been disposed
fn run(&self, input: In) -> Out;
}
/// A callback type that is not required to be [`Send`] or [`Sync`].
///
/// # Example
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::callback::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let _: UnsyncCallback<()> = UnsyncCallback::new(|_| {});
/// let _: UnsyncCallback<(i32, i32)> = (|_x: i32, _y: i32| {}).into();
/// let cb: UnsyncCallback<i32, String> = UnsyncCallback::new(|x: i32| x.to_string());
/// assert_eq!(cb.run(42), "42".to_string());
/// ```
pub struct UnsyncCallback<In: 'static, Out: 'static = ()>(
StoredValue<Rc<dyn Fn(In) -> Out>, LocalStorage>,
);
impl<In> fmt::Debug for UnsyncCallback<In> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
fmt.write_str("Callback")
}
}
impl<In, Out> Copy for UnsyncCallback<In, Out> {}
impl<In, Out> Clone for UnsyncCallback<In, Out> {
fn clone(&self) -> Self {
*self
}
}
impl<In, Out> Dispose for UnsyncCallback<In, Out> {
fn dispose(self) {
self.0.dispose();
}
}
impl<In, Out> UnsyncCallback<In, Out> {
/// Creates a new callback from the given function.
pub fn new<F>(f: F) -> UnsyncCallback<In, Out>
where
F: Fn(In) -> Out + 'static,
{
Self(StoredValue::new_local(Rc::new(f)))
}
/// Returns `true` if both callbacks wrap the same underlying function pointer.
#[inline]
pub fn matches(&self, other: &Self) -> bool {
self.0.with_value(|self_value| {
other
.0
.with_value(|other_value| Rc::ptr_eq(self_value, other_value))
})
}
}
impl<In: 'static, Out: 'static> Callable<In, Out> for UnsyncCallback<In, Out> {
fn try_run(&self, input: In) -> Option<Out> {
self.0.try_with_value(|fun| fun(input))
}
fn run(&self, input: In) -> Out {
self.0.with_value(|fun| fun(input))
}
}
macro_rules! impl_unsync_callable_from_fn {
($($arg:ident),*) => {
impl<F, $($arg,)* T, Out> From<F> for UnsyncCallback<($($arg,)*), Out>
where
F: Fn($($arg),*) -> T + 'static,
T: Into<Out> + 'static,
$($arg: 'static,)*
{
fn from(f: F) -> Self {
paste::paste!(
Self::new(move |($([<$arg:lower>],)*)| f($([<$arg:lower>]),*).into())
)
}
}
};
}
impl_unsync_callable_from_fn!();
impl_unsync_callable_from_fn!(P1);
impl_unsync_callable_from_fn!(P1, P2);
impl_unsync_callable_from_fn!(P1, P2, P3);
impl_unsync_callable_from_fn!(P1, P2, P3, P4);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10);
impl_unsync_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11);
impl_unsync_callable_from_fn!(
P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12
);
/// A callback type that is [`Send`] + [`Sync`].
///
/// # Example
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::callback::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let _: Callback<()> = Callback::new(|_| {});
/// let _: Callback<(i32, i32)> = (|_x: i32, _y: i32| {}).into();
/// let cb: Callback<i32, String> = Callback::new(|x: i32| x.to_string());
/// assert_eq!(cb.run(42), "42".to_string());
/// ```
pub struct Callback<In, Out = ()>(
StoredValue<Arc<dyn Fn(In) -> Out + Send + Sync>>,
)
where
In: 'static,
Out: 'static;
impl<In, Out> fmt::Debug for Callback<In, Out> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
fmt.write_str("SyncCallback")
}
}
impl<In, Out> Callable<In, Out> for Callback<In, Out> {
fn try_run(&self, input: In) -> Option<Out> {
self.0.try_with_value(|fun| fun(input))
}
fn run(&self, input: In) -> Out {
self.0.with_value(|f| f(input))
}
}
impl<In, Out> Clone for Callback<In, Out> {
fn clone(&self) -> Self {
*self
}
}
impl<In, Out> Dispose for Callback<In, Out> {
fn dispose(self) {
self.0.dispose();
}
}
impl<In, Out> Copy for Callback<In, Out> {}
macro_rules! impl_callable_from_fn {
($($arg:ident),*) => {
impl<F, $($arg,)* T, Out> From<F> for Callback<($($arg,)*), Out>
where
F: Fn($($arg),*) -> T + Send + Sync + 'static,
T: Into<Out> + 'static,
$($arg: Send + Sync + 'static,)*
{
fn from(f: F) -> Self {
paste::paste!(
Self::new(move |($([<$arg:lower>],)*)| f($([<$arg:lower>]),*).into())
)
}
}
};
}
impl_callable_from_fn!();
impl_callable_from_fn!(P1);
impl_callable_from_fn!(P1, P2);
impl_callable_from_fn!(P1, P2, P3);
impl_callable_from_fn!(P1, P2, P3, P4);
impl_callable_from_fn!(P1, P2, P3, P4, P5);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11);
impl_callable_from_fn!(P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12);
impl<In: 'static, Out: 'static> Callback<In, Out> {
/// Creates a new callback from the given function.
#[track_caller]
pub fn new<F>(fun: F) -> Self
where
F: Fn(In) -> Out + Send + Sync + 'static,
{
Self(StoredValue::new(Arc::new(fun)))
}
/// Returns `true` if both callbacks wrap the same underlying function pointer.
#[inline]
pub fn matches(&self, other: &Self) -> bool {
self.0
.try_with_value(|self_value| {
other.0.try_with_value(|other_value| {
Arc::ptr_eq(self_value, other_value)
})
})
.flatten()
.unwrap_or(false)
}
}
#[doc(hidden)]
pub struct __IntoReactiveValueMarkerCallbackSingleParam;
#[doc(hidden)]
pub struct __IntoReactiveValueMarkerCallbackStrOutputToString;
impl<I, O, F>
IntoReactiveValue<
Callback<I, O>,
__IntoReactiveValueMarkerCallbackSingleParam,
> for F
where
F: Fn(I) -> O + Send + Sync + 'static,
{
#[track_caller]
fn into_reactive_value(self) -> Callback<I, O> {
Callback::new(self)
}
}
impl<I, O, F>
IntoReactiveValue<
UnsyncCallback<I, O>,
__IntoReactiveValueMarkerCallbackSingleParam,
> for F
where
F: Fn(I) -> O + 'static,
{
#[track_caller]
fn into_reactive_value(self) -> UnsyncCallback<I, O> {
UnsyncCallback::new(self)
}
}
impl<I, F>
IntoReactiveValue<
Callback<I, String>,
__IntoReactiveValueMarkerCallbackStrOutputToString,
> for F
where
F: Fn(I) -> &'static str + Send + Sync + 'static,
{
#[track_caller]
fn into_reactive_value(self) -> Callback<I, String> {
Callback::new(move |i| self(i).to_string())
}
}
impl<I, F>
IntoReactiveValue<
UnsyncCallback<I, String>,
__IntoReactiveValueMarkerCallbackStrOutputToString,
> for F
where
F: Fn(I) -> &'static str + 'static,
{
#[track_caller]
fn into_reactive_value(self) -> UnsyncCallback<I, String> {
UnsyncCallback::new(move |i| self(i).to_string())
}
}
#[cfg(test)]
mod tests {
use super::Callable;
use crate::{
callback::{Callback, UnsyncCallback},
owner::Owner,
traits::Dispose,
IntoReactiveValue,
};
struct NoClone {}
#[test]
fn clone_callback() {
let owner = Owner::new();
owner.set();
let callback = Callback::new(move |_no_clone: NoClone| NoClone {});
let _cloned = callback;
}
#[test]
fn clone_unsync_callback() {
let owner = Owner::new();
owner.set();
let callback =
UnsyncCallback::new(move |_no_clone: NoClone| NoClone {});
let _cloned = callback;
}
#[test]
fn runback_from() {
let owner = Owner::new();
owner.set();
let _callback: Callback<(), String> = (|| "test").into();
let _callback: Callback<(i32, String), String> =
(|num, s| format!("{num} {s}")).into();
// Single params should work without needing the (foo,) tuple using IntoReactiveValue:
let _callback: Callback<usize, &'static str> =
(|_usize| "test").into_reactive_value();
let _callback: Callback<usize, String> =
(|_usize| "test").into_reactive_value();
}
#[test]
fn sync_callback_from() {
let owner = Owner::new();
owner.set();
let _callback: UnsyncCallback<(), String> = (|| "test").into();
let _callback: UnsyncCallback<(i32, String), String> =
(|num, s| format!("{num} {s}")).into();
// Single params should work without needing the (foo,) tuple using IntoReactiveValue:
let _callback: UnsyncCallback<usize, &'static str> =
(|_usize| "test").into_reactive_value();
let _callback: UnsyncCallback<usize, String> =
(|_usize| "test").into_reactive_value();
}
#[test]
fn sync_callback_try_run() {
let owner = Owner::new();
owner.set();
let callback = Callback::new(move |arg| arg);
assert_eq!(callback.try_run((0,)), Some((0,)));
callback.dispose();
assert_eq!(callback.try_run((0,)), None);
}
#[test]
fn unsync_callback_try_run() {
let owner = Owner::new();
owner.set();
let callback = UnsyncCallback::new(move |arg| arg);
assert_eq!(callback.try_run((0,)), Some((0,)));
callback.dispose();
assert_eq!(callback.try_run((0,)), None);
}
#[test]
fn callback_matches_same() {
let owner = Owner::new();
owner.set();
let callback1 = Callback::new(|x: i32| x * 2);
let callback2 = callback1;
assert!(callback1.matches(&callback2));
}
#[test]
fn callback_matches_different() {
let owner = Owner::new();
owner.set();
let callback1 = Callback::new(|x: i32| x * 2);
let callback2 = Callback::new(|x: i32| x + 1);
assert!(!callback1.matches(&callback2));
}
#[test]
fn unsync_callback_matches_same() {
let owner = Owner::new();
owner.set();
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
let callback2 = callback1;
assert!(callback1.matches(&callback2));
}
#[test]
fn unsync_callback_matches_different() {
let owner = Owner::new();
owner.set();
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
let callback2 = UnsyncCallback::new(|x: i32| x + 1);
assert!(!callback1.matches(&callback2));
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/transition.rs | reactive_graph/src/transition.rs | //! Utilities to wait for asynchronous primitives to resolve.
use futures::{channel::oneshot, future::join_all};
use or_poisoned::OrPoisoned;
use std::{
future::Future,
sync::{mpsc, OnceLock, RwLock},
};
static TRANSITION: OnceLock<RwLock<Option<TransitionInner>>> = OnceLock::new();
fn global_transition() -> &'static RwLock<Option<TransitionInner>> {
TRANSITION.get_or_init(|| RwLock::new(None))
}
#[derive(Debug, Clone)]
struct TransitionInner {
tx: mpsc::Sender<oneshot::Receiver<()>>,
}
/// Transitions allow you to wait for all asynchronous resources created during them to resolve.
#[derive(Debug)]
pub struct AsyncTransition;
impl AsyncTransition {
/// Calls the `action` function, and returns a `Future` that resolves when any
/// [`AsyncDerived`](crate::computed::AsyncDerived) or
/// or [`ArcAsyncDerived`](crate::computed::ArcAsyncDerived) that is read during the action
/// has resolved.
///
/// This allows for an inversion of control: the caller does not need to know when all the
/// resources created inside the `action` will resolve, but can wait for them to notify it.
pub async fn run<T, U>(action: impl FnOnce() -> T) -> U
where
T: Future<Output = U>,
{
let (tx, rx) = mpsc::channel();
let global_transition = global_transition();
let inner = TransitionInner { tx };
let prev = Option::replace(
&mut *global_transition.write().or_poisoned(),
inner.clone(),
);
let value = action().await;
_ = std::mem::replace(
&mut *global_transition.write().or_poisoned(),
prev,
);
let mut pending = Vec::new();
while let Ok(tx) = rx.try_recv() {
pending.push(tx);
}
join_all(pending).await;
value
}
pub(crate) fn register(rx: oneshot::Receiver<()>) {
if let Some(tx) = global_transition()
.read()
.or_poisoned()
.as_ref()
.map(|n| &n.tx)
{
// if it's an Err, that just means the Receiver was dropped
// i.e., the transition is no longer listening, in which case it doesn't matter if we
// successfully register with it or not
_ = tx.send(rx);
}
}
}
| 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.rs | reactive_graph/src/computed.rs | //! Computed reactive values that derive from other reactive values.
mod arc_memo;
mod async_derived;
mod inner;
mod memo;
mod selector;
use crate::{
prelude::*,
signal::RwSignal,
wrappers::{
read::Signal,
write::{IntoSignalSetter, SignalSetter},
},
};
pub use arc_memo::*;
pub use async_derived::*;
pub use memo::*;
pub use selector::*;
/// Derives a reactive slice of an [`RwSignal`].
///
/// Slices have the same guarantees as [`Memo`s](crate::computed::Memo):
/// they only emit their value when it has actually been changed.
///
/// Slices need a getter and a setter, and you must make sure that
/// the setter and getter only touch their respective field and nothing else.
/// They optimally should not have any side effects.
///
/// You can use slices whenever you want to react to only parts
/// of a bigger signal. The prime example would be state management,
/// where you want all state variables grouped together, but also need
/// fine-grained signals for each or some of these variables.
/// In the example below, setting an auth token will only trigger
/// the token signal, but none of the other derived signals.
/// ```
/// # use reactive_graph::prelude::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # use reactive_graph::signal::RwSignal;
/// # use reactive_graph::computed::*;
///
/// // some global state with independent fields
/// #[derive(Default, Clone, Debug)]
/// struct GlobalState {
/// count: u32,
/// name: String,
/// }
///
/// let state = RwSignal::new(GlobalState::default());
///
/// // `create_slice` lets us create a "lens" into the data
/// let (count, set_count) = create_slice(
/// // we take a slice *from* `state`
/// state,
/// // our getter returns a "slice" of the data
/// |state| state.count,
/// // our setter describes how to mutate that slice, given a new value
/// |state, n| state.count = n,
/// );
///
/// // this slice is completely independent of the `count` slice
/// // neither of them will cause the other to rerun
/// let (name, set_name) = create_slice(
/// // we take a slice *from* `state`
/// state,
/// // our getter returns a "slice" of the data
/// |state| state.name.clone(),
/// // our setter describes how to mutate that slice, given a new value
/// |state, n| state.name = n,
/// );
///
/// # if false { // don't run effects in doctest
/// Effect::new(move |_| {
/// println!("name is {}", name.get());
/// });
/// Effect::new(move |_| {
/// println!("count is {}", count.get());
/// });
/// # }
///
/// // setting count only causes count to log, not name
/// set_count.set(42);
///
/// // setting name only causes name to log, not count
/// set_name.set("Bob".into());
/// ```
#[track_caller]
pub fn create_slice<T, O, S>(
signal: RwSignal<T>,
getter: impl Fn(&T) -> O + Copy + Send + Sync + 'static,
setter: impl Fn(&mut T, S) + Copy + Send + Sync + 'static,
) -> (Signal<O>, SignalSetter<S>)
where
T: Send + Sync + 'static,
O: PartialEq + Send + Sync + 'static,
{
(
create_read_slice(signal, getter),
create_write_slice(signal, setter),
)
}
/// Takes a memoized, read-only slice of a signal. This is equivalent to the
/// read-only half of [`create_slice`].
#[track_caller]
pub fn create_read_slice<T, O>(
signal: RwSignal<T>,
getter: impl Fn(&T) -> O + Copy + Send + Sync + 'static,
) -> Signal<O>
where
T: Send + Sync + 'static,
O: PartialEq + Send + Sync + 'static,
{
Memo::new(move |_| signal.with(getter)).into()
}
/// Creates a setter to access one slice of a signal. This is equivalent to the
/// write-only half of [`create_slice`].
#[track_caller]
pub fn create_write_slice<T, O>(
signal: RwSignal<T>,
setter: impl Fn(&mut T, O) + Copy + Send + Sync + 'static,
) -> SignalSetter<O>
where
T: Send + Sync + 'static,
{
let setter = move |value| signal.update(|x| setter(x, value));
setter.into_signal_setter()
}
/// Creates a new memoized, computed reactive value.
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `Memo::new()` instead."]
pub fn create_memo<T>(
fun: impl Fn(Option<&T>) -> T + Send + Sync + 'static,
) -> Memo<T>
where
T: PartialEq + Send + Sync + 'static,
{
Memo::new(fun)
}
/// Creates a new memo by passing a function that computes the value.
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `Memo::new_owning()` instead."]
pub fn create_owning_memo<T>(
fun: impl Fn(Option<T>) -> (T, bool) + Send + Sync + 'static,
) -> Memo<T>
where
T: PartialEq + Send + Sync + 'static,
{
Memo::new_owning(fun)
}
/// A conditional signal that only notifies subscribers when a change
/// in the source signal’s value changes whether the given function is true.
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `Selector::new()` instead."]
pub fn create_selector<T>(
source: impl Fn() -> T + Clone + Send + Sync + 'static,
) -> Selector<T>
where
T: PartialEq + Eq + Send + Sync + Clone + std::hash::Hash + 'static,
{
Selector::new(source)
}
/// Creates a conditional signal that only notifies subscribers when a change
/// in the source signal’s value changes whether the given function is true.
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `Selector::new_with_fn()` instead."]
pub fn create_selector_with_fn<T>(
source: impl Fn() -> T + Clone + Send + Sync + 'static,
f: impl Fn(&T, &T) -> bool + Send + Sync + Clone + 'static,
) -> Selector<T>
where
T: PartialEq + Eq + Send + Sync + Clone + std::hash::Hash + 'static,
{
Selector::new_with_fn(source, f)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/into_reactive_value.rs | reactive_graph/src/into_reactive_value.rs | #[doc(hidden)]
pub struct __IntoReactiveValueMarkerBaseCase;
/// A helper trait that works like `Into<T>` but uses a marker generic
/// to allow more `From` implementations than would be allowed with just `Into<T>`.
pub trait IntoReactiveValue<T, M> {
/// Converts `self` into a `T`.
fn into_reactive_value(self) -> T;
}
// The base case, which allows anything which implements .into() to work:
impl<T, I> IntoReactiveValue<T, __IntoReactiveValueMarkerBaseCase> for I
where
I: Into<T>,
{
fn into_reactive_value(self) -> T {
self.into()
}
}
#[cfg(test)]
mod tests {
use crate::{
into_reactive_value::IntoReactiveValue,
owner::{LocalStorage, Owner},
traits::GetUntracked,
wrappers::read::Signal,
};
use typed_builder::TypedBuilder;
#[test]
fn test_into_signal_compiles() {
let owner = Owner::new();
owner.set();
#[cfg(not(feature = "nightly"))]
let _: Signal<usize> = (|| 2).into_reactive_value();
let _: Signal<usize, LocalStorage> = 2.into_reactive_value();
#[cfg(not(feature = "nightly"))]
let _: Signal<usize, LocalStorage> = (|| 2).into_reactive_value();
let _: Signal<String> = "str".into_reactive_value();
let _: Signal<String, LocalStorage> = "str".into_reactive_value();
#[derive(TypedBuilder)]
struct Foo {
#[builder(setter(
fn transform<M>(value: impl IntoReactiveValue<Signal<usize>, M>) {
value.into_reactive_value()
}
))]
sig: Signal<usize>,
}
assert_eq!(Foo::builder().sig(2).build().sig.get_untracked(), 2);
#[cfg(not(feature = "nightly"))]
assert_eq!(Foo::builder().sig(|| 2).build().sig.get_untracked(), 2);
assert_eq!(
Foo::builder()
.sig(Signal::stored(2))
.build()
.sig
.get_untracked(),
2
);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/nightly.rs | reactive_graph/src/nightly.rs | #[allow(deprecated)]
use crate::wrappers::read::{MaybeProp, MaybeSignal};
use crate::{
computed::{ArcMemo, Memo},
owner::Storage,
signal::{
ArcReadSignal, ArcRwSignal, ArcWriteSignal, ReadSignal, RwSignal,
WriteSignal,
},
traits::{Get, Set},
wrappers::{
read::{ArcSignal, Signal, SignalTypes},
write::SignalSetter,
},
};
macro_rules! impl_set_fn_traits {
($($ty:ident),*) => {
$(
#[cfg(feature = "nightly")]
impl<T> FnOnce<(T,)> for $ty<T> where $ty<T>: Set<Value = T> {
type Output = ();
#[inline(always)]
extern "rust-call" fn call_once(self, args: (T,)) -> Self::Output {
self.set(args.0);
}
}
#[cfg(feature = "nightly")]
impl<T> FnMut<(T,)> for $ty<T> where $ty<T>: Set<Value = T> {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, args: (T,)) -> Self::Output {
self.set(args.0);
}
}
#[cfg(feature = "nightly")]
impl<T> Fn<(T,)> for $ty<T> where $ty<T>: Set<Value = T> {
#[inline(always)]
extern "rust-call" fn call(&self, args: (T,)) -> Self::Output {
self.set(args.0);
}
}
)*
};
}
macro_rules! impl_set_fn_traits_arena {
($($ty:ident),*) => {
$(
#[cfg(feature = "nightly")]
impl<T, S> FnOnce<(T,)> for $ty<T, S> where $ty<T, S>: Set<Value = T> {
type Output = ();
#[inline(always)]
extern "rust-call" fn call_once(self, args: (T,)) -> Self::Output {
self.set(args.0);
}
}
#[cfg(feature = "nightly")]
impl<T, S> FnMut<(T,)> for $ty<T, S> where $ty<T, S>: Set<Value = T> {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, args: (T,)) -> Self::Output {
self.set(args.0);
}
}
#[cfg(feature = "nightly")]
impl<T, S> Fn<(T,)> for $ty<T, S> where $ty<T, S>: Set<Value = T> {
#[inline(always)]
extern "rust-call" fn call(&self, args: (T,)) -> Self::Output {
self.set(args.0);
}
}
)*
};
}
macro_rules! impl_get_fn_traits_get {
($($ty:ident),*) => {
$(
#[cfg(feature = "nightly")]
impl<T> FnOnce<()> for $ty<T> where $ty<T>: Get {
type Output = <Self as Get>::Value;
#[inline(always)]
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
self.get()
}
}
#[cfg(feature = "nightly")]
impl<T> FnMut<()> for $ty<T> where $ty<T>: Get {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
self.get()
}
}
#[cfg(feature = "nightly")]
impl<T> Fn<()> for $ty<T> where $ty<T>: Get {
#[inline(always)]
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
self.get()
}
}
)*
};
}
macro_rules! impl_get_fn_traits_get_arena {
($($ty:ident),*) => {
$(
#[cfg(feature = "nightly")]
#[allow(deprecated)]
impl<T, S> FnOnce<()> for $ty<T, S> where $ty<T, S>: Get, S: Storage<T> + Storage<Option<T>> + Storage<SignalTypes<Option<T>, S>> {
type Output = <Self as Get>::Value;
#[inline(always)]
extern "rust-call" fn call_once(self, _args: ()) -> Self::Output {
self.get()
}
}
#[cfg(feature = "nightly")]
#[allow(deprecated)]
impl<T, S> FnMut<()> for $ty<T, S> where $ty<T, S>: Get, S: Storage<T> + Storage<Option<T>> + Storage<SignalTypes<Option<T>, S>> {
#[inline(always)]
extern "rust-call" fn call_mut(&mut self, _args: ()) -> Self::Output {
self.get()
}
}
#[cfg(feature = "nightly")]
#[allow(deprecated)]
impl<T, S> Fn<()> for $ty<T, S> where $ty<T, S>: Get, S: Storage<T> + Storage<Option<T>> + Storage<SignalTypes<Option<T>, S>> {
#[inline(always)]
extern "rust-call" fn call(&self, _args: ()) -> Self::Output {
self.get()
}
}
)*
};
}
impl_get_fn_traits_get![ArcReadSignal, ArcRwSignal];
impl_get_fn_traits_get_arena![
ReadSignal,
RwSignal,
ArcMemo,
ArcSignal,
Signal,
MaybeSignal,
Memo,
MaybeProp
];
impl_set_fn_traits![ArcRwSignal, ArcWriteSignal];
impl_set_fn_traits_arena![RwSignal, WriteSignal, SignalSetter];
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/owner.rs | reactive_graph/src/owner.rs | //! The reactive ownership model, which manages effect cancellation, cleanups, and arena allocation.
#[cfg(feature = "hydration")]
use hydration_context::SharedContext;
use or_poisoned::OrPoisoned;
use rustc_hash::FxHashMap;
use std::{
any::{Any, TypeId},
cell::RefCell,
fmt::Debug,
mem,
sync::{Arc, RwLock, Weak},
};
mod arc_stored_value;
mod arena;
mod arena_item;
mod context;
mod storage;
mod stored_value;
use self::arena::Arena;
pub use arc_stored_value::ArcStoredValue;
#[cfg(feature = "sandboxed-arenas")]
pub use arena::sandboxed::Sandboxed;
#[cfg(feature = "sandboxed-arenas")]
use arena::ArenaMap;
use arena::NodeId;
pub use arena_item::*;
pub use context::*;
pub use storage::*;
#[allow(deprecated)] // allow exporting deprecated fn
pub use stored_value::{store_value, FromLocal, StoredValue};
/// A reactive owner, which manages
/// 1) the cancellation of [`Effect`](crate::effect::Effect)s,
/// 2) providing and accessing environment data via [`provide_context`] and [`use_context`],
/// 3) running cleanup functions defined via [`Owner::on_cleanup`], and
/// 4) an arena storage system to provide `Copy` handles via [`ArenaItem`], which is what allows
/// types like [`RwSignal`](crate::signal::RwSignal), [`Memo`](crate::computed::Memo), and so on to be `Copy`.
///
/// Every effect and computed reactive value has an associated `Owner`. While it is running, this
/// is marked as the current `Owner`. Whenever it re-runs, this `Owner` is cleared by calling
/// [`Owner::with_cleanup`]. This runs cleanup functions, cancels any [`Effect`](crate::effect::Effect)s created during the
/// last run, drops signals stored in the arena, and so on, because those effects and signals will
/// be re-created as needed during the next run.
///
/// When the owner is ultimately dropped, it will clean up its owned resources in the same way.
///
/// The "current owner" is set on the thread-local basis: whenever one of these reactive nodes is
/// running, it will set the current owner on its thread with [`Owner::with`] or [`Owner::set`],
/// allowing other reactive nodes implicitly to access the fact that it is currently the owner.
///
/// For a longer discussion of the ownership model, [see
/// here](https://book.leptos.dev/appendix_life_cycle.html).
#[derive(Debug, Clone, Default)]
#[must_use]
pub struct Owner {
pub(crate) inner: Arc<RwLock<OwnerInner>>,
#[cfg(feature = "hydration")]
pub(crate) shared_context: Option<Arc<dyn SharedContext + Send + Sync>>,
}
impl Owner {
fn downgrade(&self) -> WeakOwner {
WeakOwner {
inner: Arc::downgrade(&self.inner),
#[cfg(feature = "hydration")]
shared_context: self.shared_context.as_ref().map(Arc::downgrade),
}
}
}
#[derive(Clone)]
struct WeakOwner {
inner: Weak<RwLock<OwnerInner>>,
#[cfg(feature = "hydration")]
shared_context: Option<Weak<dyn SharedContext + Send + Sync>>,
}
impl WeakOwner {
fn upgrade(&self) -> Option<Owner> {
self.inner.upgrade().map(|inner| {
#[cfg(feature = "hydration")]
let shared_context =
self.shared_context.as_ref().and_then(|sc| sc.upgrade());
Owner {
inner,
#[cfg(feature = "hydration")]
shared_context,
}
})
}
}
impl PartialEq for Owner {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}
thread_local! {
static OWNER: RefCell<Option<WeakOwner>> = Default::default();
}
impl Owner {
/// Returns a unique identifier for this owner, which can be used to identify it for debugging
/// purposes.
///
/// Intended for debugging only; this is not guaranteed to be stable between runs.
pub fn debug_id(&self) -> usize {
Arc::as_ptr(&self.inner) as usize
}
/// Returns the list of parents, grandparents, and ancestors, with values corresponding to
/// [`Owner::debug_id`] for each.
///
/// Intended for debugging only; this is not guaranteed to be stable between runs.
pub fn ancestry(&self) -> Vec<usize> {
let mut ancestors = Vec::new();
let mut curr_parent = self
.inner
.read()
.or_poisoned()
.parent
.as_ref()
.and_then(|n| n.upgrade());
while let Some(parent) = curr_parent {
ancestors.push(Arc::as_ptr(&parent) as usize);
curr_parent = parent
.read()
.or_poisoned()
.parent
.as_ref()
.and_then(|n| n.upgrade());
}
ancestors
}
/// Creates a new `Owner` and registers it as a child of the current `Owner`, if there is one.
pub fn new() -> Self {
#[cfg(not(feature = "hydration"))]
let parent = OWNER.with(|o| {
o.borrow()
.as_ref()
.and_then(|o| o.upgrade())
.map(|o| Arc::downgrade(&o.inner))
});
#[cfg(feature = "hydration")]
let (parent, shared_context) = OWNER
.with(|o| {
o.borrow().as_ref().and_then(|o| o.upgrade()).map(|o| {
(Some(Arc::downgrade(&o.inner)), o.shared_context.clone())
})
})
.unwrap_or((None, None));
let this = Self {
inner: Arc::new(RwLock::new(OwnerInner {
parent: parent.clone(),
nodes: Default::default(),
contexts: Default::default(),
cleanups: Default::default(),
children: Default::default(),
#[cfg(feature = "sandboxed-arenas")]
arena: parent
.as_ref()
.and_then(|parent| parent.upgrade())
.map(|parent| parent.read().or_poisoned().arena.clone())
.unwrap_or_default(),
paused: false,
})),
#[cfg(feature = "hydration")]
shared_context,
};
if let Some(parent) = parent.and_then(|n| n.upgrade()) {
parent
.write()
.or_poisoned()
.children
.push(Arc::downgrade(&this.inner));
}
this
}
/// Creates a new "root" context with the given [`SharedContext`], which allows sharing data
/// between the server and client.
///
/// Only one `SharedContext` needs to be created per request, and will be automatically shared
/// by any other `Owner`s created under this one.
#[cfg(feature = "hydration")]
#[track_caller]
pub fn new_root(
shared_context: Option<Arc<dyn SharedContext + Send + Sync>>,
) -> Self {
let this = Self {
inner: Arc::new(RwLock::new(OwnerInner {
parent: None,
nodes: Default::default(),
contexts: Default::default(),
cleanups: Default::default(),
children: Default::default(),
#[cfg(feature = "sandboxed-arenas")]
arena: Default::default(),
paused: false,
})),
#[cfg(feature = "hydration")]
shared_context,
};
this.set();
this
}
/// Returns the parent of this `Owner`, if any.
///
/// None when:
/// - This is a root owner
/// - The parent has been dropped
pub fn parent(&self) -> Option<Owner> {
self.inner
.read()
.or_poisoned()
.parent
.as_ref()
.and_then(|p| p.upgrade())
.map(|inner| Owner {
inner,
#[cfg(feature = "hydration")]
shared_context: self.shared_context.clone(),
})
}
/// Creates a new `Owner` that is the child of the current `Owner`, if any.
pub fn child(&self) -> Self {
let parent = Some(Arc::downgrade(&self.inner));
let mut inner = self.inner.write().or_poisoned();
#[cfg(feature = "sandboxed-arenas")]
let arena = inner.arena.clone();
let paused = inner.paused;
let child = Self {
inner: Arc::new(RwLock::new(OwnerInner {
parent,
nodes: Default::default(),
contexts: Default::default(),
cleanups: Default::default(),
children: Default::default(),
#[cfg(feature = "sandboxed-arenas")]
arena,
paused,
})),
#[cfg(feature = "hydration")]
shared_context: self.shared_context.clone(),
};
inner.children.push(Arc::downgrade(&child.inner));
child
}
/// Sets this as the current `Owner`.
pub fn set(&self) {
OWNER.with_borrow_mut(|owner| *owner = Some(self.downgrade()));
#[cfg(feature = "sandboxed-arenas")]
Arena::set(&self.inner.read().or_poisoned().arena);
}
/// Runs the given function with this as the current `Owner`.
pub fn with<T>(&self, fun: impl FnOnce() -> T) -> T {
// codegen optimisation:
fn inner_1(self_: &Owner) -> Option<WeakOwner> {
let prev = {
OWNER.with(|o| (*o.borrow_mut()).replace(self_.downgrade()))
};
#[cfg(feature = "sandboxed-arenas")]
Arena::set(&self_.inner.read().or_poisoned().arena);
prev
}
let prev = inner_1(self);
let val = fun();
// monomorphisation optimisation:
fn inner_2(prev: Option<WeakOwner>) {
OWNER.with(|o| {
*o.borrow_mut() = prev;
});
}
inner_2(prev);
val
}
/// Cleans up this owner, the given function with this as the current `Owner`.
pub fn with_cleanup<T>(&self, fun: impl FnOnce() -> T) -> T {
self.cleanup();
self.with(fun)
}
/// Cleans up this owner in the following order:
/// 1) Runs `cleanup` on all children,
/// 2) Runs all cleanup functions registered with [`Owner::on_cleanup`],
/// 3) Drops the values of any arena-allocated [`ArenaItem`]s.
pub fn cleanup(&self) {
self.inner.cleanup();
}
/// Registers a function to be run the next time the current owner is cleaned up.
///
/// Because the ownership model is associated with reactive nodes, each "decision point" in an
/// application tends to have a separate `Owner`: as a result, these cleanup functions often
/// fill the same need as an "on unmount" function in other UI approaches, etc.
pub fn on_cleanup(fun: impl FnOnce() + Send + Sync + 'static) {
if let Some(owner) = Owner::current() {
let mut inner = owner.inner.write().or_poisoned();
#[cfg(feature = "sandboxed-arenas")]
let fun = {
let arena = Arc::clone(&inner.arena);
move || {
Arena::set(&arena);
fun()
}
};
inner.cleanups.push(Box::new(fun));
}
}
fn register(&self, node: NodeId) {
self.inner.write().or_poisoned().nodes.push(node);
}
/// Returns the current `Owner`, if any.
pub fn current() -> Option<Owner> {
OWNER.with(|o| o.borrow().as_ref().and_then(|n| n.upgrade()))
}
/// Returns the [`SharedContext`] associated with this owner, if any.
#[cfg(feature = "hydration")]
pub fn shared_context(
&self,
) -> Option<Arc<dyn SharedContext + Send + Sync>> {
self.shared_context.clone()
}
/// Removes this from its state as the thread-local owner and drops it.
/// If there are other holders of this owner, it may not cleanup, if always cleaning up is required,
/// see [`Owner::unset_with_forced_cleanup`].
pub fn unset(self) {
OWNER.with_borrow_mut(|owner| {
if owner.as_ref().and_then(|n| n.upgrade()) == Some(self) {
mem::take(owner);
}
})
}
/// Removes this from its state as the thread-local owner and drops it.
/// Unlike [`Owner::unset`], this will always run cleanup on this owner,
/// even if there are other holders of this owner.
pub fn unset_with_forced_cleanup(self) {
OWNER.with_borrow_mut(|owner| {
if owner
.as_ref()
.and_then(|n| n.upgrade())
.map(|o| o == self)
.unwrap_or(false)
{
mem::take(owner);
}
});
self.cleanup();
}
/// Returns the current [`SharedContext`], if any.
#[cfg(feature = "hydration")]
pub fn current_shared_context(
) -> Option<Arc<dyn SharedContext + Send + Sync>> {
OWNER.with(|o| {
o.borrow()
.as_ref()
.and_then(|o| o.upgrade())
.and_then(|current| current.shared_context.clone())
})
}
/// Runs the given function, after indicating that the current [`SharedContext`] should be
/// prepared to handle any data created in the function.
#[cfg(feature = "hydration")]
pub fn with_hydration<T>(fun: impl FnOnce() -> T + 'static) -> T {
fn inner<T>(fun: Box<dyn FnOnce() -> T>) -> T {
provide_context(IsHydrating(true));
let sc = OWNER.with_borrow(|o| {
o.as_ref()
.and_then(|o| o.upgrade())
.and_then(|current| current.shared_context.clone())
});
match sc {
None => fun(),
Some(sc) => {
let prev = sc.get_is_hydrating();
sc.set_is_hydrating(true);
let value = fun();
sc.set_is_hydrating(prev);
value
}
}
}
inner(Box::new(fun))
}
/// Runs the given function, after indicating that the current [`SharedContext`] should /// not handle data created in this function.
#[cfg(feature = "hydration")]
pub fn with_no_hydration<T>(fun: impl FnOnce() -> T + 'static) -> T {
fn inner<T>(fun: Box<dyn FnOnce() -> T>) -> T {
provide_context(IsHydrating(false));
let sc = OWNER.with_borrow(|o| {
o.as_ref()
.and_then(|o| o.upgrade())
.and_then(|current| current.shared_context.clone())
});
match sc {
None => fun(),
Some(sc) => {
let prev = sc.get_is_hydrating();
sc.set_is_hydrating(false);
let value = fun();
sc.set_is_hydrating(prev);
value
}
}
}
inner(Box::new(fun))
}
/// Pauses the execution of side effects for this owner, and any of its descendants.
///
/// If this owner is the owner for an [`Effect`](crate::effect::Effect) or [`RenderEffect`](crate::effect::RenderEffect), this effect will not run until [`Owner::resume`] is called. All children of this effects are also paused.
///
/// Any notifications will be ignored; effects that are notified will paused will not run when
/// resumed, until they are notified again by a source after being resumed.
pub fn pause(&self) {
let mut stack = Vec::with_capacity(16);
stack.push(Arc::downgrade(&self.inner));
while let Some(curr) = stack.pop() {
if let Some(curr) = curr.upgrade() {
let mut curr = curr.write().or_poisoned();
curr.paused = true;
stack.extend(curr.children.iter().map(Weak::clone));
}
}
}
/// Whether this owner has been paused by [`Owner::pause`].
pub fn paused(&self) -> bool {
self.inner.read().or_poisoned().paused
}
/// Resumes side effects that have been paused by [`Owner::pause`].
///
/// All children will also be resumed.
///
/// This will *not* cause side effects that were notified while paused to run, until they are
/// notified again by a source after being resumed.
pub fn resume(&self) {
let mut stack = Vec::with_capacity(16);
stack.push(Arc::downgrade(&self.inner));
while let Some(curr) = stack.pop() {
if let Some(curr) = curr.upgrade() {
let mut curr = curr.write().or_poisoned();
curr.paused = false;
stack.extend(curr.children.iter().map(Weak::clone));
}
}
}
}
#[doc(hidden)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct IsHydrating(pub bool);
/// Registers a function to be run the next time the current owner is cleaned up.
///
/// Because the ownership model is associated with reactive nodes, each "decision point" in an
/// application tends to have a separate `Owner`: as a result, these cleanup functions often
/// fill the same need as an "on unmount" function in other UI approaches, etc.
///
/// This is an alias for [`Owner::on_cleanup`].
pub fn on_cleanup(fun: impl FnOnce() + Send + Sync + 'static) {
Owner::on_cleanup(fun)
}
#[derive(Default)]
pub(crate) struct OwnerInner {
pub parent: Option<Weak<RwLock<OwnerInner>>>,
nodes: Vec<NodeId>,
pub contexts: FxHashMap<TypeId, Box<dyn Any + Send + Sync>>,
pub cleanups: Vec<Box<dyn FnOnce() + Send + Sync>>,
pub children: Vec<Weak<RwLock<OwnerInner>>>,
#[cfg(feature = "sandboxed-arenas")]
arena: Arc<RwLock<ArenaMap>>,
paused: bool,
}
impl Debug for OwnerInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OwnerInner")
.field("parent", &self.parent)
.field("nodes", &self.nodes)
.field("contexts", &self.contexts)
.field("cleanups", &self.cleanups.len())
.finish()
}
}
impl Drop for OwnerInner {
fn drop(&mut self) {
for child in std::mem::take(&mut self.children) {
if let Some(child) = child.upgrade() {
child.cleanup();
}
}
for cleanup in mem::take(&mut self.cleanups) {
cleanup();
}
let nodes = mem::take(&mut self.nodes);
if !nodes.is_empty() {
#[cfg(not(feature = "sandboxed-arenas"))]
Arena::with_mut(|arena| {
for node in nodes {
_ = arena.remove(node);
}
});
#[cfg(feature = "sandboxed-arenas")]
{
let mut arena = self.arena.write().or_poisoned();
for node in nodes {
_ = arena.remove(node);
}
}
}
}
}
trait Cleanup {
fn cleanup(&self);
}
impl Cleanup for RwLock<OwnerInner> {
fn cleanup(&self) {
let (cleanups, nodes, children) = {
let mut lock = self.write().or_poisoned();
(
mem::take(&mut lock.cleanups),
mem::take(&mut lock.nodes),
mem::take(&mut lock.children),
)
};
for child in children {
if let Some(child) = child.upgrade() {
child.cleanup();
}
}
for cleanup in cleanups {
cleanup();
}
if !nodes.is_empty() {
#[cfg(not(feature = "sandboxed-arenas"))]
Arena::with_mut(|arena| {
for node in nodes {
_ = arena.remove(node);
}
});
#[cfg(feature = "sandboxed-arenas")]
{
let arena = self.read().or_poisoned().arena.clone();
let mut arena = arena.write().or_poisoned();
for node in nodes {
_ = arena.remove(node);
}
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/send_wrapper_ext.rs | reactive_graph/src/send_wrapper_ext.rs | //! Additional wrapper utilities for [`send_wrapper::SendWrapper`].
use send_wrapper::SendWrapper;
use std::{
fmt::{Debug, Formatter},
hash,
ops::{Deref, DerefMut},
};
/// An optional value that can always be sent between threads, even if its inner value
/// in the `Some(_)` case would not be threadsafe.
///
/// This struct can be dereferenced to `Option<T>`.
///
/// If it has been given a local (`!Send`) value, that value is wrapped in a [`SendWrapper`], which
/// allows sending it between threads but will panic if it is accessed or updated from a
/// thread other than the one on which it was created.
///
/// If it is created with `None` for a local (`!Send`) type, no `SendWrapper` is created until a
/// value is provided via [`DerefMut`] or [`update`](SendOption::update).
///
/// ### Use Case
/// This is useful for cases like browser-only types, which are `!Send` but cannot be constructed
/// on the server anyway, and are only created in a single-threaded browser environment. The local
/// `SendOption` can be created with its `None` variant and sent between threads without causing issues
/// when it is dropped.
///
/// ### Panics
/// Dereferencing or dropping `SendOption` panics under the following conditions:
/// 1) It is created via [`new_local`](SendOption::new_local) (signifying a `!Send` inner type),
/// 2) It has `Some(_)` value, and
/// 3) It has been sent to a thread other than the one on which it was created.
pub struct SendOption<T> {
inner: Inner<T>,
}
// SAFETY: `SendOption` can *only* be given a T in four ways
// 1) via new(), which requires T: Send + Sync
// 2) via new_local(), which wraps T in a SendWrapper if given Some(T)
// 3) via deref_mut(), which creates a SendWrapper<Option<T>> as needed
// 4) via update(), which either dereferences an existing SendWrapper
// or creates a new SendWrapper as needed
unsafe impl<T> Send for SendOption<T> {}
unsafe impl<T> Sync for SendOption<T> {}
impl<T> PartialEq for SendOption<T>
where
T: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.deref() == other.deref()
}
}
impl<T> Eq for SendOption<T> where T: Eq {}
impl<T> PartialOrd for SendOption<T>
where
T: PartialOrd,
{
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self.deref().partial_cmp(other.deref())
}
}
impl<T> hash::Hash for SendOption<T>
where
T: hash::Hash,
{
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.deref().hash(state);
}
}
enum Inner<T> {
/// A threadsafe value.
Threadsafe(Option<T>),
/// A non-threadsafe value. If accessed/dropped from a different thread in the Some() variant, it will panic.
Local(Option<SendWrapper<Option<T>>>),
}
impl<T> SendOption<T>
where
T: Send + Sync,
{
/// Create a new threadsafe value.
pub fn new(value: Option<T>) -> Self {
Self {
inner: Inner::Threadsafe(value),
}
}
}
impl<T> From<Option<T>> for SendOption<T>
where
T: Send + Sync,
{
fn from(value: Option<T>) -> Self {
Self::new(value)
}
}
impl<T> SendOption<T> {
/// Create a new non-threadsafe value.
pub fn new_local(value: Option<T>) -> Self {
Self {
inner: if let Some(value) = value {
Inner::Local(Some(SendWrapper::new(Some(value))))
} else {
Inner::Local(None)
},
}
}
/// Update a value in place with a callback.
///
/// # Panics
/// If the value is [`Inner::Local`] and it is called from a different thread than the one the instance has been created with, it will panic.
pub fn update(&mut self, cb: impl FnOnce(&mut Option<T>)) {
match &mut self.inner {
Inner::Threadsafe(value) => cb(value),
Inner::Local(value) => match value {
Some(sw) => {
cb(sw.deref_mut());
if sw.is_none() {
*value = None;
}
}
None => {
let mut inner = None;
cb(&mut inner);
if let Some(inner) = inner {
*value = Some(SendWrapper::new(Some(inner)));
}
}
},
}
}
/// Consume the value.
///
/// # Panics
/// Panics if the [`Inner::Local`] variant and it is called from a different thread than the one the instance has been created with.
pub fn take(self) -> Option<T> {
match self.inner {
Inner::Threadsafe(value) => value,
Inner::Local(value) => value.and_then(|value| value.take()),
}
}
}
impl<T> Deref for SendOption<T> {
type Target = Option<T>;
fn deref(&self) -> &Self::Target {
match &self.inner {
Inner::Threadsafe(value) => value,
Inner::Local(value) => match value {
Some(value) => value.deref(),
None => &None,
},
}
}
}
impl<T> DerefMut for SendOption<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
match &mut self.inner {
Inner::Threadsafe(value) => value,
Inner::Local(value) => match value {
Some(value) => value.deref_mut(),
None => {
*value = Some(SendWrapper::new(None));
value.as_mut().unwrap().deref_mut()
}
},
}
}
}
impl<T: Debug> Debug for SendOption<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.inner {
Inner::Threadsafe(value) => {
write!(f, "SendOption::Threadsafe({value:?})")
}
Inner::Local(value) => {
write!(f, "SendOption::Local({value:?})")
}
}
}
}
impl<T: Clone> Clone for SendOption<T> {
fn clone(&self) -> Self {
Self {
inner: match &self.inner {
Inner::Threadsafe(value) => Inner::Threadsafe(value.clone()),
Inner::Local(value) => Inner::Local(value.clone()),
},
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/traits.rs | reactive_graph/src/traits.rs | //! A series of traits to implement the behavior of reactive primitive, especially signals.
//!
//! ## Principles
//! 1. **Composition**: Most of the traits are implemented as combinations of more primitive base traits,
//! and blanket implemented for all types that implement those traits.
//! 2. **Fallibility**: Most traits includes a `try_` variant, which returns `None` if the method
//! fails (e.g., if signals are arena allocated and this can't be found, or if an `RwLock` is
//! poisoned).
//!
//! ## Metadata Traits
//! - [`DefinedAt`] is used for debugging in the case of errors and should be implemented for all
//! signal types.
//! - [`IsDisposed`] checks whether a signal is currently accessible.
//!
//! ## Base Traits
//! | Trait | Mode | Description |
//! |-------------------|-------|---------------------------------------------------------------------------------------|
//! | [`Track`] | — | Tracks changes to this value, adding it as a source of the current reactive observer. |
//! | [`Notify`] | — | Notifies subscribers that this value has changed. |
//! | [`ReadUntracked`] | Guard | Gives immutable access to the value of this signal. |
//! | [`Write`] | Guard | Gives mutable access to the value of this signal.
//!
//! ## Derived Traits
//!
//! ### Access
//! | Trait | Mode | Composition | Description
//! |-------------------|---------------|-------------------------------|------------
//! | [`WithUntracked`] | `fn(&T) -> U` | [`ReadUntracked`] | Applies closure to the current value of the signal and returns result.
//! | [`With`] | `fn(&T) -> U` | [`ReadUntracked`] + [`Track`] | Applies closure to the current value of the signal and returns result, with reactive tracking.
//! | [`GetUntracked`] | `T` | [`WithUntracked`] + [`Clone`] | Clones the current value of the signal.
//! | [`Get`] | `T` | [`GetUntracked`] + [`Track`] | Clones the current value of the signal, with reactive tracking.
//!
//! ### Update
//! | Trait | Mode | Composition | Description
//! |---------------------|---------------|-----------------------------------|------------
//! | [`UpdateUntracked`] | `fn(&mut T)` | [`Write`] | Applies closure to the current value to update it, but doesn't notify subscribers.
//! | [`Update`] | `fn(&mut T)` | [`UpdateUntracked`] + [`Notify`] | Applies closure to the current value to update it, and notifies subscribers.
//! | [`Set`] | `T` | [`Update`] | Sets the value to a new value, and notifies subscribers.
//!
//! ## Using the Traits
//!
//! These traits are designed so that you can implement as few as possible, and the rest will be
//! implemented automatically.
//!
//! For example, if you have a struct for which you can implement [`ReadUntracked`] and [`Track`], then
//! [`WithUntracked`] and [`With`] will be implemented automatically (as will [`GetUntracked`] and
//! [`Get`] for `Clone` types). But if you cannot implement [`ReadUntracked`] (because, for example,
//! there isn't an `RwLock` so you can't wrap in a [`ReadGuard`](crate::signal::guards::ReadGuard),
//! but you can still implement [`WithUntracked`] and [`Track`], the same traits will still be implemented.
pub use crate::trait_options::*;
use crate::{
effect::Effect,
graph::{Observer, Source, Subscriber, ToAnySource},
owner::Owner,
signal::{arc_signal, guards::UntrackedWriteGuard, ArcReadSignal},
};
use any_spawner::Executor;
use futures::{Stream, StreamExt};
use std::{
ops::{Deref, DerefMut},
panic::Location,
};
#[doc(hidden)]
/// Provides a sensible panic message for accessing disposed signals.
#[macro_export]
macro_rules! unwrap_signal {
($signal:ident) => {{
#[cfg(any(debug_assertions, leptos_debuginfo))]
let location = std::panic::Location::caller();
|| {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
panic!(
"{}",
$crate::traits::panic_getting_disposed_signal(
$signal.defined_at(),
location
)
);
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
panic!(
"Tried to access a reactive value that has already been \
disposed."
);
}
}
}};
}
/// Allows disposing an arena-allocated signal before its owner has been disposed.
pub trait Dispose {
/// Disposes of the signal. This:
/// 1. Detaches the signal from the reactive graph, preventing it from triggering
/// further updates; and
/// 2. Drops the value contained in the signal.
fn dispose(self);
}
/// Allows tracking the value of some reactive data.
pub trait Track {
/// Subscribes to this signal in the current reactive scope without doing anything with its value.
#[track_caller]
fn track(&self);
}
impl<T: Source + ToAnySource + DefinedAt> Track for T {
#[track_caller]
fn track(&self) {
if self.is_disposed() {
return;
}
if let Some(subscriber) = Observer::get() {
subscriber.add_source(self.to_any_source());
self.add_subscriber(subscriber);
} else {
#[cfg(all(debug_assertions, feature = "effects"))]
{
use crate::diagnostics::SpecialNonReactiveZone;
if !SpecialNonReactiveZone::is_inside() {
let called_at = Location::caller();
let ty = std::any::type_name::<T>();
let defined_at = self
.defined_at()
.map(ToString::to_string)
.unwrap_or_else(|| String::from("{unknown}"));
crate::log_warning(format_args!(
"At {called_at}, you access a {ty} (defined at \
{defined_at}) outside a reactive tracking context. \
This might mean your app is not responding to \
changes in signal values in the way you \
expect.\n\nHere’s how to fix it:\n\n1. If this is \
inside a `view!` macro, make sure you are passing a \
function, not a value.\n ❌ NO <p>{{x.get() * \
2}}</p>\n ✅ YES <p>{{move || x.get() * \
2}}</p>\n\n2. If it’s in the body of a component, \
try wrapping this access in a closure: \n ❌ NO \
let y = x.get() * 2\n ✅ YES let y = move || \
x.get() * 2.\n\n3. If you’re *trying* to access the \
value without tracking, use `.get_untracked()` or \
`.with_untracked()` instead."
));
}
}
}
}
}
/// Give read-only access to a signal's value by reference through a guard type,
/// without tracking the value reactively.
pub trait ReadUntracked: Sized + DefinedAt {
/// The guard type that will be returned, which can be dereferenced to the value.
type Value: Deref;
/// Returns the guard, or `None` if the signal has already been disposed.
#[track_caller]
fn try_read_untracked(&self) -> Option<Self::Value>;
/// Returns the guard.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn read_untracked(&self) -> Self::Value {
self.try_read_untracked()
.unwrap_or_else(unwrap_signal!(self))
}
/// This is a backdoor to allow overriding the [`Read::try_read`] implementation despite it being auto implemented.
///
/// If your type contains a [`Signal`](crate::wrappers::read::Signal),
/// call it's [`ReadUntracked::custom_try_read`] here, else return `None`.
#[track_caller]
fn custom_try_read(&self) -> Option<Option<Self::Value>> {
None
}
}
/// Give read-only access to a signal's value by reference through a guard type,
/// and subscribes the active reactive observer (an effect or computed) to changes in its value.
pub trait Read: DefinedAt {
/// The guard type that will be returned, which can be dereferenced to the value.
type Value: Deref;
/// Subscribes to the signal, and returns the guard, or `None` if the signal has already been disposed.
#[track_caller]
fn try_read(&self) -> Option<Self::Value>;
/// Subscribes to the signal, and returns the guard.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn read(&self) -> Self::Value {
self.try_read().unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> Read for T
where
T: Track + ReadUntracked,
{
type Value = T::Value;
fn try_read(&self) -> Option<Self::Value> {
// The [`Read`] trait is auto implemented for types that implement [`ReadUntracked`] + [`Track`]. The [`Read`] trait then auto implements the [`With`] and [`Get`] traits too.
//
// This is a problem for e.g. the [`Signal`](crate::wrappers::read::Signal) type,
// this type must use a custom [`Read::try_read`] implementation to avoid an unnecessary clone.
//
// This is a backdoor to allow overriding the [`Read::try_read`] implementation despite it being auto implemented.
if let Some(custom) = self.custom_try_read() {
custom
} else {
self.track();
self.try_read_untracked()
}
}
}
/// A reactive, mutable guard that can be untracked to prevent it from notifying subscribers when
/// it is dropped.
pub trait UntrackableGuard: DerefMut {
/// Removes the notifier from the guard, such that it will no longer notify subscribers when it is dropped.
fn untrack(&mut self);
}
impl<T> UntrackableGuard for Box<dyn UntrackableGuard<Target = T>> {
fn untrack(&mut self) {
(**self).untrack();
}
}
/// Gives mutable access to a signal's value through a guard type. When the guard is dropped, the
/// signal's subscribers will be notified.
pub trait Write: Sized + DefinedAt + Notify {
/// The type of the signal's value.
type Value: Sized + 'static;
/// Returns the guard, or `None` if the signal has already been disposed.
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>>;
// Returns a guard that will not notify subscribers when dropped,
/// or `None` if the signal has already been disposed.
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>>;
/// Returns the guard.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
fn write(&self) -> impl UntrackableGuard<Target = Self::Value> {
self.try_write().unwrap_or_else(unwrap_signal!(self))
}
/// Returns a guard that will not notify subscribers when dropped.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
fn write_untracked(&self) -> impl DerefMut<Target = Self::Value> {
self.try_write_untracked()
.unwrap_or_else(unwrap_signal!(self))
}
}
/// Give read-only access to a signal's value by reference inside a closure,
/// without tracking the value reactively.
pub trait WithUntracked: DefinedAt {
/// The type of the value contained in the signal.
type Value: ?Sized;
/// Applies the closure to the value, and returns the result,
/// or `None` if the signal has already been disposed.
#[track_caller]
fn try_with_untracked<U>(
&self,
fun: impl FnOnce(&Self::Value) -> U,
) -> Option<U>;
/// Applies the closure to the value, and returns the result.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn with_untracked<U>(&self, fun: impl FnOnce(&Self::Value) -> U) -> U {
self.try_with_untracked(fun)
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> WithUntracked for T
where
T: DefinedAt + ReadUntracked,
{
type Value = <<Self as ReadUntracked>::Value as Deref>::Target;
fn try_with_untracked<U>(
&self,
fun: impl FnOnce(&Self::Value) -> U,
) -> Option<U> {
self.try_read_untracked().map(|value| fun(&value))
}
}
/// Give read-only access to a signal's value by reference inside a closure,
/// and subscribes the active reactive observer (an effect or computed) to changes in its value.
pub trait With: DefinedAt {
/// The type of the value contained in the signal.
type Value: ?Sized;
/// Subscribes to the signal, applies the closure to the value, and returns the result,
/// or `None` if the signal has already been disposed.
#[track_caller]
fn try_with<U>(&self, fun: impl FnOnce(&Self::Value) -> U) -> Option<U>;
/// Subscribes to the signal, applies the closure to the value, and returns the result.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn with<U>(&self, fun: impl FnOnce(&Self::Value) -> U) -> U {
self.try_with(fun).unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> With for T
where
T: Read,
{
type Value = <<T as Read>::Value as Deref>::Target;
#[track_caller]
fn try_with<U>(&self, fun: impl FnOnce(&Self::Value) -> U) -> Option<U> {
self.try_read().map(|val| fun(&val))
}
}
/// Clones the value of the signal, without tracking the value reactively.
pub trait GetUntracked: DefinedAt {
/// The type of the value contained in the signal.
type Value;
/// Clones and returns the value of the signal,
/// or `None` if the signal has already been disposed.
#[track_caller]
fn try_get_untracked(&self) -> Option<Self::Value>;
/// Clones and returns the value of the signal,
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn get_untracked(&self) -> Self::Value {
self.try_get_untracked()
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> GetUntracked for T
where
T: WithUntracked,
T::Value: Clone,
{
type Value = <Self as WithUntracked>::Value;
fn try_get_untracked(&self) -> Option<Self::Value> {
self.try_with_untracked(Self::Value::clone)
}
}
/// Clones the value of the signal, without tracking the value reactively.
/// and subscribes the active reactive observer (an effect or computed) to changes in its value.
pub trait Get: DefinedAt {
/// The type of the value contained in the signal.
type Value: Clone;
/// Subscribes to the signal, then clones and returns the value of the signal,
/// or `None` if the signal has already been disposed.
#[track_caller]
fn try_get(&self) -> Option<Self::Value>;
/// Subscribes to the signal, then clones and returns the value of the signal.
///
/// # Panics
/// Panics if you try to access a signal that has been disposed.
#[track_caller]
fn get(&self) -> Self::Value {
self.try_get().unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> Get for T
where
T: With,
T::Value: Clone,
{
type Value = <T as With>::Value;
#[track_caller]
fn try_get(&self) -> Option<Self::Value> {
self.try_with(Self::Value::clone)
}
}
/// Notifies subscribers of a change in this signal.
pub trait Notify {
/// Notifies subscribers of a change in this signal.
#[track_caller]
fn notify(&self);
}
/// Updates the value of a signal by applying a function that updates it in place,
/// without notifying subscribers.
pub trait UpdateUntracked: DefinedAt {
/// The type of the value contained in the signal.
type Value;
/// Updates the value by applying a function, returning the value returned by that function.
/// Does not notify subscribers that the signal has changed.
///
/// # Panics
/// Panics if you try to update a signal that has been disposed.
#[track_caller]
fn update_untracked<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> U,
) -> U {
self.try_update_untracked(fun)
.unwrap_or_else(unwrap_signal!(self))
}
/// Updates the value by applying a function, returning the value returned by that function,
/// or `None` if the signal has already been disposed.
/// Does not notify subscribers that the signal has changed.
fn try_update_untracked<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> U,
) -> Option<U>;
}
impl<T> UpdateUntracked for T
where
T: Write,
{
type Value = <Self as Write>::Value;
#[track_caller]
fn try_update_untracked<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> U,
) -> Option<U> {
let mut guard = self.try_write_untracked()?;
Some(fun(&mut *guard))
}
}
/// Updates the value of a signal by applying a function that updates it in place,
/// notifying its subscribers that the value has changed.
pub trait Update {
/// The type of the value contained in the signal.
type Value;
/// Updates the value of the signal and notifies subscribers.
#[track_caller]
fn update(&self, fun: impl FnOnce(&mut Self::Value)) {
self.try_update(fun);
}
/// Updates the value of the signal, but only notifies subscribers if the function
/// returns `true`.
#[track_caller]
fn maybe_update(&self, fun: impl FnOnce(&mut Self::Value) -> bool) {
self.try_maybe_update(|val| {
let did_update = fun(val);
(did_update, ())
});
}
/// Updates the value of the signal and notifies subscribers, returning the value that is
/// returned by the update function, or `None` if the signal has already been disposed.
#[track_caller]
fn try_update<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> U,
) -> Option<U> {
self.try_maybe_update(|val| (true, fun(val)))
}
/// Updates the value of the signal, notifying subscribers if the update function returns
/// `(true, _)`, and returns the value returned by the update function,
/// or `None` if the signal has already been disposed.
fn try_maybe_update<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> (bool, U),
) -> Option<U>;
}
impl<T> Update for T
where
T: Write,
{
type Value = <Self as Write>::Value;
#[track_caller]
fn try_maybe_update<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> (bool, U),
) -> Option<U> {
let mut lock = self.try_write()?;
let (did_update, val) = fun(&mut *lock);
if !did_update {
lock.untrack();
}
drop(lock);
Some(val)
}
}
/// Updates the value of the signal by replacing it.
pub trait Set {
/// The type of the value contained in the signal.
type Value;
/// Updates the value by replacing it, and notifies subscribers that it has changed.
fn set(&self, value: Self::Value);
/// Updates the value by replacing it, and notifies subscribers that it has changed.
///
/// If the signal has already been disposed, returns `Some(value)` with the value that was
/// passed in. Otherwise, returns `None`.
fn try_set(&self, value: Self::Value) -> Option<Self::Value>;
}
impl<T> Set for T
where
T: Update + IsDisposed,
{
type Value = <Self as Update>::Value;
#[track_caller]
fn set(&self, value: Self::Value) {
self.try_update(|n| *n = value);
}
#[track_caller]
fn try_set(&self, value: Self::Value) -> Option<Self::Value> {
if self.is_disposed() {
Some(value)
} else {
self.set(value);
None
}
}
}
/// Allows converting a signal into an async [`Stream`].
pub trait ToStream<T> {
/// Generates a [`Stream`] that emits the new value of the signal
/// whenever it changes.
///
/// # Panics
/// Panics if you try to access a signal that is owned by a reactive node that has been disposed.
#[track_caller]
fn to_stream(&self) -> impl Stream<Item = T> + Send;
}
impl<S> ToStream<S::Value> for S
where
S: Clone + Get + Send + Sync + 'static,
S::Value: Send + 'static,
{
fn to_stream(&self) -> impl Stream<Item = S::Value> + Send {
let (tx, rx) = futures::channel::mpsc::unbounded();
let close_channel = tx.clone();
Owner::on_cleanup(move || close_channel.close_channel());
Effect::new_isomorphic({
let this = self.clone();
move |_| {
let _ = tx.unbounded_send(this.get());
}
});
rx
}
}
/// Allows creating a signal from an async [`Stream`].
pub trait FromStream<T> {
/// Creates a signal that contains the latest value of the stream.
#[track_caller]
fn from_stream(stream: impl Stream<Item = T> + Send + 'static) -> Self;
/// Creates a signal that contains the latest value of the stream.
#[track_caller]
fn from_stream_unsync(stream: impl Stream<Item = T> + 'static) -> Self;
}
impl<S, T> FromStream<T> for S
where
S: From<ArcReadSignal<Option<T>>> + Send + Sync,
T: Send + Sync + 'static,
{
fn from_stream(stream: impl Stream<Item = T> + Send + 'static) -> Self {
let (read, write) = arc_signal(None);
let mut stream = Box::pin(stream);
crate::spawn(async move {
while let Some(value) = stream.next().await {
write.set(Some(value));
}
});
read.into()
}
fn from_stream_unsync(stream: impl Stream<Item = T> + 'static) -> Self {
let (read, write) = arc_signal(None);
let mut stream = Box::pin(stream);
Executor::spawn_local(async move {
while let Some(value) = stream.next().await {
write.set(Some(value));
}
});
read.into()
}
}
/// Checks whether a signal has already been disposed.
pub trait IsDisposed {
/// If `true`, the signal cannot be accessed without a panic.
fn is_disposed(&self) -> bool;
}
/// Turns a signal back into a raw value.
pub trait IntoInner {
/// The type of the value contained in the signal.
type Value;
/// Returns the inner value if this is the only reference to the signal.
/// Otherwise, returns `None` and drops this reference.
/// # Panics
/// Panics if the inner lock is poisoned.
fn into_inner(self) -> Option<Self::Value>;
}
/// Describes where the signal was defined. This is used for diagnostic warnings and is purely a
/// debug-mode tool.
pub trait DefinedAt {
/// Returns the location at which the signal was defined. This is usually simply `None` in
/// release mode.
fn defined_at(&self) -> Option<&'static Location<'static>>;
}
#[doc(hidden)]
pub fn panic_getting_disposed_signal(
defined_at: Option<&'static Location<'static>>,
location: &'static Location<'static>,
) -> String {
if let Some(defined_at) = defined_at {
format!(
"At {location}, you tried to access a reactive value which was \
defined at {defined_at}, but it has already been disposed."
)
} else {
format!(
"At {location}, you tried to access a reactive value, but it has \
already been disposed."
)
}
}
/// A variation of the [`Read`] trait that provides a signposted "always-non-reactive" API.
/// E.g. for [`StoredValue`](`crate::owner::StoredValue`).
pub trait ReadValue: Sized + DefinedAt {
/// The guard type that will be returned, which can be dereferenced to the value.
type Value: Deref;
/// Returns the non-reactive guard, or `None` if the value has already been disposed.
#[track_caller]
fn try_read_value(&self) -> Option<Self::Value>;
/// Returns the non-reactive guard.
///
/// # Panics
/// Panics if you try to access a value that has been disposed.
#[track_caller]
fn read_value(&self) -> Self::Value {
self.try_read_value().unwrap_or_else(unwrap_signal!(self))
}
}
/// A variation of the [`With`] trait that provides a signposted "always-non-reactive" API.
/// E.g. for [`StoredValue`](`crate::owner::StoredValue`).
pub trait WithValue: DefinedAt {
/// The type of the value contained in the value.
type Value: ?Sized;
/// Applies the closure to the value, non-reactively, and returns the result,
/// or `None` if the value has already been disposed.
#[track_caller]
fn try_with_value<U>(
&self,
fun: impl FnOnce(&Self::Value) -> U,
) -> Option<U>;
/// Applies the closure to the value, non-reactively, and returns the result.
///
/// # Panics
/// Panics if you try to access a value that has been disposed.
#[track_caller]
fn with_value<U>(&self, fun: impl FnOnce(&Self::Value) -> U) -> U {
self.try_with_value(fun)
.unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> WithValue for T
where
T: DefinedAt + ReadValue,
{
type Value = <<Self as ReadValue>::Value as Deref>::Target;
fn try_with_value<U>(
&self,
fun: impl FnOnce(&Self::Value) -> U,
) -> Option<U> {
self.try_read_value().map(|value| fun(&value))
}
}
/// A variation of the [`Get`] trait that provides a signposted "always-non-reactive" API.
/// E.g. for [`StoredValue`](`crate::owner::StoredValue`).
pub trait GetValue: DefinedAt {
/// The type of the value contained in the value.
type Value: Clone;
/// Clones and returns the value of the value, non-reactively,
/// or `None` if the value has already been disposed.
#[track_caller]
fn try_get_value(&self) -> Option<Self::Value>;
/// Clones and returns the value of the value, non-reactively.
///
/// # Panics
/// Panics if you try to access a value that has been disposed.
#[track_caller]
fn get_value(&self) -> Self::Value {
self.try_get_value().unwrap_or_else(unwrap_signal!(self))
}
}
impl<T> GetValue for T
where
T: WithValue,
T::Value: Clone,
{
type Value = <Self as WithValue>::Value;
fn try_get_value(&self) -> Option<Self::Value> {
self.try_with_value(Self::Value::clone)
}
}
/// A variation of the [`Write`] trait that provides a signposted "always-non-reactive" API.
/// E.g. for [`StoredValue`](`crate::owner::StoredValue`).
pub trait WriteValue: Sized + DefinedAt {
/// The type of the value's value.
type Value: Sized + 'static;
/// Returns a non-reactive write guard, or `None` if the value has already been disposed.
#[track_caller]
fn try_write_value(&self) -> Option<UntrackedWriteGuard<Self::Value>>;
/// Returns a non-reactive write guard.
///
/// # Panics
/// Panics if you try to access a value that has been disposed.
#[track_caller]
fn write_value(&self) -> UntrackedWriteGuard<Self::Value> {
self.try_write_value().unwrap_or_else(unwrap_signal!(self))
}
}
/// A variation of the [`Update`] trait that provides a signposted "always-non-reactive" API.
/// E.g. for [`StoredValue`](`crate::owner::StoredValue`).
pub trait UpdateValue: DefinedAt {
/// The type of the value contained in the value.
type Value;
/// Updates the value, returning the value that is
/// returned by the update function, or `None` if the value has already been disposed.
#[track_caller]
fn try_update_value<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> U,
) -> Option<U>;
/// Updates the value.
#[track_caller]
fn update_value(&self, fun: impl FnOnce(&mut Self::Value)) {
self.try_update_value(fun);
}
}
impl<T> UpdateValue for T
where
T: WriteValue,
{
type Value = <Self as WriteValue>::Value;
#[track_caller]
fn try_update_value<U>(
&self,
fun: impl FnOnce(&mut Self::Value) -> U,
) -> Option<U> {
let mut guard = self.try_write_value()?;
Some(fun(&mut *guard))
}
}
/// A variation of the [`Set`] trait that provides a signposted "always-non-reactive" API.
/// E.g. for [`StoredValue`](`crate::owner::StoredValue`).
pub trait SetValue: DefinedAt {
/// The type of the value contained in the value.
type Value;
/// Updates the value by replacing it, non-reactively.
///
/// If the value has already been disposed, returns `Some(value)` with the value that was
/// passed in. Otherwise, returns `None`.
#[track_caller]
fn try_set_value(&self, value: Self::Value) -> Option<Self::Value>;
/// Updates the value by replacing it, non-reactively.
#[track_caller]
fn set_value(&self, value: Self::Value) {
self.try_set_value(value);
}
}
impl<T> SetValue for T
where
T: WriteValue,
{
type Value = <Self as WriteValue>::Value;
fn try_set_value(&self, value: Self::Value) -> Option<Self::Value> {
// Unlike most other traits, for these None actually means success:
if let Some(mut guard) = self.try_write_value() {
*guard = value;
None
} else {
Some(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/channel.rs | reactive_graph/src/channel.rs | use core::sync::atomic::Ordering::Relaxed;
use futures::{task::AtomicWaker, Stream};
use std::{
fmt::Debug,
hash::Hash,
pin::Pin,
sync::{atomic::AtomicBool, Arc, Weak},
task::{Context, Poll},
};
#[derive(Debug)]
pub(crate) struct Sender(Arc<Inner>);
#[derive(Debug)]
pub(crate) struct Receiver(Weak<Inner>);
#[derive(Debug, Default)]
struct Inner {
waker: AtomicWaker,
set: AtomicBool,
}
impl Drop for Inner {
fn drop(&mut self) {
// Sender holds a strong reference to Inner, and Receiver holds a weak reference to Inner,
// so this will run when the Sender is dropped.
//
// The Receiver is usually owned by a spawned async task that is always waiting on the next
// value from its Stream. While it's waiting, it continues owning all the data it has
// captured. That data will not be dropped until the the stream ends.
//
// If we don't wake the waker a final time here, the spawned task will continue waiting for
// a final message from the Receiver that never arrives, because the waker never wakes it
// up again. So we wake the waker a final time, which tries to upgrade the Receiver, which
// fails, which causes the stream to yield Poll::Ready(None), ending the stream, and
// therefore ending the task, and therefore dropping all data that the stream has
// captured, avoiding a memory leak.
self.waker.wake();
}
}
pub fn channel() -> (Sender, Receiver) {
let inner = Arc::new(Inner {
waker: AtomicWaker::new(),
set: AtomicBool::new(false),
});
let rx = Arc::downgrade(&inner);
(Sender(inner), Receiver(rx))
}
impl Sender {
pub fn notify(&mut self) {
self.0.set.store(true, Relaxed);
self.0.waker.wake();
}
}
impl Stream for Receiver {
type Item = ();
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
if let Some(inner) = self.0.upgrade() {
inner.waker.register(cx.waker());
if inner.set.swap(false, Relaxed) {
Poll::Ready(Some(()))
} else {
Poll::Pending
}
} else {
Poll::Ready(None)
}
}
}
impl Hash for Sender {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Arc::as_ptr(&self.0).hash(state)
}
}
impl PartialEq for Sender {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for Sender {}
impl Hash for Receiver {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
Weak::as_ptr(&self.0).hash(state)
}
}
impl PartialEq for Receiver {
fn eq(&self, other: &Self) -> bool {
Weak::ptr_eq(&self.0, &other.0)
}
}
impl Eq for Receiver {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/graph.rs | reactive_graph/src/graph.rs | //! Types that define the reactive graph itself. These are mostly internal, but can be used to
//! create custom reactive primitives.
mod node;
mod sets;
mod source;
mod subscriber;
pub use node::*;
pub(crate) use sets::*;
pub use source::*;
pub use 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/effect/effect.rs | reactive_graph/src/effect/effect.rs | use crate::{
channel::{channel, Receiver},
effect::{inner::EffectInner, EffectFunction},
graph::{
AnySubscriber, ReactiveNode, SourceSet, Subscriber, ToAnySubscriber,
WithObserver,
},
owner::{ArenaItem, LocalStorage, Owner, Storage, SyncStorage},
traits::Dispose,
};
use any_spawner::Executor;
use futures::StreamExt;
use or_poisoned::OrPoisoned;
use std::{
mem,
sync::{atomic::AtomicBool, Arc, RwLock},
};
/// Effects run a certain chunk of code whenever the signals they depend on change.
///
/// Creating an effect runs the given function once after any current synchronous work is done.
/// This tracks its reactive values read within it, and reruns the function whenever the value
/// of a dependency changes.
///
/// Effects are intended to run *side-effects* of the system, not to synchronize state
/// *within* the system. In other words: In most cases, you usually should not write to
/// signals inside effects. (If you need to define a signal that depends on the value of
/// other signals, use a derived signal or a [`Memo`](crate::computed::Memo)).
///
/// You can provide an effect function without parameters or one with one parameter.
/// If you provide such a parameter, the effect function is called with an argument containing
/// whatever value it returned the last time it ran. On the initial run, this is `None`.
///
/// Effects stop running when their reactive [`Owner`] is disposed.
///
///
/// ## Example
///
/// ```
/// # 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::ArenaItem;
/// # 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 a = RwSignal::new(0);
/// let b = RwSignal::new(0);
///
/// // ✅ use effects to interact between reactive state and the outside world
/// Effect::new(move || {
/// // on the next “tick” prints "Value: 0" and subscribes to `a`
/// println!("Value: {}", a.get());
/// });
///
/// # assert_eq!(a.get(), 0);
/// a.set(1);
/// # assert_eq!(a.get(), 1);
/// // ✅ because it's subscribed to `a`, the effect reruns and prints "Value: 1"
///
/// // ❌ don't use effects to synchronize state within the reactive system
/// Effect::new(move || {
/// // this technically works but can cause unnecessary re-renders
/// // and easily lead to problems like infinite loops
/// b.set(a.get() + 1);
/// });
/// # }).await;
/// # });
/// ```
/// ## Web-Specific Notes
///
/// 1. **Scheduling**: Effects run after synchronous work, on the next “tick” of the reactive
/// system. This makes them suitable for “on mount” actions: they will fire immediately after
/// DOM rendering.
/// 2. By default, effects do not run unless the `effects` feature is enabled. If you are using
/// this with a web framework, this generally means that effects **do not run on the server**.
/// and you can call browser-specific APIs within the effect function without causing issues.
/// If you need an effect to run on the server, use [`Effect::new_isomorphic`].
#[derive(Debug, Clone, Copy)]
pub struct Effect<S> {
inner: Option<ArenaItem<StoredEffect, S>>,
}
type StoredEffect = Option<Arc<RwLock<EffectInner>>>;
impl<S> Dispose for Effect<S> {
fn dispose(self) {
if let Some(inner) = self.inner {
inner.dispose()
}
}
}
fn effect_base() -> (Receiver, Owner, Arc<RwLock<EffectInner>>) {
let (mut observer, rx) = channel();
// spawn the effect asynchronously
// we'll notify once so it runs on the next tick,
// to register observed values
observer.notify();
let owner = Owner::new();
let inner = Arc::new(RwLock::new(EffectInner {
dirty: true,
observer,
sources: SourceSet::new(),
}));
(rx, owner, inner)
}
#[cfg(debug_assertions)]
thread_local! {
static EFFECT_SCOPE_ACTIVE: AtomicBool = const { AtomicBool::new(false) };
}
#[cfg(debug_assertions)]
/// Returns whether the current thread is currently running an effect.
pub fn in_effect_scope() -> bool {
EFFECT_SCOPE_ACTIVE
.with(|scope| scope.load(std::sync::atomic::Ordering::Relaxed))
}
/// Set a static to true whilst running the given function.
/// [`is_in_effect_scope`] will return true whilst the function is running.
fn run_in_effect_scope<T>(fun: impl FnOnce() -> T) -> T {
#[cfg(debug_assertions)]
{
// For the theoretical nested case, set back to initial value rather than false:
let initial = EFFECT_SCOPE_ACTIVE.with(|scope| {
scope.swap(true, std::sync::atomic::Ordering::Relaxed)
});
let result = fun();
EFFECT_SCOPE_ACTIVE.with(|scope| {
scope.store(initial, std::sync::atomic::Ordering::Relaxed)
});
result
}
#[cfg(not(debug_assertions))]
{
fun()
}
}
impl<S> Effect<S>
where
S: Storage<StoredEffect>,
{
/// Stops this effect before it is disposed.
pub fn stop(self) {
if let Some(inner) = self
.inner
.and_then(|this| this.try_update_value(|inner| inner.take()))
{
drop(inner);
}
}
}
impl Effect<LocalStorage> {
/// Creates a new effect, which runs once on the next “tick”, and then runs again when reactive values
/// that are read inside it change.
///
/// This spawns a task on the local thread using
/// [`spawn_local`](any_spawner::Executor::spawn_local). For an effect that can be spawned on
/// any thread, use [`new_sync`](Effect::new_sync).
pub fn new<T, M>(mut fun: impl EffectFunction<T, M> + 'static) -> Self
where
T: 'static,
{
let inner = cfg!(feature = "effects").then(|| {
let (mut rx, owner, inner) = effect_base();
let value = Arc::new(RwLock::new(None::<T>));
let mut first_run = true;
Executor::spawn_local({
let value = Arc::clone(&value);
let subscriber = inner.to_any_subscriber();
async move {
while rx.next().await.is_some() {
if !owner.paused()
&& (subscriber.with_observer(|| {
subscriber.update_if_necessary()
}) || first_run)
{
first_run = false;
subscriber.clear_sources(&subscriber);
let old_value =
mem::take(&mut *value.write().or_poisoned());
let new_value = owner.with_cleanup(|| {
subscriber.with_observer(|| {
run_in_effect_scope(|| fun.run(old_value))
})
});
*value.write().or_poisoned() = Some(new_value);
}
}
}
});
ArenaItem::new_with_storage(Some(inner))
});
Self { inner }
}
/// A version of [`Effect::new`] that only listens to any dependency
/// that is accessed inside `dependency_fn`.
///
/// The return value of `dependency_fn` is passed into `handler` as an argument together with the previous value.
/// Additionally, the last return value of `handler` is provided as a third argument, as is done in [`Effect::new`].
///
/// ## Usage
///
/// ```
/// # use reactive_graph::effect::Effect;
/// # use reactive_graph::traits::*;
/// # use reactive_graph::signal::signal;
/// # 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 (num, set_num) = signal(0);
///
/// let effect = Effect::watch(
/// move || num.get(),
/// move |num, prev_num, _| {
/// // log::debug!("Number: {}; Prev: {:?}", num, prev_num);
/// },
/// false,
/// );
/// # assert_eq!(num.get(), 0);
///
/// set_num.set(1); // > "Number: 1; Prev: Some(0)"
/// # assert_eq!(num.get(), 1);
///
/// effect.stop(); // stop watching
///
/// set_num.set(2); // (nothing happens)
/// # assert_eq!(num.get(), 2);
/// # }).await;
/// # });
/// ```
///
/// The callback itself doesn't track any signal that is accessed within it.
///
/// ```
/// # use reactive_graph::effect::Effect;
/// # use reactive_graph::traits::*;
/// # use reactive_graph::signal::signal;
/// # 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 (num, set_num) = signal(0);
/// let (cb_num, set_cb_num) = signal(0);
///
/// Effect::watch(
/// move || num.get(),
/// move |num, _, _| {
/// // log::debug!("Number: {}; Cb: {}", num, cb_num.get());
/// },
/// false,
/// );
///
/// # assert_eq!(num.get(), 0);
/// set_num.set(1); // > "Number: 1; Cb: 0"
/// # assert_eq!(num.get(), 1);
///
/// # assert_eq!(cb_num.get(), 0);
/// set_cb_num.set(1); // (nothing happens)
/// # assert_eq!(cb_num.get(), 1);
///
/// set_num.set(2); // > "Number: 2; Cb: 1"
/// # assert_eq!(num.get(), 2);
/// # }).await;
/// # });
/// ```
///
/// ## Immediate
///
/// If the final parameter `immediate` is true, the `handler` will run immediately.
/// If it's `false`, the `handler` will run only after
/// the first change is detected of any signal that is accessed in `dependency_fn`.
///
/// ```
/// # use reactive_graph::effect::Effect;
/// # use reactive_graph::traits::*;
/// # use reactive_graph::signal::signal;
/// # 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 (num, set_num) = signal(0);
///
/// Effect::watch(
/// move || num.get(),
/// move |num, prev_num, _| {
/// // log::debug!("Number: {}; Prev: {:?}", num, prev_num);
/// },
/// true,
/// ); // > "Number: 0; Prev: None"
///
/// # assert_eq!(num.get(), 0);
/// set_num.set(1); // > "Number: 1; Prev: Some(0)"
/// # assert_eq!(num.get(), 1);
/// # }).await;
/// # });
/// ```
pub fn watch<D, T>(
mut dependency_fn: impl FnMut() -> D + 'static,
mut handler: impl FnMut(&D, Option<&D>, Option<T>) -> T + 'static,
immediate: bool,
) -> Self
where
D: 'static,
T: 'static,
{
let inner = cfg!(feature = "effects").then(|| {
let (mut rx, owner, inner) = effect_base();
let mut first_run = true;
let dep_value = Arc::new(RwLock::new(None::<D>));
let watch_value = Arc::new(RwLock::new(None::<T>));
Executor::spawn_local({
let dep_value = Arc::clone(&dep_value);
let watch_value = Arc::clone(&watch_value);
let subscriber = inner.to_any_subscriber();
async move {
while rx.next().await.is_some() {
if !owner.paused()
&& (subscriber.with_observer(|| {
subscriber.update_if_necessary()
}) || first_run)
{
subscriber.clear_sources(&subscriber);
let old_dep_value = mem::take(
&mut *dep_value.write().or_poisoned(),
);
let new_dep_value = owner.with_cleanup(|| {
subscriber.with_observer(&mut dependency_fn)
});
let old_watch_value = mem::take(
&mut *watch_value.write().or_poisoned(),
);
if immediate || !first_run {
let new_watch_value = handler(
&new_dep_value,
old_dep_value.as_ref(),
old_watch_value,
);
*watch_value.write().or_poisoned() =
Some(new_watch_value);
}
*dep_value.write().or_poisoned() =
Some(new_dep_value);
first_run = false;
}
}
}
});
ArenaItem::new_with_storage(Some(inner))
});
Self { inner }
}
}
impl Effect<SyncStorage> {
/// Creates a new effect, which runs once on the next “tick”, and then runs again when reactive values
/// that are read inside it change.
///
/// This spawns a task that can be run on any thread. For an effect that will be spawned on
/// the current thread, use [`new`](Effect::new).
pub fn new_sync<T, M>(
fun: impl EffectFunction<T, M> + Send + Sync + 'static,
) -> Self
where
T: Send + Sync + 'static,
{
if !cfg!(feature = "effects") {
return Self { inner: None };
}
Self::new_isomorphic(fun)
}
/// Creates a new effect, which runs once on the next “tick”, and then runs again when reactive values
/// that are read inside it change.
///
/// This will run whether the `effects` feature is enabled or not.
pub fn new_isomorphic<T, M>(
mut fun: impl EffectFunction<T, M> + Send + Sync + 'static,
) -> Self
where
T: Send + Sync + 'static,
{
let (mut rx, owner, inner) = effect_base();
let mut first_run = true;
let value = Arc::new(RwLock::new(None::<T>));
let task = {
let value = Arc::clone(&value);
let subscriber = inner.to_any_subscriber();
async move {
while rx.next().await.is_some() {
if !owner.paused()
&& (subscriber
.with_observer(|| subscriber.update_if_necessary())
|| first_run)
{
first_run = false;
subscriber.clear_sources(&subscriber);
let old_value =
mem::take(&mut *value.write().or_poisoned());
let new_value = owner.with_cleanup(|| {
subscriber.with_observer(|| {
run_in_effect_scope(|| fun.run(old_value))
})
});
*value.write().or_poisoned() = Some(new_value);
}
}
}
};
crate::spawn(task);
Self {
inner: Some(ArenaItem::new_with_storage(Some(inner))),
}
}
/// This is to [`Effect::watch`] what [`Effect::new_sync`] is to [`Effect::new`].
pub fn watch_sync<D, T>(
mut dependency_fn: impl FnMut() -> D + Send + Sync + 'static,
mut handler: impl FnMut(&D, Option<&D>, Option<T>) -> T
+ Send
+ Sync
+ 'static,
immediate: bool,
) -> Self
where
D: Send + Sync + 'static,
T: Send + Sync + 'static,
{
let (mut rx, owner, inner) = effect_base();
let mut first_run = true;
let dep_value = Arc::new(RwLock::new(None::<D>));
let watch_value = Arc::new(RwLock::new(None::<T>));
let inner = cfg!(feature = "effects").then(|| {
crate::spawn({
let dep_value = Arc::clone(&dep_value);
let watch_value = Arc::clone(&watch_value);
let subscriber = inner.to_any_subscriber();
async move {
while rx.next().await.is_some() {
if !owner.paused()
&& (subscriber.with_observer(|| {
subscriber.update_if_necessary()
}) || first_run)
{
subscriber.clear_sources(&subscriber);
let old_dep_value = mem::take(
&mut *dep_value.write().or_poisoned(),
);
let new_dep_value = owner.with_cleanup(|| {
subscriber.with_observer(&mut dependency_fn)
});
let old_watch_value = mem::take(
&mut *watch_value.write().or_poisoned(),
);
if immediate || !first_run {
let new_watch_value = handler(
&new_dep_value,
old_dep_value.as_ref(),
old_watch_value,
);
*watch_value.write().or_poisoned() =
Some(new_watch_value);
}
*dep_value.write().or_poisoned() =
Some(new_dep_value);
first_run = false;
}
}
}
});
ArenaItem::new_with_storage(Some(inner))
});
Self { inner }
}
}
impl<S> ToAnySubscriber for Effect<S>
where
S: Storage<StoredEffect>,
{
fn to_any_subscriber(&self) -> AnySubscriber {
self.inner
.and_then(|inner| {
inner
.try_with_value(|inner| {
inner.as_ref().map(|inner| inner.to_any_subscriber())
})
.flatten()
})
.expect("tried to set effect that has been stopped")
}
}
/// Creates an [`Effect`].
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `Effect::new()` instead."]
pub fn create_effect<T>(
fun: impl FnMut(Option<T>) -> T + 'static,
) -> Effect<LocalStorage>
where
T: 'static,
{
Effect::new(fun)
}
/// Creates an [`Effect`], equivalent to [Effect::watch].
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `Effect::watch()` instead."]
pub fn watch<W, T>(
deps: impl Fn() -> W + 'static,
callback: impl Fn(&W, Option<&W>, Option<T>) -> T + Clone + 'static,
immediate: bool,
) -> impl Fn() + Clone
where
W: Clone + 'static,
T: 'static,
{
let watch = Effect::watch(deps, callback, immediate);
move || watch.stop()
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/effect/inner.rs | reactive_graph/src/effect/inner.rs | use crate::{
channel::Sender,
graph::{
AnySource, AnySubscriber, ReactiveNode, SourceSet, Subscriber,
ToAnySubscriber,
},
};
use or_poisoned::OrPoisoned;
use std::sync::{Arc, RwLock, Weak};
/// Handles internal subscription logic for effects.
#[derive(Debug)]
pub struct EffectInner {
pub(crate) dirty: bool,
pub(crate) observer: Sender,
pub(crate) sources: SourceSet,
}
impl ToAnySubscriber for Arc<RwLock<EffectInner>> {
fn to_any_subscriber(&self) -> AnySubscriber {
AnySubscriber(
Arc::as_ptr(self) as usize,
Arc::downgrade(self) as Weak<dyn Subscriber + Send + Sync>,
)
}
}
impl ReactiveNode for RwLock<EffectInner> {
fn mark_subscribers_check(&self) {}
fn update_if_necessary(&self) -> bool {
let mut guard = self.write().or_poisoned();
if guard.dirty {
guard.dirty = false;
return true;
}
let sources = guard.sources.clone();
drop(guard);
sources
.into_iter()
.any(|source| source.update_if_necessary())
}
fn mark_check(&self) {
self.write().or_poisoned().observer.notify()
}
fn mark_dirty(&self) {
let mut lock = self.write().or_poisoned();
lock.dirty = true;
lock.observer.notify()
}
}
impl Subscriber for RwLock<EffectInner> {
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/effect/render_effect.rs | reactive_graph/src/effect/render_effect.rs | use crate::{
channel::channel,
effect::inner::EffectInner,
graph::{
AnySubscriber, ReactiveNode, SourceSet, Subscriber, ToAnySubscriber,
WithObserver,
},
owner::Owner,
};
use futures::StreamExt;
use or_poisoned::OrPoisoned;
#[cfg(feature = "subsecond")]
use std::sync::Mutex;
use std::{
fmt::Debug,
future::{Future, IntoFuture},
mem,
pin::Pin,
sync::{Arc, RwLock, Weak},
};
/// A render effect is similar to an [`Effect`](super::Effect), but with two key differences:
/// 1. Its first run takes place immediately and synchronously: for example, if it is being used to
/// drive a user interface, it will run during rendering, not on the next tick after rendering.
/// (Hence “render effect.”)
/// 2. It is canceled when the `RenderEffect` itself is dropped, rather than being stored in the
/// reactive system and canceled when the `Owner` cleans up.
///
/// Unless you are implementing a rendering framework, or require one of these two characteristics,
/// it is unlikely you will use render effects directly.
///
/// Like an [`Effect`](super::Effect), a render effect runs only with the `effects` feature
/// enabled.
#[must_use = "A RenderEffect will be canceled when it is dropped. Creating a \
RenderEffect that is not stored in some other data structure or \
leaked will drop it immediately, and it will not react to \
changes in signals it reads."]
pub struct RenderEffect<T>
where
T: 'static,
{
value: Arc<RwLock<Option<T>>>,
inner: Arc<RwLock<EffectInner>>,
}
impl<T> Debug for RenderEffect<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RenderEffect")
.field("inner", &Arc::as_ptr(&self.inner))
.finish()
}
}
#[cfg(feature = "subsecond")]
type CurrentHotPtr = Box<dyn Fn() -> Option<subsecond::HotFnPtr> + Send + Sync>;
impl<T> RenderEffect<T>
where
T: 'static,
{
/// Creates a new render effect, which immediately runs `fun`.
pub fn new(fun: impl FnMut(Option<T>) -> T + 'static) -> Self {
#[cfg(feature = "subsecond")]
let (hot_fn_ptr, fun) = {
let fun = Arc::new(Mutex::new(subsecond::HotFn::current(fun)));
(
{
let fun = Arc::downgrade(&fun);
let wrapped = send_wrapper::SendWrapper::new(move || {
fun.upgrade()
.map(|n| n.lock().or_poisoned().ptr_address())
});
// it's not redundant, it's due to the SendWrapper deref
#[allow(clippy::redundant_closure)]
Box::new(move || wrapped())
},
move |prev| fun.lock().or_poisoned().call((prev,)),
)
};
Self::new_with_value_erased(
Box::new(fun),
None,
#[cfg(feature = "subsecond")]
hot_fn_ptr,
)
}
/// Creates a new render effect with an initial value.
pub fn new_with_value(
fun: impl FnMut(Option<T>) -> T + 'static,
initial_value: Option<T>,
) -> Self {
#[cfg(feature = "subsecond")]
let (hot_fn_ptr, fun) = {
let fun = Arc::new(Mutex::new(subsecond::HotFn::current(fun)));
(
{
let fun = Arc::downgrade(&fun);
let wrapped = send_wrapper::SendWrapper::new(move || {
fun.upgrade()
.map(|n| n.lock().or_poisoned().ptr_address())
});
// it's not redundant, it's due to the SendWrapper deref
#[allow(clippy::redundant_closure)]
Box::new(move || wrapped())
},
move |prev| fun.lock().or_poisoned().call((prev,)),
)
};
Self::new_with_value_erased(
Box::new(fun),
initial_value,
#[cfg(feature = "subsecond")]
hot_fn_ptr,
)
}
/// Creates a new render effect, which immediately runs `fun`.
pub async fn new_with_async_value(
fun: impl FnMut(Option<T>) -> T + 'static,
value: impl IntoFuture<Output = T> + 'static,
) -> Self {
#[cfg(feature = "subsecond")]
let mut fun = subsecond::HotFn::current(fun);
#[cfg(feature = "subsecond")]
let fun = move |prev| fun.call((prev,));
Self::new_with_async_value_erased(
Box::new(fun),
Box::pin(value.into_future()),
)
.await
}
fn new_with_value_erased(
#[allow(unused_mut)] mut fun: Box<dyn FnMut(Option<T>) -> T + 'static>,
initial_value: Option<T>,
// this argument can be used to invalidate individual effects in the future
// in present experiments, I have found that it is not actually granular enough to make a difference
#[allow(unused)]
#[cfg(feature = "subsecond")]
hot_fn_ptr: CurrentHotPtr,
) -> Self {
// codegen optimisation:
fn prep() -> (Owner, Arc<RwLock<EffectInner>>, crate::channel::Receiver)
{
let (observer, rx) = channel();
let owner = Owner::new();
let inner = Arc::new(RwLock::new(EffectInner {
dirty: false,
observer,
sources: SourceSet::new(),
}));
(owner, inner, rx)
}
let (owner, inner, mut rx) = prep();
let value = Arc::new(RwLock::new(None::<T>));
#[cfg(not(feature = "effects"))]
{
let _ = initial_value;
let _ = owner;
let _ = &mut rx;
let _ = fun;
}
#[cfg(feature = "effects")]
{
let subscriber = inner.to_any_subscriber();
#[cfg(all(feature = "subsecond", debug_assertions))]
let mut fun = {
use crate::graph::ReactiveNode;
use rustc_hash::FxHashMap;
use std::sync::{Arc, LazyLock, Mutex};
use subsecond::HotFnPtr;
static HOT_RELOAD_SUBSCRIBERS: LazyLock<
Mutex<FxHashMap<AnySubscriber, (HotFnPtr, CurrentHotPtr)>>,
> = LazyLock::new(|| {
subsecond::register_handler(Arc::new(|| {
HOT_RELOAD_SUBSCRIBERS.lock().or_poisoned().retain(
|subscriber, (prev_ptr, hot_fn_ptr)| {
match hot_fn_ptr() {
None => false,
Some(curr_hot_ptr) => {
if curr_hot_ptr != *prev_ptr {
crate::log_warning(format_args!(
"{prev_ptr:?} <> \
{curr_hot_ptr:?}",
));
*prev_ptr = curr_hot_ptr;
subscriber.mark_dirty();
}
true
}
}
},
);
}));
Default::default()
});
let mut fun = subsecond::HotFn::current(fun);
let initial_ptr = hot_fn_ptr().unwrap();
HOT_RELOAD_SUBSCRIBERS
.lock()
.or_poisoned()
.insert(subscriber.clone(), (initial_ptr, hot_fn_ptr));
move |prev| fun.call((prev,))
};
*value.write().or_poisoned() = Some(
owner.with(|| subscriber.with_observer(|| fun(initial_value))),
);
any_spawner::Executor::spawn_local({
let value = Arc::clone(&value);
async move {
while rx.next().await.is_some() {
if !owner.paused()
&& subscriber.with_observer(|| {
subscriber.update_if_necessary()
})
{
subscriber.clear_sources(&subscriber);
let old_value =
mem::take(&mut *value.write().or_poisoned());
let new_value = owner.with_cleanup(|| {
subscriber.with_observer(|| fun(old_value))
});
*value.write().or_poisoned() = Some(new_value);
}
}
}
});
}
RenderEffect { value, inner }
}
async fn new_with_async_value_erased(
mut fun: Box<dyn FnMut(Option<T>) -> T + 'static>,
initial_value: Pin<Box<dyn Future<Output = T>>>,
) -> Self {
// codegen optimisation:
fn prep() -> (Owner, Arc<RwLock<EffectInner>>, crate::channel::Receiver)
{
let (observer, rx) = channel();
let owner = Owner::new();
let inner = Arc::new(RwLock::new(EffectInner {
dirty: false,
observer,
sources: SourceSet::new(),
}));
(owner, inner, rx)
}
let (owner, inner, mut rx) = prep();
let value = Arc::new(RwLock::new(None::<T>));
#[cfg(not(feature = "effects"))]
{
drop(initial_value);
let _ = owner;
let _ = &mut rx;
let _ = &mut fun;
}
#[cfg(feature = "effects")]
{
use crate::computed::ScopedFuture;
let subscriber = inner.to_any_subscriber();
let initial = subscriber
.with_observer(|| ScopedFuture::new(initial_value))
.await;
*value.write().or_poisoned() = Some(initial);
any_spawner::Executor::spawn_local({
let value = Arc::clone(&value);
async move {
while rx.next().await.is_some() {
if !owner.paused()
&& subscriber.with_observer(|| {
subscriber.update_if_necessary()
})
{
subscriber.clear_sources(&subscriber);
let old_value =
mem::take(&mut *value.write().or_poisoned());
let new_value = owner.with_cleanup(|| {
subscriber.with_observer(|| fun(old_value))
});
*value.write().or_poisoned() = Some(new_value);
}
}
}
});
}
RenderEffect { value, inner }
}
/// Mutably accesses the current value.
pub fn with_value_mut<U>(
&self,
fun: impl FnOnce(&mut T) -> U,
) -> Option<U> {
self.value.write().or_poisoned().as_mut().map(fun)
}
/// Takes the current value, replacing it with `None`.
pub fn take_value(&self) -> Option<T> {
self.value.write().or_poisoned().take()
}
}
impl<T> RenderEffect<T>
where
T: Send + Sync + 'static,
{
/// Creates a render effect that will run whether the `effects` feature is enabled or not.
pub fn new_isomorphic(
fun: impl FnMut(Option<T>) -> T + Send + Sync + 'static,
) -> Self {
#[cfg(feature = "subsecond")]
let mut fun = subsecond::HotFn::current(fun);
#[cfg(feature = "subsecond")]
let fun = move |prev| fun.call((prev,));
fn erased<T: Send + Sync + 'static>(
mut fun: Box<dyn FnMut(Option<T>) -> T + Send + Sync + 'static>,
) -> RenderEffect<T> {
let (observer, mut rx) = channel();
let value = Arc::new(RwLock::new(None::<T>));
let owner = Owner::new();
let inner = Arc::new(RwLock::new(EffectInner {
dirty: false,
observer,
sources: SourceSet::new(),
}));
let initial_value = owner
.with(|| inner.to_any_subscriber().with_observer(|| fun(None)));
*value.write().or_poisoned() = Some(initial_value);
crate::spawn({
let value = Arc::clone(&value);
let subscriber = inner.to_any_subscriber();
async move {
while rx.next().await.is_some() {
if !owner.paused()
&& subscriber.with_observer(|| {
subscriber.update_if_necessary()
})
{
subscriber.clear_sources(&subscriber);
let old_value =
mem::take(&mut *value.write().or_poisoned());
let new_value = owner.with_cleanup(|| {
subscriber.with_observer(|| fun(old_value))
});
*value.write().or_poisoned() = Some(new_value);
}
}
}
});
RenderEffect { value, inner }
}
erased(Box::new(fun))
}
}
impl<T> ToAnySubscriber for RenderEffect<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>,
)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/effect/effect_function.rs | reactive_graph/src/effect/effect_function.rs | /// Trait to enable effect functions that have zero or one parameter
pub trait EffectFunction<T, M> {
/// Call this to execute the function. In case the actual function has no parameters
/// the parameter `p` will simply be ignored.
fn run(&mut self, p: Option<T>) -> T;
}
/// Marker for single parameter functions
pub struct SingleParam;
/// Marker for no parameter functions
pub struct NoParam;
impl<Func, T> EffectFunction<T, SingleParam> for Func
where
Func: FnMut(Option<T>) -> T,
{
#[inline(always)]
fn run(&mut self, p: Option<T>) -> T {
(self)(p)
}
}
impl<Func> EffectFunction<(), NoParam> for Func
where
Func: FnMut(),
{
#[inline(always)]
fn run(&mut self, _: Option<()>) {
self()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/effect/immediate.rs | reactive_graph/src/effect/immediate.rs | use crate::{
graph::{AnySubscriber, ReactiveNode, ToAnySubscriber},
owner::on_cleanup,
traits::{DefinedAt, Dispose},
};
use or_poisoned::OrPoisoned;
use std::{
panic::Location,
sync::{Arc, Mutex, RwLock},
};
/// Effects run a certain chunk of code whenever the signals they depend on change.
///
/// The effect runs on creation and again as soon as any tracked signal changes.
///
/// NOTE: you probably want use [`Effect`](super::Effect) instead.
/// This is for the few cases where it's important to execute effects immediately and in order.
///
/// [ImmediateEffect]s stop running when dropped.
///
/// NOTE: since effects are executed immediately, they might recurse.
/// Under recursion or parallelism only the last run to start is tracked.
///
/// ## Example
///
/// ```
/// # 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::ImmediateEffect;
/// # use reactive_graph::owner::ArenaItem;
/// # let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let a = RwSignal::new(0);
/// let b = RwSignal::new(0);
///
/// // ✅ use effects to interact between reactive state and the outside world
/// let _drop_guard = ImmediateEffect::new(move || {
/// // on the next “tick” prints "Value: 0" and subscribes to `a`
/// println!("Value: {}", a.get());
/// });
///
/// // The effect runs immediately and subscribes to `a`, in the process it prints "Value: 0"
/// # assert_eq!(a.get(), 0);
/// a.set(1);
/// # assert_eq!(a.get(), 1);
/// // ✅ because it's subscribed to `a`, the effect reruns and prints "Value: 1"
/// ```
/// ## Notes
///
/// 1. **Scheduling**: Effects run immediately, as soon as any tracked signal changes.
/// 2. By default, effects do not run unless the `effects` feature is enabled. If you are using
/// this with a web framework, this generally means that effects **do not run on the server**.
/// and you can call browser-specific APIs within the effect function without causing issues.
/// If you need an effect to run on the server, use [`ImmediateEffect::new_isomorphic`].
#[derive(Debug, Clone)]
pub struct ImmediateEffect {
inner: StoredEffect,
}
type StoredEffect = Option<Arc<RwLock<inner::EffectInner>>>;
impl Dispose for ImmediateEffect {
fn dispose(self) {}
}
impl ImmediateEffect {
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
/// (Unless [batch] is used.)
///
/// NOTE: this requires a `Fn` function because it might recurse.
/// Use [Self::new_mut] to pass a `FnMut` function, it'll panic on recursion.
#[track_caller]
#[must_use]
pub fn new(fun: impl Fn() + Send + Sync + 'static) -> Self {
if !cfg!(feature = "effects") {
return Self { inner: None };
}
let inner = inner::EffectInner::new(fun);
inner.update_if_necessary();
Self { inner: Some(inner) }
}
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
/// (Unless [batch] is used.)
///
/// # Panics
/// Panics on recursion or if triggered in parallel. Also see [Self::new]
#[track_caller]
#[must_use]
pub fn new_mut(fun: impl FnMut() + Send + Sync + 'static) -> Self {
const MSG: &str = "The effect recursed or its function panicked.";
let fun = Mutex::new(fun);
Self::new(move || fun.try_lock().expect(MSG)())
}
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
/// (Unless [batch] is used.)
///
/// NOTE: this requires a `Fn` function because it might recurse.
/// Use [Self::new_mut_scoped] to pass a `FnMut` function, it'll panic on recursion.
/// NOTE: this effect is automatically cleaned up when the current owner is cleared or disposed.
#[track_caller]
pub fn new_scoped(fun: impl Fn() + Send + Sync + 'static) {
let effect = Self::new(fun);
on_cleanup(move || effect.dispose());
}
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
/// (Unless [batch] is used.)
///
/// NOTE: this effect is automatically cleaned up when the current owner is cleared or disposed.
///
/// # Panics
/// Panics on recursion or if triggered in parallel. Also see [Self::new_scoped]
#[track_caller]
pub fn new_mut_scoped(fun: impl FnMut() + Send + Sync + 'static) {
let effect = Self::new_mut(fun);
on_cleanup(move || effect.dispose());
}
/// Creates a new effect which runs immediately, then again as soon as any tracked signal changes.
///
/// This will run whether the `effects` feature is enabled or not.
#[track_caller]
#[must_use]
pub fn new_isomorphic(fun: impl Fn() + Send + Sync + 'static) -> Self {
let inner = inner::EffectInner::new(fun);
inner.update_if_necessary();
Self { inner: Some(inner) }
}
}
impl ToAnySubscriber for ImmediateEffect {
fn to_any_subscriber(&self) -> AnySubscriber {
const MSG: &str = "tried to set effect that has been stopped";
self.inner.as_ref().expect(MSG).to_any_subscriber()
}
}
impl DefinedAt for ImmediateEffect {
fn defined_at(&self) -> Option<&'static Location<'static>> {
self.inner.as_ref()?.read().or_poisoned().defined_at()
}
}
/// Defers any [ImmediateEffect]s from running until the end of the function.
///
/// NOTE: this affects only [ImmediateEffect]s, not other effects.
///
/// NOTE: this is rarely needed, but it is useful for example when multiple signals
/// need to be updated atomically (for example a double-bound signal tree).
pub fn batch<T>(f: impl FnOnce() -> T) -> T {
struct ExecuteOnDrop;
impl Drop for ExecuteOnDrop {
fn drop(&mut self) {
let effects = {
let mut batch = inner::BATCH.write().or_poisoned();
batch.take().unwrap().into_inner().expect("lock poisoned")
};
// TODO: Should we skip the effects if it's panicking?
for effect in effects {
effect.update_if_necessary();
}
}
}
let mut execute_on_drop = None;
{
let mut batch = inner::BATCH.write().or_poisoned();
if batch.is_none() {
execute_on_drop = Some(ExecuteOnDrop);
} else {
// Nested batching has no effect.
}
*batch = Some(batch.take().unwrap_or_default());
}
let ret = f();
drop(execute_on_drop);
ret
}
mod inner {
use crate::{
graph::{
AnySource, AnySubscriber, ReactiveNode, ReactiveNodeState,
SourceSet, Subscriber, ToAnySubscriber, WithObserver,
},
log_warning,
owner::Owner,
traits::DefinedAt,
};
use indexmap::IndexSet;
use or_poisoned::OrPoisoned;
use std::{
panic::Location,
sync::{Arc, RwLock, Weak},
thread::{self, ThreadId},
};
/// Only the [super::batch] function ever writes to the outer RwLock.
/// While the effects will write to the inner one.
pub(super) static BATCH: RwLock<Option<RwLock<IndexSet<AnySubscriber>>>> =
RwLock::new(None);
/// Handles subscription logic for effects.
///
/// To handle parallelism and recursion we assign ordered (1..) ids to each run.
/// We only keep the sources tracked by the run with the highest id (the last one).
///
/// We do this by:
/// - Clearing the sources before every run, so the last one clears anything before it.
/// - We stop tracking sources after the last run has completed.
/// (A parent run will start before and end after a recursive child run.)
/// - To handle parallelism with the last run, we only allow sources to be added by its thread.
pub(super) struct EffectInner {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
owner: Owner,
state: ReactiveNodeState,
/// The number of effect runs in this 'batch'.
/// Cleared when no runs are *ongoing* anymore.
/// Used to assign ordered ids to each run, and to know when we can clear these values.
run_count_start: usize,
/// The number of effect runs that have completed in the current 'batch'.
/// Cleared when no runs are *ongoing* anymore.
/// Used to know when we can clear these values.
run_done_count: usize,
/// Given ordered ids (1..), the run with the highest id that has completed in this 'batch'.
/// Cleared when no runs are *ongoing* anymore.
/// Used to know whether the current run is the latest one.
run_done_max: usize,
/// The [ThreadId] of the run with the highest id.
/// Used to prevent over-subscribing during parallel execution with the last run.
///
/// ```text
/// Thread 1:
/// -------------------------
/// --- --- =======
///
/// Thread 2:
/// -------------------------
/// -----------
/// ```
///
/// In the parallel example above, we can see why we need this.
/// The last run is marked using `=`, but another run in the other thread might
/// also be gathering sources. So we only allow the run from the correct [ThreadId] to push sources.
last_run_thread_id: ThreadId,
fun: Arc<dyn Fn() + Send + Sync>,
sources: SourceSet,
any_subscriber: AnySubscriber,
}
impl EffectInner {
#[track_caller]
pub fn new(
fun: impl Fn() + Send + Sync + 'static,
) -> Arc<RwLock<EffectInner>> {
let owner = Owner::new();
#[cfg(any(debug_assertions, leptos_debuginfo))]
let defined_at = Location::caller();
Arc::new_cyclic(|weak| {
let any_subscriber = AnySubscriber(
weak.as_ptr() as usize,
Weak::clone(weak) as Weak<dyn Subscriber + Send + Sync>,
);
RwLock::new(EffectInner {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at,
owner,
state: ReactiveNodeState::Dirty,
run_count_start: 0,
run_done_count: 0,
run_done_max: 0,
last_run_thread_id: thread::current().id(),
fun: Arc::new(fun),
sources: SourceSet::new(),
any_subscriber,
})
})
}
}
impl ToAnySubscriber for Arc<RwLock<EffectInner>> {
fn to_any_subscriber(&self) -> AnySubscriber {
AnySubscriber(
Arc::as_ptr(self) as usize,
Arc::downgrade(self) as Weak<dyn Subscriber + Send + Sync>,
)
}
}
impl ReactiveNode for RwLock<EffectInner> {
fn mark_subscribers_check(&self) {}
fn update_if_necessary(&self) -> bool {
let state = {
let guard = self.read().or_poisoned();
if guard.owner.paused() {
return false;
}
guard.state
};
let needs_update = match state {
ReactiveNodeState::Clean => false,
ReactiveNodeState::Check => {
let sources = self.read().or_poisoned().sources.clone();
sources
.into_iter()
.any(|source| source.update_if_necessary())
}
ReactiveNodeState::Dirty => true,
};
{
if let Some(batch) = &*BATCH.read().or_poisoned() {
let mut batch = batch.write().or_poisoned();
let subscriber =
self.read().or_poisoned().any_subscriber.clone();
batch.insert(subscriber);
return needs_update;
}
}
if needs_update {
let mut guard = self.write().or_poisoned();
let owner = guard.owner.clone();
let any_subscriber = guard.any_subscriber.clone();
let fun = guard.fun.clone();
// New run has started.
guard.run_count_start += 1;
// We get a value for this run, the highest value will be what we keep the sources from.
let recursion_count = guard.run_count_start;
// We clear the sources before running the effect.
// Note that this is tied to the ordering of the initial write lock acquisition
// to ensure the last run is also the last to clear them.
guard.sources.clear_sources(&any_subscriber);
// Only this thread will be able to subscribe.
guard.last_run_thread_id = thread::current().id();
if recursion_count > 2 {
warn_excessive_recursion(&guard);
}
drop(guard);
// We execute the effect.
// Note that *this could happen in parallel across threads*.
owner.with_cleanup(|| any_subscriber.with_observer(|| fun()));
let mut guard = self.write().or_poisoned();
// This run has completed.
guard.run_done_count += 1;
// We update the done count.
// Sources will only be added if recursion_done_max < recursion_count_start.
// (Meaning the last run is not done yet.)
guard.run_done_max =
Ord::max(recursion_count, guard.run_done_max);
// The same amount of runs has started and completed,
// so we can clear everything up for next time.
if guard.run_count_start == guard.run_done_count {
guard.run_count_start = 0;
guard.run_done_count = 0;
guard.run_done_max = 0;
// Can be left unchanged, it'll be set again next time.
// guard.last_run_thread_id = thread::current().id();
}
guard.state = ReactiveNodeState::Clean;
}
needs_update
}
fn mark_check(&self) {
self.write().or_poisoned().state = ReactiveNodeState::Check;
self.update_if_necessary();
}
fn mark_dirty(&self) {
self.write().or_poisoned().state = ReactiveNodeState::Dirty;
self.update_if_necessary();
}
}
impl Subscriber for RwLock<EffectInner> {
fn add_source(&self, source: AnySource) {
let mut guard = self.write().or_poisoned();
if guard.run_done_max < guard.run_count_start
&& guard.last_run_thread_id == thread::current().id()
{
guard.sources.insert(source);
}
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
self.write().or_poisoned().sources.clear_sources(subscriber);
}
}
impl DefinedAt for EffectInner {
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 std::fmt::Debug for EffectInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EffectInner")
.field("owner", &self.owner)
.field("state", &self.state)
.field("sources", &self.sources)
.field("any_subscriber", &self.any_subscriber)
.finish()
}
}
fn warn_excessive_recursion(effect: &EffectInner) {
const MSG: &str = "ImmediateEffect recursed more than once.";
match effect.defined_at() {
Some(defined_at) => {
log_warning(format_args!("{MSG} Defined at: {defined_at}"));
}
None => {
log_warning(format_args!("{MSG}"));
}
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/graph/node.rs | reactive_graph/src/graph/node.rs | /// A node in the reactive graph.
pub trait ReactiveNode {
/// Notifies the source's dependencies that it has changed.
fn mark_dirty(&self);
/// Notifies the source's dependencies that it may have changed.
fn mark_check(&self);
/// Marks that all subscribers need to be checked.
fn mark_subscribers_check(&self);
/// Regenerates the value for this node, if needed, and returns whether
/// it has actually changed or not.
fn update_if_necessary(&self) -> bool;
}
/// The current state of a reactive node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ReactiveNodeState {
/// The node is known to be clean: i.e., either none of its sources have changed, or its
/// sources have changed but its value is unchanged and its dependencies do not need to change.
Clean,
/// The node may have changed, but it is not yet known whether it has actually changed.
Check,
/// The node's value has definitely changed, and subscribers will need to update.
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/graph/source.rs | reactive_graph/src/graph/source.rs | use super::{node::ReactiveNode, AnySubscriber};
use crate::traits::{DefinedAt, IsDisposed};
use core::{fmt::Debug, hash::Hash};
use std::{panic::Location, sync::Weak};
/// Abstracts over the type of any reactive source.
pub trait ToAnySource: IsDisposed {
/// Converts this type to its type-erased equivalent.
fn to_any_source(&self) -> AnySource;
}
/// Describes the behavior of any source of reactivity (like a signal, trigger, or memo.)
pub trait Source: ReactiveNode {
/// Adds a subscriber to this source's list of dependencies.
fn add_subscriber(&self, subscriber: AnySubscriber);
/// Removes a subscriber from this source's list of dependencies.
fn remove_subscriber(&self, subscriber: &AnySubscriber);
/// Remove all subscribers from this source's list of dependencies.
fn clear_subscribers(&self);
}
/// A weak reference to any reactive source node.
#[derive(Clone)]
pub struct AnySource(
pub(crate) usize,
pub(crate) Weak<dyn Source + Send + Sync>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) &'static Location<'static>,
);
impl DefinedAt for AnySource {
fn defined_at(&self) -> Option<&'static Location<'static>> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
{
Some(self.2)
}
#[cfg(not(any(debug_assertions, leptos_debuginfo)))]
{
None
}
}
}
impl Debug for AnySource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("AnySource").field(&self.0).finish()
}
}
impl Hash for AnySource {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl PartialEq for AnySource {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for AnySource {}
impl IsDisposed for AnySource {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl ToAnySource for AnySource {
fn to_any_source(&self) -> AnySource {
self.clone()
}
}
impl Source for AnySource {
fn add_subscriber(&self, subscriber: AnySubscriber) {
if let Some(inner) = self.1.upgrade() {
inner.add_subscriber(subscriber)
}
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
if let Some(inner) = self.1.upgrade() {
inner.remove_subscriber(subscriber)
}
}
fn clear_subscribers(&self) {
if let Some(inner) = self.1.upgrade() {
inner.clear_subscribers();
}
}
}
impl ReactiveNode for AnySource {
fn mark_dirty(&self) {
if let Some(inner) = self.1.upgrade() {
inner.mark_dirty()
}
}
fn mark_subscribers_check(&self) {
if let Some(inner) = self.1.upgrade() {
inner.mark_subscribers_check()
}
}
fn update_if_necessary(&self) -> bool {
if let Some(inner) = self.1.upgrade() {
inner.update_if_necessary()
} else {
false
}
}
fn mark_check(&self) {
if let Some(inner) = self.1.upgrade() {
inner.mark_check()
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/graph/subscriber.rs | reactive_graph/src/graph/subscriber.rs | use super::{node::ReactiveNode, AnySource};
#[cfg(debug_assertions)]
use crate::diagnostics::SpecialNonReactiveZone;
use core::{fmt::Debug, hash::Hash};
use std::{cell::RefCell, mem, sync::Weak};
thread_local! {
static OBSERVER: RefCell<Option<ObserverState>> = const { RefCell::new(None) };
}
#[derive(Debug)]
struct ObserverState {
subscriber: AnySubscriber,
untracked: bool,
}
/// The current reactive observer.
///
/// The observer is whatever reactive node is currently listening for signals that need to be
/// tracked. For example, if an effect is running, that effect is the observer, which means it will
/// subscribe to changes in any signals that are read.
pub struct Observer;
#[derive(Debug)]
struct SetObserverOnDrop(Option<AnySubscriber>);
impl Drop for SetObserverOnDrop {
fn drop(&mut self) {
Observer::set(self.0.take());
}
}
impl Observer {
/// Returns the current observer, if any.
pub fn get() -> Option<AnySubscriber> {
OBSERVER.with_borrow(|obs| {
obs.as_ref().and_then(|obs| {
if obs.untracked {
None
} else {
Some(obs.subscriber.clone())
}
})
})
}
pub(crate) fn is(observer: &AnySubscriber) -> bool {
OBSERVER.with_borrow(|o| {
o.as_ref().map(|o| &o.subscriber) == Some(observer)
})
}
fn take() -> SetObserverOnDrop {
SetObserverOnDrop(
OBSERVER.with_borrow_mut(Option::take).map(|o| o.subscriber),
)
}
fn set(observer: Option<AnySubscriber>) {
OBSERVER.with_borrow_mut(|o| {
*o = observer.map(|subscriber| ObserverState {
subscriber,
untracked: false,
})
});
}
fn replace(observer: Option<AnySubscriber>) -> SetObserverOnDrop {
SetObserverOnDrop(
OBSERVER
.with(|o| {
mem::replace(
&mut *o.borrow_mut(),
observer.map(|subscriber| ObserverState {
subscriber,
untracked: false,
}),
)
})
.map(|o| o.subscriber),
)
}
fn replace_untracked(observer: Option<AnySubscriber>) -> SetObserverOnDrop {
SetObserverOnDrop(
OBSERVER
.with(|o| {
mem::replace(
&mut *o.borrow_mut(),
observer.map(|subscriber| ObserverState {
subscriber,
untracked: true,
}),
)
})
.map(|o| o.subscriber),
)
}
}
/// Suspends reactive tracking while running the given function.
///
/// This can be used to isolate parts of the reactive graph from one another.
///
/// ```rust
/// # use reactive_graph::computed::*;
/// # use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::graph::untrack;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio(); let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let (a, set_a) = signal(0);
/// let (b, set_b) = signal(0);
/// let c = Memo::new(move |_| {
/// // this memo will *only* update when `a` changes
/// a.get() + untrack(move || b.get())
/// });
///
/// assert_eq!(c.get(), 0);
/// set_a.set(1);
/// assert_eq!(c.get(), 1);
/// set_b.set(1);
/// // hasn't updated, because we untracked before reading b
/// assert_eq!(c.get(), 1);
/// set_a.set(2);
/// assert_eq!(c.get(), 3);
/// # });
/// ```
#[track_caller]
pub fn untrack<T>(fun: impl FnOnce() -> T) -> T {
#[cfg(debug_assertions)]
let _warning_guard = crate::diagnostics::SpecialNonReactiveZone::enter();
let _prev = Observer::take();
fun()
}
#[doc(hidden)]
#[track_caller]
pub fn untrack_with_diagnostics<T>(fun: impl FnOnce() -> T) -> T {
let _prev = Observer::take();
fun()
}
/// Converts a [`Subscriber`] to a type-erased [`AnySubscriber`].
pub trait ToAnySubscriber {
/// Converts this type to its type-erased equivalent.
fn to_any_subscriber(&self) -> AnySubscriber;
}
/// Any type that can track reactive values (like an effect or a memo).
pub trait Subscriber: ReactiveNode {
/// Adds a subscriber to this subscriber's list of dependencies.
fn add_source(&self, source: AnySource);
/// Clears the set of sources for this subscriber.
fn clear_sources(&self, subscriber: &AnySubscriber);
}
/// A type-erased subscriber.
#[derive(Clone)]
pub struct AnySubscriber(pub usize, pub Weak<dyn Subscriber + Send + Sync>);
impl ToAnySubscriber for AnySubscriber {
fn to_any_subscriber(&self) -> AnySubscriber {
self.clone()
}
}
impl Subscriber for AnySubscriber {
fn add_source(&self, source: AnySource) {
if let Some(inner) = self.1.upgrade() {
inner.add_source(source);
}
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
if let Some(inner) = self.1.upgrade() {
inner.clear_sources(subscriber);
}
}
}
impl ReactiveNode for AnySubscriber {
fn mark_dirty(&self) {
if let Some(inner) = self.1.upgrade() {
inner.mark_dirty()
}
}
fn mark_subscribers_check(&self) {
if let Some(inner) = self.1.upgrade() {
inner.mark_subscribers_check()
}
}
fn update_if_necessary(&self) -> bool {
if let Some(inner) = self.1.upgrade() {
inner.update_if_necessary()
} else {
false
}
}
fn mark_check(&self) {
if let Some(inner) = self.1.upgrade() {
inner.mark_check()
}
}
}
/// Runs code with some subscriber as the thread-local [`Observer`].
pub trait WithObserver {
/// Runs the given function with this subscriber as the thread-local [`Observer`].
fn with_observer<T>(&self, fun: impl FnOnce() -> T) -> T;
/// Runs the given function with this subscriber as the thread-local [`Observer`],
/// but without tracking dependencies.
fn with_observer_untracked<T>(&self, fun: impl FnOnce() -> T) -> T;
}
impl WithObserver for AnySubscriber {
fn with_observer<T>(&self, fun: impl FnOnce() -> T) -> T {
let _prev = Observer::replace(Some(self.clone()));
fun()
}
fn with_observer_untracked<T>(&self, fun: impl FnOnce() -> T) -> T {
#[cfg(debug_assertions)]
let _guard = SpecialNonReactiveZone::enter();
let _prev = Observer::replace_untracked(Some(self.clone()));
fun()
}
}
impl WithObserver for Option<AnySubscriber> {
fn with_observer<T>(&self, fun: impl FnOnce() -> T) -> T {
let _prev = Observer::replace(self.clone());
fun()
}
fn with_observer_untracked<T>(&self, fun: impl FnOnce() -> T) -> T {
#[cfg(debug_assertions)]
let _guard = SpecialNonReactiveZone::enter();
let _prev = Observer::replace_untracked(self.clone());
fun()
}
}
impl Debug for AnySubscriber {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("AnySubscriber").field(&self.0).finish()
}
}
impl Hash for AnySubscriber {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl PartialEq for AnySubscriber {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for AnySubscriber {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/graph/sets.rs | reactive_graph/src/graph/sets.rs | //! Types that hold the set of sources or subscribers affiliated with a reactive node.
//!
//! At the moment, these are implemented as linear maps built on a `Vec<_>`. This is for the sake
//! of minimizing binary size as much as possible, and on the assumption that the M:N relationship
//! between sources and subscribers usually consists of fairly small numbers, such that the cost of
//! a linear search is not significantly more expensive than a hash and lookup.
use super::{AnySource, AnySubscriber, Source};
use indexmap::IndexSet;
use rustc_hash::FxHasher;
use std::{hash::BuildHasherDefault, mem};
type FxIndexSet<T> = IndexSet<T, BuildHasherDefault<FxHasher>>;
#[derive(Default, Clone, Debug)]
pub struct SourceSet(FxIndexSet<AnySource>);
impl SourceSet {
pub fn new() -> Self {
Self(Default::default())
}
pub fn insert(&mut self, source: AnySource) {
self.0.insert(source);
}
pub fn remove(&mut self, source: &AnySource) {
self.0.shift_remove(source);
}
pub fn take(&mut self) -> FxIndexSet<AnySource> {
mem::take(&mut self.0)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn clear_sources(&mut self, subscriber: &AnySubscriber) {
for source in self.take() {
source.remove_subscriber(subscriber);
}
}
}
impl IntoIterator for SourceSet {
type Item = AnySource;
type IntoIter = <FxIndexSet<AnySource> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a SourceSet {
type Item = &'a AnySource;
type IntoIter = <&'a FxIndexSet<AnySource> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
#[derive(Debug, Default, Clone)]
pub struct SubscriberSet(FxIndexSet<AnySubscriber>);
impl SubscriberSet {
pub fn new() -> Self {
Self(FxIndexSet::with_capacity_and_hasher(2, Default::default()))
}
pub fn subscribe(&mut self, subscriber: AnySubscriber) {
self.0.insert(subscriber);
}
pub fn unsubscribe(&mut self, subscriber: &AnySubscriber) {
// note: do not use `.swap_remove()` here.
// using `.remove()` is slower because it shifts other items
// but it maintains the order of the subscribers, which is important
// to correctness when you're using this to drive something like a UI,
// which can have nested effects, where the inner one assumes the outer
// has already run (for example, an outer effect that checks .is_some(),
// and an inner effect that unwraps)
self.0.shift_remove(subscriber);
}
pub fn take(&mut self) -> FxIndexSet<AnySubscriber> {
mem::take(&mut self.0)
}
pub fn len(&self) -> usize {
self.0.len()
}
}
impl IntoIterator for SubscriberSet {
type Item = AnySubscriber;
type IntoIter = <FxIndexSet<AnySubscriber> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a SubscriberSet {
type Item = &'a AnySubscriber;
type IntoIter = <&'a FxIndexSet<AnySubscriber> as IntoIterator>::IntoIter;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/actions/multi_action.rs | reactive_graph/src/actions/multi_action.rs | use crate::{
diagnostics::is_suppressing_resource_load,
owner::{ArenaItem, FromLocal, LocalStorage, Storage, SyncStorage},
signal::{ArcReadSignal, ArcRwSignal, ReadSignal, RwSignal},
traits::{DefinedAt, Dispose, GetUntracked, Set, Update},
unwrap_signal,
};
use std::{fmt::Debug, future::Future, panic::Location, pin::Pin, sync::Arc};
/// An action that synchronizes multiple imperative `async` calls to the reactive system,
/// tracking the progress of each one.
///
/// Where an [`Action`](super::Action) fires a single call, a `MultiAction` allows you to
/// keep track of multiple in-flight actions.
///
/// If you’re trying to load data by running an `async` function reactively, you probably
/// want to use an [`AsyncDerived`](crate::computed::AsyncDerived) instead.
/// If you’re trying to occasionally run an `async` function in response to something
/// like a user adding a task to a todo list, you’re in the right place.
///
/// The reference-counted, `Clone` (but not `Copy` version of a `MultiAction` is an [`ArcMultiAction`].
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = MultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// let submissions = add_todo.submissions();
/// assert_eq!(submissions.with(Vec::len), 3);
/// # });
/// ```
pub struct MultiAction<I, O, S = SyncStorage> {
inner: ArenaItem<ArcMultiAction<I, O>, S>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<I, O, S> Dispose for MultiAction<I, O, S> {
fn dispose(self) {
self.inner.dispose()
}
}
impl<I, O, S> DefinedAt for MultiAction<I, O, S>
where
I: 'static,
O: 'static,
{
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<I, O, S> Copy for MultiAction<I, O, S>
where
I: 'static,
O: 'static,
{
}
impl<I, O, S> Clone for MultiAction<I, O, S>
where
I: 'static,
O: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<I, O> MultiAction<I, O>
where
I: Send + Sync + 'static,
O: Send + Sync + 'static,
{
/// Creates a new multi-action.
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Submission::input] as well.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// // if there's a single argument, just use that
/// let action1 = MultiAction::new(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = MultiAction::new(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 =
/// MultiAction::new(|input: &(usize, String)| async { todo!() });
/// # });
/// ```
#[track_caller]
pub fn new<Fut>(
action_fn: impl Fn(&I) -> Fut + Send + Sync + 'static,
) -> Self
where
Fut: Future<Output = O> + Send + 'static,
{
Self {
inner: ArenaItem::new_with_storage(ArcMultiAction::new(action_fn)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<I, O, S> MultiAction<I, O, S>
where
I: Send + Sync + 'static,
O: Send + Sync + 'static,
S: Storage<ArcMultiAction<I, O>>,
{
/// Calls the `async` function with a reference to the input type as its argument.
///
/// This can be called any number of times: each submission will be dispatched, running
/// concurrently, and its status can be checked via the
/// [`submissions()`](MultiAction::submissions) signal.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = MultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let submissions = add_todo.submissions();
/// let pending_submissions = move || {
/// submissions.with(|subs| subs.iter().filter(|sub| sub.pending().get()).count())
/// };
///
/// add_todo.dispatch("Buy milk".to_string());
/// assert_eq!(submissions.with(Vec::len), 1);
/// assert_eq!(pending_submissions(), 1);
///
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(submissions.with(Vec::len), 3);
/// assert_eq!(pending_submissions(), 3);
///
/// // when submissions resolve, they are not removed from the set
/// // however, their `pending` signal is now `false`, and this can be used to filter them
/// # any_spawner::Executor::tick().await;
/// assert_eq!(submissions.with(Vec::len), 3);
/// assert_eq!(pending_submissions(), 0);
/// # });
/// ```
pub fn dispatch(&self, input: I) {
if !is_suppressing_resource_load() {
self.inner.try_with_value(|inner| inner.dispatch(input));
}
}
/// Synchronously adds a submission with the given value.
///
/// This takes the output value, rather than the input, because it is adding a result, not an
/// input.
///
/// This can be useful for use cases like handling errors, where the error can already be known
/// on the client side.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = MultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let submissions = add_todo.submissions();
/// let pending_submissions = move || {
/// submissions.with(|subs| subs.iter().filter(|sub| sub.pending().get()).count())
/// };
///
/// add_todo.dispatch("Buy milk".to_string());
/// assert_eq!(submissions.with(Vec::len), 1);
/// assert_eq!(pending_submissions(), 1);
///
/// add_todo.dispatch_sync(42);
///
/// assert_eq!(submissions.with(Vec::len), 2);
/// assert_eq!(pending_submissions(), 1);
/// # });
/// ```
pub fn dispatch_sync(&self, value: O) {
self.inner
.try_with_value(|inner| inner.dispatch_sync(value));
}
}
impl<I, O> MultiAction<I, O>
where
I: Send + Sync + 'static,
O: Send + Sync + 'static,
{
/// The set of all submissions to this multi-action.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = MultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let submissions = add_todo.submissions();
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(submissions.with(Vec::len), 3);
/// # });
/// ```
pub fn submissions(&self) -> ReadSignal<Vec<ArcSubmission<I, O>>> {
self.inner
.try_with_value(|inner| inner.submissions())
.unwrap_or_else(unwrap_signal!(self))
.into()
}
}
impl<I, O, S> MultiAction<I, O, S>
where
I: 'static,
O: 'static,
S: Storage<ArcMultiAction<I, O>>
+ Storage<ArcReadSignal<Vec<ArcSubmission<I, O>>>>,
{
/// How many times an action has successfully resolved.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = MultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let version = add_todo.version();
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(version.get(), 0);
/// # any_spawner::Executor::tick().await;
///
/// // when they've all resolved
/// assert_eq!(version.get(), 3);
/// # });
/// ```
pub fn version(&self) -> RwSignal<usize> {
self.inner
.try_with_value(|inner| inner.version())
.unwrap_or_else(unwrap_signal!(self))
.into()
}
}
/// An action that synchronizes multiple imperative `async` calls to the reactive system,
/// tracking the progress of each one.
///
/// Where an [`Action`](super::Action) fires a single call, a `MultiAction` allows you to
/// keep track of multiple in-flight actions.
///
/// If you’re trying to load data by running an `async` function reactively, you probably
/// want to use an [`AsyncDerived`](crate::computed::AsyncDerived) instead.
/// If you’re trying to occasionally run an `async` function in response to something
/// like a user adding a task to a todo list, you’re in the right place.
///
/// The arena-allocated, `Copy` version of an `ArcMultiAction` is a [`MultiAction`].
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = ArcMultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// let submissions = add_todo.submissions();
/// assert_eq!(submissions.with(Vec::len), 3);
/// # });
/// ```
pub struct ArcMultiAction<I, O> {
version: ArcRwSignal<usize>,
submissions: ArcRwSignal<Vec<ArcSubmission<I, O>>>,
#[allow(clippy::complexity)]
action_fn: Arc<
dyn Fn(&I) -> Pin<Box<dyn Future<Output = O> + Send>> + Send + Sync,
>,
}
impl<I, O> Debug for ArcMultiAction<I, O>
where
I: 'static,
O: 'static,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArcMultiAction")
.field("version", &self.version)
.field("submissions", &self.submissions)
.finish()
}
}
impl<I, O> Clone for ArcMultiAction<I, O>
where
I: 'static,
O: 'static,
{
fn clone(&self) -> Self {
Self {
version: self.version.clone(),
submissions: self.submissions.clone(),
action_fn: Arc::clone(&self.action_fn),
}
}
}
impl<I, O> ArcMultiAction<I, O> {
/// Creates a new multi-action.
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Submission::input] as well.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// // if there's a single argument, just use that
/// let action1 = ArcMultiAction::new(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = ArcMultiAction::new(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 =
/// ArcMultiAction::new(|input: &(usize, String)| async { todo!() });
/// # });
/// ```
#[track_caller]
pub fn new<Fut>(
action_fn: impl Fn(&I) -> Fut + Send + Sync + 'static,
) -> Self
where
Fut: Future<Output = O> + Send + 'static,
{
let action_fn = Arc::new(move |input: &I| {
let fut = action_fn(input);
Box::pin(fut) as Pin<Box<dyn Future<Output = O> + Send>>
});
Self {
version: ArcRwSignal::new(0),
submissions: ArcRwSignal::new(Vec::new()),
action_fn,
}
}
}
impl<I, O> ArcMultiAction<I, O>
where
I: Send + Sync + 'static,
O: Send + Sync + 'static,
{
/// Calls the `async` function with a reference to the input type as its argument.
///
/// This can be called any number of times: each submission will be dispatched, running
/// concurrently, and its status can be checked via the
/// [`submissions()`](MultiAction::submissions) signal.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = ArcMultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let submissions = add_todo.submissions();
/// let pending_submissions = {
/// let submissions = submissions.clone();
/// move || {
/// submissions.with(|subs| subs.iter().filter(|sub| sub.pending().get()).count())
/// }
/// };
///
/// add_todo.dispatch("Buy milk".to_string());
/// assert_eq!(submissions.with(Vec::len), 1);
/// assert_eq!(pending_submissions(), 1);
///
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(submissions.with(Vec::len), 3);
/// assert_eq!(pending_submissions(), 3);
///
/// // when submissions resolve, they are not removed from the set
/// // however, their `pending` signal is now `false`, and this can be used to filter them
/// # any_spawner::Executor::tick().await;
/// assert_eq!(submissions.with(Vec::len), 3);
/// assert_eq!(pending_submissions(), 0);
/// # });
/// ```
pub fn dispatch(&self, input: I) {
if !is_suppressing_resource_load() {
let fut = (self.action_fn)(&input);
let submission = ArcSubmission {
input: ArcRwSignal::new(Some(input)),
value: ArcRwSignal::new(None),
pending: ArcRwSignal::new(true),
canceled: ArcRwSignal::new(false),
};
self.submissions
.try_update(|subs| subs.push(submission.clone()));
let version = self.version.clone();
crate::spawn(async move {
let new_value = fut.await;
let canceled = submission.canceled.get_untracked();
if !canceled {
submission.value.try_set(Some(new_value));
}
submission.input.try_set(None);
submission.pending.try_set(false);
version.try_update(|n| *n += 1);
})
}
}
/// Synchronously adds a submission with the given value.
///
/// This takes the output value, rather than the input, because it is adding a result, not an
/// input.
///
/// This can be useful for use cases like handling errors, where the error can already be known
/// on the client side.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = ArcMultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let submissions = add_todo.submissions();
/// let pending_submissions = {
/// let submissions = submissions.clone();
/// move || {
/// submissions.with(|subs| subs.iter().filter(|sub| sub.pending().get()).count())
/// }
/// };
///
/// add_todo.dispatch("Buy milk".to_string());
/// assert_eq!(submissions.with(Vec::len), 1);
/// assert_eq!(pending_submissions(), 1);
///
/// add_todo.dispatch_sync(42);
///
/// assert_eq!(submissions.with(Vec::len), 2);
/// assert_eq!(pending_submissions(), 1);
/// # });
/// ```
pub fn dispatch_sync(&self, value: O) {
let submission = ArcSubmission {
input: ArcRwSignal::new(None),
value: ArcRwSignal::new(Some(value)),
pending: ArcRwSignal::new(false),
canceled: ArcRwSignal::new(false),
};
self.submissions
.try_update(|subs| subs.push(submission.clone()));
self.version.try_update(|n| *n += 1);
}
}
impl<I, O> ArcMultiAction<I, O> {
/// The set of all submissions to this multi-action.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = ArcMultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let submissions = add_todo.submissions();
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(submissions.with(Vec::len), 3);
/// # });
/// ```
pub fn submissions(&self) -> ArcReadSignal<Vec<ArcSubmission<I, O>>> {
self.submissions.read_only()
}
/// How many times an action has successfully resolved.
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let add_todo = ArcMultiAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// let version = add_todo.version();
///
/// add_todo.dispatch("Buy milk".to_string());
/// add_todo.dispatch("???".to_string());
/// add_todo.dispatch("Profit!!!".to_string());
///
/// assert_eq!(version.get(), 0);
/// # any_spawner::Executor::tick().await;
///
/// // when they've all resolved
/// assert_eq!(version.get(), 3);
/// # });
/// ```
pub fn version(&self) -> ArcRwSignal<usize> {
self.version.clone()
}
}
/// An action that has been submitted by dispatching it to a [`MultiAction`].
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct ArcSubmission<I, O> {
/// The current argument that was dispatched to the `async` function.
/// `Some` while we are waiting for it to resolve, `None` if it has resolved.
input: ArcRwSignal<Option<I>>,
/// The most recent return value of the `async` function.
value: ArcRwSignal<Option<O>>,
pending: ArcRwSignal<bool>,
/// Controls this submission has been canceled.
canceled: ArcRwSignal<bool>,
}
impl<I, O> ArcSubmission<I, O>
where
I: 'static,
O: 'static,
{
/// The current argument that was dispatched to the `async` function.
/// `Some` while we are waiting for it to resolve, `None` if it has resolved.
#[track_caller]
pub fn input(&self) -> ArcReadSignal<Option<I>> {
self.input.read_only()
}
/// The most recent return value of the `async` function.
#[track_caller]
pub fn value(&self) -> ArcReadSignal<Option<O>> {
self.value.read_only()
}
/// Whether this submision is still waiting to resolve.
#[track_caller]
pub fn pending(&self) -> ArcReadSignal<bool> {
self.pending.read_only()
}
/// Whether this submission has been canceled.
#[track_caller]
pub fn canceled(&self) -> ArcReadSignal<bool> {
self.canceled.read_only()
}
/// Cancels the submission. This will not necessarily prevent the `Future`
/// from continuing to run, but it will update the returned value.
#[track_caller]
pub fn cancel(&self) {
// TODO if we set these up to race against a cancel signal, we could actually drop the
// futures
self.canceled.try_set(true);
}
}
impl<I, O> Clone for ArcSubmission<I, O> {
fn clone(&self) -> Self {
Self {
input: self.input.clone(),
value: self.value.clone(),
pending: self.pending.clone(),
canceled: self.canceled.clone(),
}
}
}
/// An action that has been submitted by dispatching it to a [`MultiAction`].
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct Submission<I, O, S = SyncStorage>
where
I: 'static,
O: 'static,
{
/// The current argument that was dispatched to the `async` function.
/// `Some` while we are waiting for it to resolve, `None` if it has resolved.
input: RwSignal<Option<I>, S>,
/// The most recent return value of the `async` function.
value: RwSignal<Option<O>, S>,
pending: RwSignal<bool>,
/// Controls this submission has been canceled.
canceled: RwSignal<bool>,
}
impl<I, O> From<ArcSubmission<I, O>> for Submission<I, O>
where
I: Send + Sync + 'static,
O: Send + Sync + 'static,
{
fn from(value: ArcSubmission<I, O>) -> Self {
let ArcSubmission {
input,
value,
pending,
canceled,
} = value;
Self {
input: input.into(),
value: value.into(),
pending: pending.into(),
canceled: canceled.into(),
}
}
}
impl<I, O> FromLocal<ArcSubmission<I, O>> for Submission<I, O, LocalStorage>
where
I: 'static,
O: 'static,
{
fn from_local(value: ArcSubmission<I, O>) -> Self {
let ArcSubmission {
input,
value,
pending,
canceled,
} = value;
Self {
input: RwSignal::from_local(input),
value: RwSignal::from_local(value),
pending: pending.into(),
canceled: canceled.into(),
}
}
}
impl<I, O, S> Submission<I, O, S>
where
S: Storage<ArcRwSignal<Option<I>>> + Storage<ArcReadSignal<Option<I>>>,
{
/// The current argument that was dispatched to the `async` function.
/// `Some` while we are waiting for it to resolve, `None` if it has resolved.
#[track_caller]
pub fn input(&self) -> ReadSignal<Option<I>, S> {
self.input.read_only()
}
}
impl<I, O, S> Submission<I, O, S>
where
S: Storage<ArcRwSignal<Option<O>>> + Storage<ArcReadSignal<Option<O>>>,
{
/// The most recent return value of the `async` function.
#[track_caller]
pub fn value(&self) -> ReadSignal<Option<O>, S> {
self.value.read_only()
}
}
impl<I, O, S> Submission<I, O, S> {
/// Whether this submision is still waiting to resolve.
#[track_caller]
pub fn pending(&self) -> ReadSignal<bool> {
self.pending.read_only()
}
/// Whether this submission has been canceled.
#[track_caller]
pub fn canceled(&self) -> ReadSignal<bool> {
self.canceled.read_only()
}
/// Cancels the submission. This will not necessarily prevent the `Future`
/// from continuing to run, but it will update the returned value.
#[track_caller]
pub fn cancel(&self) {
self.canceled.try_set(true);
}
}
impl<I, O, S> Clone for Submission<I, O, S> {
fn clone(&self) -> Self {
*self
}
}
impl<I, O, S> Copy for Submission<I, O, S> {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/actions/mod.rs | reactive_graph/src/actions/mod.rs | //! Reactive primitives to asynchronously update some value.
mod action;
mod multi_action;
pub use action::*;
pub use multi_action::*;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/actions/action.rs | reactive_graph/src/actions/action.rs | use crate::{
computed::{ArcMemo, Memo, ScopedFuture},
diagnostics::is_suppressing_resource_load,
graph::untrack,
owner::{ArcStoredValue, ArenaItem, Owner},
send_wrapper_ext::SendOption,
signal::{ArcMappedSignal, ArcRwSignal, MappedSignal, RwSignal},
traits::{DefinedAt, Dispose, Get, GetUntracked, GetValue, Update, Write},
unwrap_signal,
};
use any_spawner::Executor;
use futures::{channel::oneshot, select, FutureExt};
use send_wrapper::SendWrapper;
use std::{
future::Future,
ops::{Deref, DerefMut},
panic::Location,
pin::Pin,
sync::Arc,
};
/// An action runs some asynchronous code when you dispatch a new value to it, and gives you
/// reactive access to the result.
///
/// Actions are intended for mutating or updating data, not for loading data. If you find yourself
/// creating an action and immediately dispatching a value to it, this is probably the wrong
/// primitive.
///
/// The arena-allocated, `Copy` version of an `ArcAction` is an [`Action`].
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let save_data = ArcAction::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// // the argument currently running
/// let input = save_data.input();
/// // the most recent returned result
/// let result_of_call = save_data.value();
/// // whether the call is pending
/// let pending = save_data.pending();
/// // how many times the action has run
/// // useful for reactively updating something else in response to a `dispatch` and response
/// let version = save_data.version();
///
/// // before we do anything
/// assert_eq!(input.get(), None); // no argument yet
/// assert_eq!(pending.get(), false); // isn't pending a response
/// assert_eq!(result_of_call.get(), None); // there's no "last value"
/// assert_eq!(version.get(), 0);
///
/// // dispatch the action
/// save_data.dispatch("My todo".to_string());
///
/// // when we're making the call
/// assert_eq!(input.get(), Some("My todo".to_string()));
/// assert_eq!(pending.get(), true); // is pending
/// assert_eq!(result_of_call.get(), None); // has not yet gotten a response
///
/// # any_spawner::Executor::tick().await;
///
/// // after call has resolved
/// assert_eq!(input.get(), None); // input clears out after resolved
/// assert_eq!(pending.get(), false); // no longer pending
/// assert_eq!(result_of_call.get(), Some(42));
/// assert_eq!(version.get(), 1);
/// # });
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Action::input] as well.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// // if there's a single argument, just use that
/// let action1 = ArcAction::new(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = ArcAction::new(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 = ArcAction::new(|input: &(usize, String)| async { todo!() });
/// ```
pub struct ArcAction<I, O> {
in_flight: ArcRwSignal<usize>,
input: ArcRwSignal<SendOption<I>>,
value: ArcRwSignal<SendOption<O>>,
version: ArcRwSignal<usize>,
dispatched: ArcStoredValue<usize>,
#[allow(clippy::complexity)]
action_fn: Arc<
dyn Fn(&I) -> Pin<Box<dyn Future<Output = O> + Send>> + Send + Sync,
>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<I, O> Clone for ArcAction<I, O> {
fn clone(&self) -> Self {
Self {
in_flight: self.in_flight.clone(),
input: self.input.clone(),
value: self.value.clone(),
version: self.version.clone(),
dispatched: self.dispatched.clone(),
action_fn: self.action_fn.clone(),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
}
}
}
impl<I, O> ArcAction<I, O>
where
I: 'static,
O: 'static,
{
/// Creates a new action. This is lazy: it does not run the action function until some value
/// is dispatched.
///
/// The constructor takes a function which will create a new `Future` from some input data.
/// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
/// be spawned.
///
/// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
/// `Future` must be `Send` so that it can be moved across threads by the async executor as
/// needed.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = ArcAction::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// act.dispatch(3);
/// assert_eq!(act.input().get(), Some(3));
///
/// // Remember that async functions already return a future if they are
/// // not `await`ed. You can save keystrokes by leaving out the `async move`
///
/// let act2 = Action::new(|n: &String| yell(n.to_owned()));
/// act2.dispatch(String::from("i'm in a doctest"));
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
///
/// // after it resolves
/// assert_eq!(act2.value().get(), Some("I'M IN A DOCTEST".to_string()));
///
/// async fn yell(n: String) -> String {
/// n.to_uppercase()
/// }
/// # });
/// ```
#[track_caller]
pub fn new<F, Fu>(action_fn: F) -> Self
where
F: Fn(&I) -> Fu + Send + Sync + 'static,
Fu: Future<Output = O> + Send + 'static,
I: Send + Sync,
O: Send + Sync,
{
Self::new_with_value(None, action_fn)
}
/// Creates a new action, initializing it with the given value.
///
/// This is lazy: it does not run the action function until some value is dispatched.
///
/// The constructor takes a function which will create a new `Future` from some input data.
/// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
/// be spawned.
///
/// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
/// `Future` must be `Send` so that it can be moved across threads by the async executor as
/// needed.
#[track_caller]
pub fn new_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
where
F: Fn(&I) -> Fu + Send + Sync + 'static,
Fu: Future<Output = O> + Send + 'static,
I: Send + Sync,
O: Send + Sync,
{
let owner = Owner::current().unwrap_or_default();
ArcAction {
in_flight: ArcRwSignal::new(0),
input: ArcRwSignal::new(SendOption::new(None)),
value: ArcRwSignal::new(SendOption::new(value)),
version: Default::default(),
dispatched: Default::default(),
action_fn: Arc::new(move |input| {
Box::pin(owner.with(|| {
ScopedFuture::new_untracked(untrack(|| action_fn(input)))
}))
}),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
/// Clears the value of the action, setting its current value to `None`.
///
/// This has no other effect: i.e., it will not cancel in-flight actions, set the
/// input, etc.
#[track_caller]
pub fn clear(&self) {
if let Some(mut guard) = self.value.try_write() {
**guard = None;
}
}
}
/// A handle that allows aborting an in-flight action. It is returned from [`Action::dispatch`] or
/// [`ArcAction::dispatch`].
#[derive(Debug)]
pub struct ActionAbortHandle(oneshot::Sender<()>);
impl ActionAbortHandle {
/// Aborts the action.
///
/// This will cause the dispatched task to complete, without updating the action's value. The
/// dispatched action's `Future` will no longer be polled. This does not guarantee that side
/// effects created by that `Future` no longer run: for example, if the action dispatches an
/// HTTP request, whether that request is actually canceled or not depends on whether the
/// request library actually cancels a request when its `Future` is dropped.
pub fn abort(self) {
let _ = self.0.send(());
}
}
impl<I, O> ArcAction<I, O>
where
I: Send + Sync + 'static,
O: Send + Sync + 'static,
{
/// Calls the `async` function with a reference to the input type as its argument.
#[track_caller]
pub fn dispatch(&self, input: I) -> ActionAbortHandle {
let (abort_tx, mut abort_rx) = oneshot::channel();
if !is_suppressing_resource_load() {
let mut fut = (self.action_fn)(&input).fuse();
// Update the state before loading
self.in_flight.update(|n| *n += 1);
let current_version = self.dispatched.get_value();
self.input.try_update(|inp| **inp = Some(input));
// Spawn the task
crate::spawn({
let input = self.input.clone();
let version = self.version.clone();
let dispatched = self.dispatched.clone();
let value = self.value.clone();
let in_flight = self.in_flight.clone();
async move {
select! {
// if the abort message has been sent, bail and do nothing
_ = abort_rx => {
in_flight.update(|n| *n = n.saturating_sub(1));
},
// otherwise, update the value
result = fut => {
in_flight.update(|n| *n = n.saturating_sub(1));
let is_latest = dispatched.get_value() <= current_version;
if is_latest {
version.update(|n| *n += 1);
value.update(|n| **n = Some(result));
}
}
}
if in_flight.get_untracked() == 0 {
input.update(|inp| **inp = None);
}
}
});
}
ActionAbortHandle(abort_tx)
}
}
impl<I, O> ArcAction<I, O>
where
I: 'static,
O: 'static,
{
/// Calls the `async` function with a reference to the input type as its argument,
/// ensuring that it is spawned on the current thread.
#[track_caller]
pub fn dispatch_local(&self, input: I) -> ActionAbortHandle {
let (abort_tx, mut abort_rx) = oneshot::channel();
if !is_suppressing_resource_load() {
let mut fut = (self.action_fn)(&input).fuse();
// Update the state before loading
self.in_flight.update(|n| *n += 1);
let current_version = self.dispatched.get_value();
self.input.try_update(|inp| **inp = Some(input));
// Spawn the task
Executor::spawn_local({
let input = self.input.clone();
let version = self.version.clone();
let value = self.value.clone();
let dispatched = self.dispatched.clone();
let in_flight = self.in_flight.clone();
async move {
select! {
// if the abort message has been sent, bail and do nothing
_ = abort_rx => {
in_flight.update(|n| *n = n.saturating_sub(1));
},
// otherwise, update the value
result = fut => {
in_flight.update(|n| *n = n.saturating_sub(1));
let is_latest = dispatched.get_value() <= current_version;
if is_latest {
version.update(|n| *n += 1);
value.update(|n| **n = Some(result));
}
}
}
if in_flight.get_untracked() == 0 {
input.update(|inp| **inp = None);
}
}
});
}
ActionAbortHandle(abort_tx)
}
}
impl<I, O> ArcAction<I, O>
where
I: 'static,
O: 'static,
{
/// Creates a new action, which will only be run on the thread in which it is created.
///
/// In all other ways, this is identical to [`ArcAction::new`].
#[track_caller]
pub fn new_unsync<F, Fu>(action_fn: F) -> Self
where
F: Fn(&I) -> Fu + 'static,
Fu: Future<Output = O> + 'static,
{
let action_fn = move |inp: &I| SendWrapper::new(action_fn(inp));
Self::new_unsync_with_value(None, action_fn)
}
/// Creates a new action that will only run on the current thread, initializing it with the given value.
///
/// In all other ways, this is identical to [`ArcAction::new_with_value`].
#[track_caller]
pub fn new_unsync_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
where
F: Fn(&I) -> Fu + 'static,
Fu: Future<Output = O> + 'static,
{
let owner = Owner::current().unwrap_or_default();
let action_fn = SendWrapper::new(action_fn);
ArcAction {
in_flight: ArcRwSignal::new(0),
input: ArcRwSignal::new(SendOption::new_local(None)),
value: ArcRwSignal::new(SendOption::new_local(value)),
version: Default::default(),
dispatched: Default::default(),
action_fn: Arc::new(move |input| {
Box::pin(SendWrapper::new(owner.with(|| {
ScopedFuture::new_untracked(untrack(|| action_fn(input)))
})))
}),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<I, O> ArcAction<I, O>
where
I: 'static,
O: 'static,
{
/// The number of times the action has successfully completed.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = ArcAction::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// let version = act.version();
/// act.dispatch(3);
/// assert_eq!(version.get(), 0);
///
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// // after it resolves
/// assert_eq!(version.get(), 1);
/// # });
/// ```
#[track_caller]
pub fn version(&self) -> ArcRwSignal<usize> {
self.version.clone()
}
/// The current argument that was dispatched to the async function. This value will
/// be `Some` while we are waiting for it to resolve, and `None` after it has resolved.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = ArcAction::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// let input = act.input();
/// assert_eq!(input.get(), None);
/// act.dispatch(3);
/// assert_eq!(input.get(), Some(3));
///
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// // after it resolves
/// assert_eq!(input.get(), None);
/// # });
/// ```
#[track_caller]
pub fn input(&self) -> ArcMappedSignal<Option<I>> {
ArcMappedSignal::new(
self.input.clone(),
|n| n.deref(),
|n| n.deref_mut(),
)
}
/// The most recent return value of the `async` function. This will be `None` before
/// the action has ever run successfully, and subsequently will always be `Some(_)`,
/// holding the old value until a new value has been received.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = ArcAction::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// let value = act.value();
/// assert_eq!(value.get(), None);
/// act.dispatch(3);
/// assert_eq!(value.get(), None);
///
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// // after it resolves
/// assert_eq!(value.get(), Some(6));
/// // dispatch another value, and it still holds the old value
/// act.dispatch(3);
/// assert_eq!(value.get(), Some(6));
/// # });
/// ```
#[track_caller]
pub fn value(&self) -> ArcMappedSignal<Option<O>> {
ArcMappedSignal::new(
self.value.clone(),
|n| n.deref(),
|n| n.deref_mut(),
)
}
/// Whether the action has been dispatched and is currently waiting to resolve.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = ArcAction::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// let pending = act.pending();
/// assert_eq!(pending.get(), false);
/// act.dispatch(3);
/// assert_eq!(pending.get(), true);
///
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// // after it resolves
/// assert_eq!(pending.get(), false);
/// # });
/// ```
#[track_caller]
pub fn pending(&self) -> ArcMemo<bool> {
let in_flight = self.in_flight.clone();
ArcMemo::new(move |_| in_flight.get() > 0)
}
}
impl<I, O> DefinedAt for ArcAction<I, O>
where
I: 'static,
O: 'static,
{
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
}
}
}
/// An action runs some asynchronous code when you dispatch a new value to it, and gives you
/// reactive access to the result.
///
/// Actions are intended for mutating or updating data, not for loading data. If you find yourself
/// creating an action and immediately dispatching a value to it, this is probably the wrong
/// primitive.
///
/// The reference-counted, `Clone` (but not `Copy` version of an `Action` is an [`ArcAction`].
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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();
/// async fn send_new_todo_to_api(task: String) -> usize {
/// // do something...
/// // return a task id
/// 42
/// }
/// let save_data = Action::new(|task: &String| {
/// // `task` is given as `&String` because its value is available in `input`
/// send_new_todo_to_api(task.clone())
/// });
///
/// // the argument currently running
/// let input = save_data.input();
/// // the most recent returned result
/// let result_of_call = save_data.value();
/// // whether the call is pending
/// let pending = save_data.pending();
/// // how many times the action has run
/// // useful for reactively updating something else in response to a `dispatch` and response
/// let version = save_data.version();
///
/// // before we do anything
/// assert_eq!(input.get(), None); // no argument yet
/// assert_eq!(pending.get(), false); // isn't pending a response
/// assert_eq!(result_of_call.get(), None); // there's no "last value"
/// assert_eq!(version.get(), 0);
///
/// // dispatch the action
/// save_data.dispatch("My todo".to_string());
///
/// // when we're making the call
/// assert_eq!(input.get(), Some("My todo".to_string()));
/// assert_eq!(pending.get(), true); // is pending
/// assert_eq!(result_of_call.get(), None); // has not yet gotten a response
///
/// # any_spawner::Executor::tick().await;
///
/// // after call has resolved
/// assert_eq!(input.get(), None); // input clears out after resolved
/// assert_eq!(pending.get(), false); // no longer pending
/// assert_eq!(result_of_call.get(), Some(42));
/// assert_eq!(version.get(), 1);
/// # });
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Action::input] as well.
///
/// ```rust
/// # use reactive_graph::actions::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// // if there's a single argument, just use that
/// let action1 = Action::new(|input: &String| {
/// let input = input.clone();
/// async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = Action::new(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 = Action::new(|input: &(usize, String)| async { todo!() });
/// ```
pub struct Action<I, O> {
inner: ArenaItem<ArcAction<I, O>>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<I, O> Dispose for Action<I, O> {
fn dispose(self) {
self.inner.dispose()
}
}
impl<I, O> Action<I, O>
where
I: Send + Sync + 'static,
O: Send + Sync + 'static,
{
/// Creates a new action. This is lazy: it does not run the action function until some value
/// is dispatched.
///
/// The constructor takes a function which will create a new `Future` from some input data.
/// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
/// be spawned.
///
/// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
/// `Future` must be `Send` so that it can be moved across threads by the async executor as
/// needed. In order to be stored in the `Copy` arena, the input and output types should also
/// be `Send + Sync`.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = Action::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// act.dispatch(3);
/// assert_eq!(act.input().get(), Some(3));
///
/// // Remember that async functions already return a future if they are
/// // not `await`ed. You can save keystrokes by leaving out the `async move`
///
/// let act2 = Action::new(|n: &String| yell(n.to_owned()));
/// act2.dispatch(String::from("i'm in a doctest"));
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
///
/// // after it resolves
/// assert_eq!(act2.value().get(), Some("I'M IN A DOCTEST".to_string()));
///
/// async fn yell(n: String) -> String {
/// n.to_uppercase()
/// }
/// # });
/// ```
#[track_caller]
pub fn new<F, Fu>(action_fn: F) -> Self
where
F: Fn(&I) -> Fu + Send + Sync + 'static,
Fu: Future<Output = O> + Send + 'static,
{
Self {
inner: ArenaItem::new(ArcAction::new(action_fn)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
/// Creates a new action, initializing it with the given value.
///
/// This is lazy: it does not run the action function until some value is dispatched.
///
/// The constructor takes a function which will create a new `Future` from some input data.
/// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
/// be spawned.
///
/// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
/// `Future` must be `Send` so that it can be moved across threads by the async executor as
/// needed. In order to be stored in the `Copy` arena, the input and output types should also
/// be `Send + Sync`.
#[track_caller]
pub fn new_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
where
F: Fn(&I) -> Fu + Send + Sync + 'static,
Fu: Future<Output = O> + Send + 'static,
{
Self {
inner: ArenaItem::new(ArcAction::new_with_value(value, action_fn)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<I, O> Action<I, O>
where
I: 'static,
O: 'static,
{
/// Clears the value of the action, setting its current value to `None`.
///
/// This has no other effect: i.e., it will not cancel in-flight actions, set the
/// input, etc.
#[track_caller]
pub fn clear(&self) {
self.inner.try_with_value(|inner| inner.clear());
}
}
impl<I, O> Action<I, O>
where
I: 'static,
O: 'static,
{
/// Creates a new action, which does not require its inputs or outputs to be `Send`. In all other
/// ways, this is the same as [`Action::new`]. If this action is accessed from outside the
/// thread on which it was created, it panics.
#[track_caller]
pub fn new_local<F, Fu>(action_fn: F) -> Self
where
F: Fn(&I) -> Fu + 'static,
Fu: Future<Output = O> + 'static,
{
Self {
inner: ArenaItem::new(ArcAction::new_unsync(action_fn)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
/// Creates a new action with the initial value, which does not require its inputs or outputs to be `Send`. In all other
/// ways, this is the same as [`Action::new_with_value`]. If this action is accessed from outside the
/// thread on which it was created, it panics.
#[track_caller]
pub fn new_local_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
where
F: Fn(&I) -> Fu + 'static,
Fu: Future<Output = O> + Send + 'static,
{
Self {
inner: ArenaItem::new(ArcAction::new_unsync_with_value(
value, action_fn,
)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<I, O> Action<I, O>
where
I: 'static,
O: 'static,
{
/// The number of times the action has successfully completed.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = Action::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// let version = act.version();
/// act.dispatch(3);
/// assert_eq!(version.get(), 0);
///
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// // after it resolves
/// assert_eq!(version.get(), 1);
/// # });
/// ```
#[track_caller]
pub fn version(&self) -> RwSignal<usize> {
let inner = self
.inner
.try_with_value(|inner| inner.version())
.unwrap_or_else(unwrap_signal!(self));
inner.into()
}
/// Whether the action has been dispatched and is currently waiting to resolve.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = Action::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// let pending = act.pending();
/// assert_eq!(pending.get(), false);
/// act.dispatch(3);
/// assert_eq!(pending.get(), true);
///
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// // after it resolves
/// assert_eq!(pending.get(), false);
/// # });
/// ```
#[track_caller]
pub fn pending(&self) -> Memo<bool> {
let inner = self
.inner
.try_with_value(|inner| inner.pending())
.unwrap_or_else(unwrap_signal!(self));
inner.into()
}
}
impl<I, O> Action<I, O>
where
I: 'static,
O: 'static,
{
/// The current argument that was dispatched to the async function. This value will
/// be `Some` while we are waiting for it to resolve, and `None` after it has resolved.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # 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 act = Action::new(|n: &u8| {
/// let n = n.to_owned();
/// async move { n * 2 }
/// });
///
/// let input = act.input();
/// assert_eq!(input.get(), None);
/// act.dispatch(3);
/// assert_eq!(input.get(), Some(3));
///
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
/// // after it resolves
/// assert_eq!(input.get(), None);
/// # });
/// ```
#[track_caller]
pub fn input(&self) -> MappedSignal<Option<I>> {
self.inner
.try_with_value(|inner| inner.input())
.unwrap_or_else(unwrap_signal!(self))
.into()
}
/// The current argument that was dispatched to the async function. This value will
/// be `Some` while we are waiting for it to resolve, and `None` after it has resolved.
///
/// Returns a thread-local signal using [`LocalStorage`].
#[track_caller]
#[deprecated = "You can now use .input() for any value, whether it's \
thread-safe or not."]
pub fn input_local(&self) -> MappedSignal<Option<I>> {
self.inner
.try_with_value(|inner| inner.input())
.unwrap_or_else(unwrap_signal!(self))
.into()
}
}
impl<I, O> Action<I, O>
where
I: 'static,
O: 'static,
{
/// The most recent return value of the `async` function. This will be `None` before
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/owner/arc_stored_value.rs | reactive_graph/src/owner/arc_stored_value.rs | use crate::{
signal::guards::{Plain, ReadGuard, UntrackedWriteGuard},
traits::{DefinedAt, IntoInner, IsDisposed, ReadValue, WriteValue},
};
use std::{
fmt::{Debug, Formatter},
hash::Hash,
panic::Location,
sync::{Arc, RwLock},
};
/// A reference-counted getter for any value non-reactively.
///
/// This is a reference-counted value, which is `Clone` but not `Copy`.
/// For arena-allocated `Copy` values, use [`StoredValue`](super::StoredValue).
///
/// This allows you to create a stable reference for any value by storing it within
/// the reactive system. Unlike e.g. [`ArcRwSignal`](crate::signal::ArcRwSignal), it is not reactive;
/// accessing it does not cause effects to subscribe, and
/// updating it does not notify anything else.
pub struct ArcStoredValue<T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
value: Arc<RwLock<T>>,
}
impl<T> Clone for ArcStoredValue<T> {
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
value: Arc::clone(&self.value),
}
}
}
impl<T> Debug for ArcStoredValue<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ArcStoredValue")
.field("type", &std::any::type_name::<T>())
.field("value", &Arc::as_ptr(&self.value))
.finish()
}
}
impl<T: Default> Default for ArcStoredValue<T> {
#[track_caller]
fn default() -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::new(RwLock::new(T::default())),
}
}
}
impl<T> PartialEq for ArcStoredValue<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.value, &other.value)
}
}
impl<T> Eq for ArcStoredValue<T> {}
impl<T> Hash for ArcStoredValue<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(&Arc::as_ptr(&self.value), state);
}
}
impl<T> DefinedAt for ArcStoredValue<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> ArcStoredValue<T> {
/// Creates a new stored value, 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 {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::new(RwLock::new(value)),
}
}
}
impl<T> ReadValue for ArcStoredValue<T>
where
T: 'static,
{
type Value = ReadGuard<T, Plain<T>>;
fn try_read_value(&self) -> Option<ReadGuard<T, Plain<T>>> {
Plain::try_new(Arc::clone(&self.value)).map(ReadGuard::new)
}
}
impl<T> WriteValue for ArcStoredValue<T>
where
T: 'static,
{
type Value = T;
fn try_write_value(&self) -> Option<UntrackedWriteGuard<T>> {
UntrackedWriteGuard::try_new(self.value.clone())
}
}
impl<T> IsDisposed for ArcStoredValue<T> {
fn is_disposed(&self) -> bool {
false
}
}
impl<T> IntoInner for ArcStoredValue<T> {
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
Some(Arc::into_inner(self.value)?.into_inner().unwrap())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/owner/arena.rs | reactive_graph/src/owner/arena.rs | use or_poisoned::OrPoisoned;
use slotmap::{new_key_type, SlotMap};
#[cfg(feature = "sandboxed-arenas")]
use std::cell::RefCell;
#[cfg(not(feature = "sandboxed-arenas"))]
use std::sync::OnceLock;
#[cfg(feature = "sandboxed-arenas")]
use std::sync::Weak;
use std::{
any::Any,
hash::Hash,
sync::{Arc, RwLock},
};
new_key_type! {
/// Unique identifier for an item stored in the arena.
pub struct NodeId;
}
pub struct Arena;
pub type ArenaMap = SlotMap<NodeId, Box<dyn Any + Send + Sync>>;
#[cfg(not(feature = "sandboxed-arenas"))]
static MAP: OnceLock<RwLock<ArenaMap>> = OnceLock::new();
#[cfg(feature = "sandboxed-arenas")]
thread_local! {
pub(crate) static MAP: RefCell<Option<Weak<RwLock<ArenaMap>>>> = RefCell::new(Some(Default::default()));
}
impl Arena {
#[inline(always)]
#[allow(unused)]
pub fn set(arena: &Arc<RwLock<ArenaMap>>) {
#[cfg(feature = "sandboxed-arenas")]
{
let new_arena = Arc::downgrade(arena);
MAP.with_borrow_mut(|arena| {
*arena = Some(new_arena);
})
}
}
#[track_caller]
pub fn with<U>(fun: impl FnOnce(&ArenaMap) -> U) -> U {
#[cfg(not(feature = "sandboxed-arenas"))]
{
fun(&MAP.get_or_init(Default::default).read().or_poisoned())
}
#[cfg(feature = "sandboxed-arenas")]
{
Arena::try_with(fun).unwrap_or_else(|| {
panic!(
"at {}, the `sandboxed-arenas` feature is active, but no \
Arena is active",
std::panic::Location::caller()
)
})
}
}
#[track_caller]
pub fn try_with<U>(fun: impl FnOnce(&ArenaMap) -> U) -> Option<U> {
#[cfg(not(feature = "sandboxed-arenas"))]
{
Some(fun(&MAP.get_or_init(Default::default).read().or_poisoned()))
}
#[cfg(feature = "sandboxed-arenas")]
{
MAP.with_borrow(|arena| {
arena
.as_ref()
.and_then(Weak::upgrade)
.map(|n| fun(&n.read().or_poisoned()))
})
}
}
#[track_caller]
pub fn with_mut<U>(fun: impl FnOnce(&mut ArenaMap) -> U) -> U {
#[cfg(not(feature = "sandboxed-arenas"))]
{
fun(&mut MAP.get_or_init(Default::default).write().or_poisoned())
}
#[cfg(feature = "sandboxed-arenas")]
{
Arena::try_with_mut(fun).unwrap_or_else(|| {
panic!(
"at {}, the `sandboxed-arenas` feature is active, but no \
Arena is active",
std::panic::Location::caller()
)
})
}
}
#[track_caller]
pub fn try_with_mut<U>(fun: impl FnOnce(&mut ArenaMap) -> U) -> Option<U> {
#[cfg(not(feature = "sandboxed-arenas"))]
{
Some(fun(&mut MAP
.get_or_init(Default::default)
.write()
.or_poisoned()))
}
#[cfg(feature = "sandboxed-arenas")]
{
MAP.with_borrow(|arena| {
arena
.as_ref()
.and_then(Weak::upgrade)
.map(|n| fun(&mut n.write().or_poisoned()))
})
}
}
}
#[cfg(feature = "sandboxed-arenas")]
pub mod sandboxed {
use super::{Arena, ArenaMap, MAP};
use futures::Stream;
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
sync::{Arc, RwLock, Weak},
task::{Context, Poll},
};
pin_project! {
/// A [`Future`] that restores its associated arena as the current arena whenever it is
/// polled.
///
/// Sandboxed arenas are used to ensure that data created in response to e.g., different
/// HTTP requests can be handled separately, while providing stable identifiers for their
/// stored values. Wrapping a `Future` in `Sandboxed` ensures that it will always use the
/// same arena that it was created under.
pub struct Sandboxed<T> {
arena: Option<Arc<RwLock<ArenaMap>>>,
#[pin]
inner: T,
}
}
impl<T> Sandboxed<T> {
/// Wraps the given [`Future`], ensuring that any [`ArenaItem`][item] created while it is
/// being polled will be associated with the same arena that was active when this was
/// called.
///
/// [item]:[crate::owner::ArenaItem]
#[track_caller]
pub fn new(inner: T) -> Self {
let arena = MAP.with_borrow(|n| n.as_ref().and_then(Weak::upgrade));
Self { arena, inner }
}
}
impl<Fut> Future for Sandboxed<Fut>
where
Fut: Future,
{
type Output = Fut::Output;
fn poll(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Self::Output> {
if let Some(arena) = self.arena.as_ref() {
Arena::set(arena);
}
let this = self.project();
this.inner.poll(cx)
}
}
impl<T> Stream for Sandboxed<T>
where
T: Stream,
{
type Item = T::Item;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
if let Some(arena) = self.arena.as_ref() {
Arena::set(arena);
}
let this = self.project();
this.inner.poll_next(cx)
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/owner/storage.rs | reactive_graph/src/owner/storage.rs | use super::arena::{Arena, NodeId};
use send_wrapper::SendWrapper;
/// A trait for borrowing and taking data.
pub trait StorageAccess<T> {
/// Borrows the value.
fn as_borrowed(&self) -> &T;
/// Takes the value.
fn into_taken(self) -> T;
}
impl<T> StorageAccess<T> for T {
fn as_borrowed(&self) -> &T {
self
}
fn into_taken(self) -> T {
self
}
}
impl<T> StorageAccess<T> for SendWrapper<T> {
fn as_borrowed(&self) -> &T {
self
}
fn into_taken(self) -> T {
self.take()
}
}
/// A way of storing an [`ArenaItem`](super::arena_item::ArenaItem), either as itself or with a wrapper to make it threadsafe.
///
/// This exists because all items stored in the arena must be `Send + Sync`, but in single-threaded
/// environments you might want or need to use thread-unsafe types.
pub trait Storage<T>: Send + Sync + 'static {
/// The type being stored, once it has been wrapped.
type Wrapped: StorageAccess<T> + Send + Sync + 'static;
/// Adds any needed wrapper to the type.
fn wrap(value: T) -> Self::Wrapped;
/// Applies the given function to the stored value, if it exists and can be accessed from this
/// thread.
fn try_with<U>(node: NodeId, fun: impl FnOnce(&T) -> U) -> Option<U>;
/// Applies the given function to a mutable reference to the stored value, if it exists and can be accessed from this
/// thread.
fn try_with_mut<U>(
node: NodeId,
fun: impl FnOnce(&mut T) -> U,
) -> Option<U>;
/// Sets a new value for the stored value. If it has been disposed, returns `Some(T)`.
fn try_set(node: NodeId, value: T) -> Option<T>;
/// Takes an item from the arena if it exists and can be accessed from this thread.
/// If it cannot be casted, it will still be removed from the arena.
fn take(node: NodeId) -> Option<T>;
}
/// A form of [`Storage`] that stores the type as itself, with no wrapper.
#[derive(Debug, Copy, Clone)]
pub struct SyncStorage;
impl<T> Storage<T> for SyncStorage
where
T: Send + Sync + 'static,
{
type Wrapped = T;
#[inline(always)]
fn wrap(value: T) -> Self::Wrapped {
value
}
fn try_with<U>(node: NodeId, fun: impl FnOnce(&T) -> U) -> Option<U> {
Arena::try_with(|arena| {
let m = arena.get(node);
m.and_then(|n| n.downcast_ref::<T>()).map(fun)
})
.flatten()
}
fn try_with_mut<U>(
node: NodeId,
fun: impl FnOnce(&mut T) -> U,
) -> Option<U> {
Arena::try_with_mut(|arena| {
let m = arena.get_mut(node);
m.and_then(|n| n.downcast_mut::<T>()).map(fun)
})
.flatten()
}
fn try_set(node: NodeId, value: T) -> Option<T> {
Arena::try_with_mut(|arena| {
let m = arena.get_mut(node);
match m.and_then(|n| n.downcast_mut::<T>()) {
Some(inner) => {
*inner = value;
None
}
None => Some(value),
}
})
.flatten()
}
fn take(node: NodeId) -> Option<T> {
Arena::with_mut(|arena| {
let m = arena.remove(node)?;
match m.downcast::<T>() {
Ok(inner) => Some(*inner),
Err(_) => None,
}
})
}
}
/// A form of [`Storage`] that stores the type with a wrapper that makes it `Send + Sync`, but only
/// allows it to be accessed from the thread on which it was created.
#[derive(Debug, Copy, Clone)]
pub struct LocalStorage;
impl<T> Storage<T> for LocalStorage
where
T: 'static,
{
type Wrapped = SendWrapper<T>;
fn wrap(value: T) -> Self::Wrapped {
SendWrapper::new(value)
}
fn try_with<U>(node: NodeId, fun: impl FnOnce(&T) -> U) -> Option<U> {
Arena::with(|arena| {
let m = arena.get(node);
m.and_then(|n| n.downcast_ref::<SendWrapper<T>>())
.map(|inner| fun(inner))
})
}
fn try_with_mut<U>(
node: NodeId,
fun: impl FnOnce(&mut T) -> U,
) -> Option<U> {
Arena::with_mut(|arena| {
let m = arena.get_mut(node);
m.and_then(|n| n.downcast_mut::<SendWrapper<T>>())
.map(|inner| fun(&mut *inner))
})
}
fn try_set(node: NodeId, value: T) -> Option<T> {
Arena::with_mut(|arena| {
let m = arena.get_mut(node);
match m.and_then(|n| n.downcast_mut::<SendWrapper<T>>()) {
Some(inner) => {
*inner = SendWrapper::new(value);
None
}
None => Some(value),
}
})
}
fn take(node: NodeId) -> Option<T> {
Arena::with_mut(|arena| {
let m = arena.remove(node)?;
match m.downcast::<SendWrapper<T>>() {
Ok(inner) => Some(inner.take()),
Err(_) => None,
}
})
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/owner/stored_value.rs | reactive_graph/src/owner/stored_value.rs | use super::{
arc_stored_value::ArcStoredValue, ArenaItem, LocalStorage, Storage,
SyncStorage,
};
use crate::{
signal::guards::{Plain, ReadGuard, UntrackedWriteGuard},
traits::{
DefinedAt, Dispose, IntoInner, IsDisposed, ReadValue, WriteValue,
},
unwrap_signal,
};
use std::{
fmt::{Debug, Formatter},
hash::Hash,
panic::Location,
};
/// A **non-reactive**, `Copy` handle for any value.
///
/// This allows you to create a stable reference for any value by storing it within
/// the reactive system. Like the signal types (e.g., [`ReadSignal`](crate::signal::ReadSignal)
/// and [`RwSignal`](crate::signal::RwSignal)), it is `Copy` and `'static`. Unlike the signal
/// types, it is not reactive; accessing it does not cause effects to subscribe, and
/// updating it does not notify anything else.
pub struct StoredValue<T, S = SyncStorage> {
value: ArenaItem<ArcStoredValue<T>, S>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<T, S> Copy for StoredValue<T, S> {}
impl<T, S> Clone for StoredValue<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Debug for StoredValue<T, S>
where
S: Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("StoredValue")
.field("type", &std::any::type_name::<T>())
.field("value", &self.value)
.finish()
}
}
impl<T, S> PartialEq for StoredValue<T, S> {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl<T, S> Eq for StoredValue<T, S> {}
impl<T, S> Hash for StoredValue<T, S> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.value.hash(state);
}
}
impl<T, S> DefinedAt for StoredValue<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, S> StoredValue<T, S>
where
T: 'static,
S: Storage<ArcStoredValue<T>>,
{
/// Stores the given value in the arena allocator.
#[track_caller]
pub fn new_with_storage(value: T) -> Self {
Self {
value: ArenaItem::new_with_storage(ArcStoredValue::new(value)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
}
}
}
impl<T, S> Default for StoredValue<T, S>
where
T: Default + 'static,
S: Storage<ArcStoredValue<T>>,
{
#[track_caller] // Default trait is not annotated with #[track_caller]
fn default() -> Self {
Self::new_with_storage(Default::default())
}
}
impl<T> StoredValue<T>
where
T: Send + Sync + 'static,
{
/// Stores the given value in the arena allocator.
#[track_caller]
pub fn new(value: T) -> Self {
StoredValue::new_with_storage(value)
}
}
impl<T> StoredValue<T, LocalStorage>
where
T: 'static,
{
/// Stores the given value in the arena allocator.
#[track_caller]
pub fn new_local(value: T) -> Self {
StoredValue::new_with_storage(value)
}
}
impl<T, S> ReadValue for StoredValue<T, S>
where
T: 'static,
S: Storage<ArcStoredValue<T>>,
{
type Value = ReadGuard<T, Plain<T>>;
fn try_read_value(&self) -> Option<ReadGuard<T, Plain<T>>> {
self.value
.try_get_value()
.and_then(|inner| inner.try_read_value())
}
}
impl<T, S> WriteValue for StoredValue<T, S>
where
T: 'static,
S: Storage<ArcStoredValue<T>>,
{
type Value = T;
fn try_write_value(&self) -> Option<UntrackedWriteGuard<T>> {
self.value
.try_get_value()
.and_then(|inner| inner.try_write_value())
}
}
impl<T, S> IsDisposed for StoredValue<T, S> {
fn is_disposed(&self) -> bool {
self.value.is_disposed()
}
}
impl<T, S> Dispose for StoredValue<T, S> {
fn dispose(self) {
self.value.dispose();
}
}
impl<T, S> IntoInner for StoredValue<T, S>
where
T: 'static,
S: Storage<ArcStoredValue<T>>,
{
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
self.value.into_inner()?.into_inner()
}
}
impl<T> From<ArcStoredValue<T>> for StoredValue<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcStoredValue<T>) -> Self {
StoredValue {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: ArenaItem::new(value),
}
}
}
impl<T, S> From<StoredValue<T, S>> for ArcStoredValue<T>
where
S: Storage<ArcStoredValue<T>>,
{
#[track_caller]
fn from(value: StoredValue<T, S>) -> Self {
value
.value
.try_get_value()
.unwrap_or_else(unwrap_signal!(value))
}
}
/// Creates a new [`StoredValue`].
#[inline(always)]
#[track_caller]
#[deprecated(
since = "0.7.0-beta5",
note = "This function is being removed to conform to Rust idioms. Please \
use `StoredValue::new()` or `StoredValue::new_local()` instead."
)]
pub fn store_value<T>(value: T) -> StoredValue<T>
where
T: Send + Sync + 'static,
{
StoredValue::new(value)
}
/// Converts some value into a locally-stored type, using [`LocalStorage`].
///
/// This is modeled on [`From`] but special-cased for this thread-local storage method, which
/// allows for better type inference for the default case.
pub trait FromLocal<T> {
/// Converts between the types.
fn from_local(value: T) -> Self;
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/owner/arena_item.rs | reactive_graph/src/owner/arena_item.rs | use super::{
arena::{Arena, NodeId},
LocalStorage, Storage, SyncStorage, OWNER,
};
use crate::traits::{Dispose, IntoInner, IsDisposed};
use send_wrapper::SendWrapper;
use std::{any::Any, hash::Hash, marker::PhantomData};
/// A copyable, stable reference for any value, stored on the arena whose ownership is managed by the
/// reactive ownership tree.
#[derive(Debug)]
pub struct ArenaItem<T, S = SyncStorage> {
node: NodeId,
#[allow(clippy::type_complexity)]
ty: PhantomData<fn() -> (SendWrapper<T>, S)>,
}
impl<T, S> Copy for ArenaItem<T, S> {}
impl<T, S> Clone for ArenaItem<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> PartialEq for ArenaItem<T, S> {
fn eq(&self, other: &Self) -> bool {
self.node == other.node
}
}
impl<T, S> Eq for ArenaItem<T, S> {}
impl<T, S> Hash for ArenaItem<T, S> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.node.hash(state);
}
}
impl<T, S> ArenaItem<T, S>
where
T: 'static,
S: Storage<T>,
{
/// Stores the given value in the arena allocator.
#[track_caller]
pub fn new_with_storage(value: T) -> Self {
let node = {
Arena::with_mut(|arena| {
arena.insert(
Box::new(S::wrap(value)) as Box<dyn Any + Send + Sync>
)
})
};
OWNER.with(|o| {
if let Some(owner) = o.borrow().as_ref().and_then(|o| o.upgrade()) {
owner.register(node);
}
});
Self {
node,
ty: PhantomData,
}
}
}
impl<T, S> Default for ArenaItem<T, S>
where
T: Default + 'static,
S: Storage<T>,
{
#[track_caller] // Default trait is not annotated with #[track_caller]
fn default() -> Self {
Self::new_with_storage(Default::default())
}
}
impl<T> ArenaItem<T>
where
T: Send + Sync + 'static,
{
/// Stores the given value in the arena allocator.
#[track_caller]
pub fn new(value: T) -> Self {
ArenaItem::new_with_storage(value)
}
}
impl<T> ArenaItem<T, LocalStorage>
where
T: 'static,
{
/// Stores the given value in the arena allocator.
#[track_caller]
pub fn new_local(value: T) -> Self {
ArenaItem::new_with_storage(value)
}
}
impl<T, S: Storage<T>> ArenaItem<T, S> {
/// Applies a function to a reference to the stored value and returns the result, or `None` if it has already been disposed.
#[track_caller]
pub fn try_with_value<U>(&self, fun: impl FnOnce(&T) -> U) -> Option<U> {
S::try_with(self.node, fun)
}
/// Applies a function to a mutable reference to the stored value and returns the result, or `None` if it has already been disposed.
#[track_caller]
pub fn try_update_value<U>(
&self,
fun: impl FnOnce(&mut T) -> U,
) -> Option<U> {
S::try_with_mut(self.node, fun)
}
}
impl<T: Clone, S: Storage<T>> ArenaItem<T, S> {
/// Returns a clone of the stored value, or `None` if it has already been disposed.
#[track_caller]
pub fn try_get_value(&self) -> Option<T> {
S::try_with(self.node, Clone::clone)
}
}
impl<T, S> IsDisposed for ArenaItem<T, S> {
fn is_disposed(&self) -> bool {
Arena::with(|arena| !arena.contains_key(self.node))
}
}
impl<T, S> Dispose for ArenaItem<T, S> {
fn dispose(self) {
Arena::with_mut(|arena| arena.remove(self.node));
}
}
impl<T, S: Storage<T>> IntoInner for ArenaItem<T, S> {
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
S::take(self.node)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_graph/src/owner/context.rs | reactive_graph/src/owner/context.rs | use crate::owner::Owner;
use or_poisoned::OrPoisoned;
use std::{
any::{Any, TypeId},
collections::VecDeque,
};
impl Owner {
fn provide_context<T: Send + Sync + 'static>(&self, value: T) {
self.inner
.write()
.or_poisoned()
.contexts
.insert(value.type_id(), Box::new(value));
}
fn use_context<T: Clone + 'static>(&self) -> Option<T> {
self.with_context(Clone::clone)
}
fn take_context<T: 'static>(&self) -> Option<T> {
let ty = TypeId::of::<T>();
let mut inner = self.inner.write().or_poisoned();
let contexts = &mut inner.contexts;
if let Some(context) = contexts.remove(&ty) {
context.downcast::<T>().ok().map(|n| *n)
} else {
let mut parent = inner.parent.as_ref().and_then(|p| p.upgrade());
while let Some(ref this_parent) = parent.clone() {
let mut this_parent = this_parent.write().or_poisoned();
let contexts = &mut this_parent.contexts;
let value = contexts.remove(&ty);
let downcast =
value.and_then(|context| context.downcast::<T>().ok());
if let Some(value) = downcast {
return Some(*value);
} else {
parent =
this_parent.parent.as_ref().and_then(|p| p.upgrade());
}
}
None
}
}
fn with_context<T: 'static, R>(
&self,
cb: impl FnOnce(&T) -> R,
) -> Option<R> {
let ty = TypeId::of::<T>();
let inner = self.inner.read().or_poisoned();
let contexts = &inner.contexts;
let reference = if let Some(context) = contexts.get(&ty) {
context.downcast_ref::<T>()
} else {
let mut parent = inner.parent.as_ref().and_then(|p| p.upgrade());
while let Some(ref this_parent) = parent.clone() {
let this_parent = this_parent.read().or_poisoned();
let contexts = &this_parent.contexts;
let value = contexts.get(&ty);
let downcast =
value.and_then(|context| context.downcast_ref::<T>());
if let Some(value) = downcast {
return Some(cb(value));
} else {
parent =
this_parent.parent.as_ref().and_then(|p| p.upgrade());
}
}
None
};
reference.map(cb)
}
fn update_context<T: 'static, R>(
&self,
cb: impl FnOnce(&mut T) -> R,
) -> Option<R> {
let ty = TypeId::of::<T>();
let mut inner = self.inner.write().or_poisoned();
let contexts = &mut inner.contexts;
let reference = if let Some(context) = contexts.get_mut(&ty) {
context.downcast_mut::<T>()
} else {
let mut parent = inner.parent.as_ref().and_then(|p| p.upgrade());
while let Some(ref this_parent) = parent.clone() {
let mut this_parent = this_parent.write().or_poisoned();
let contexts = &mut this_parent.contexts;
let value = contexts.get_mut(&ty);
let downcast =
value.and_then(|context| context.downcast_mut::<T>());
if let Some(value) = downcast {
return Some(cb(value));
} else {
parent =
this_parent.parent.as_ref().and_then(|p| p.upgrade());
}
}
None
};
reference.map(cb)
}
/// Searches for items stored in context in either direction, either among parents or among
/// descendants.
pub fn use_context_bidirectional<T: Clone + 'static>(&self) -> Option<T> {
self.use_context()
.unwrap_or_else(|| self.find_context_in_children())
}
fn find_context_in_children<T: Clone + 'static>(&self) -> Option<T> {
let ty = TypeId::of::<T>();
let inner = self.inner.read().or_poisoned();
let mut to_search = VecDeque::new();
to_search.extend(inner.children.clone());
drop(inner);
while let Some(next) = to_search.pop_front() {
if let Some(child) = next.upgrade() {
let child = child.read().or_poisoned();
let contexts = &child.contexts;
if let Some(context) = contexts.get(&ty) {
return context.downcast_ref::<T>().cloned();
}
to_search.extend(child.children.clone());
}
}
None
}
}
/// Provides a context value of type `T` to the current reactive [`Owner`]
/// and all of its descendants. This can be accessed using [`use_context`].
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
/// arguments to a function or properties of a component.
///
/// Context works similarly to variable scope: a context that is provided higher in
/// the reactive graph can be used lower down, but a context that is provided lower
/// down cannot be used higher up.
///
/// ```rust
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::owner::*;
/// # let owner = Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # futures::executor::block_on(async move {
/// # any_spawner::Executor::init_futures_executor();
/// Effect::new(move |_| {
/// println!("Provider");
/// provide_context(42i32); // provide an i32
///
/// Effect::new(move |_| {
/// println!("intermediate node");
///
/// Effect::new(move |_| {
/// let value = use_context::<i32>()
/// .expect("could not find i32 in context");
/// assert_eq!(value, 42);
/// });
/// });
/// });
/// # });
/// ```
///
/// ## Context Shadowing
///
/// Only a single value of any type can be provided via context. If you need to provide multiple
/// values of the same type, wrap each one in a "newtype" struct wrapper so that each one is a
/// distinct type.
///
/// Providing a second value of the same type "lower" in the ownership tree will shadow the value,
/// just as a second `let` declaration with the same variable name will shadow that variable.
///
/// ```rust
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::owner::*;
/// # let owner = Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # futures::executor::block_on(async move {
/// # any_spawner::Executor::init_futures_executor();
/// Effect::new(move |_| {
/// println!("Provider");
/// provide_context("foo"); // provide a &'static str
///
/// Effect::new(move |_| {
/// // before we provide another value of the same type, we can access the old one
/// assert_eq!(use_context::<&'static str>(), Some("foo"));
/// // but providing another value of the same type shadows it
/// provide_context("bar");
///
/// Effect::new(move |_| {
/// assert_eq!(use_context::<&'static str>(), Some("bar"));
/// });
/// });
/// });
/// # });
/// ```
pub fn provide_context<T: Send + Sync + 'static>(value: T) {
if let Some(owner) = Owner::current() {
owner.provide_context(value);
}
}
/// Extracts a context value of type `T` from the reactive system.
///
/// This traverses the reactive ownership graph, beginning from the current reactive
/// [`Owner`] and iterating through its parents, if any. When the value is found, it is cloned.
///
/// The context value should have been provided elsewhere using
/// [`provide_context`](provide_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
/// arguments to a function or properties of a component.
///
/// Context works similarly to variable scope: a context that is provided higher in
/// the reactive graph can be used lower down, but a context that is provided lower
/// in the tree cannot be used higher up.
///
/// While the term “consume” is sometimes used, note that [`use_context`] clones the value, rather
/// than removing it; it is still accessible to other users.
///
/// ```rust
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::owner::*;
/// # let owner = Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # futures::executor::block_on(async move {
/// # any_spawner::Executor::init_futures_executor();
/// Effect::new(move |_| {
/// provide_context(String::from("foo"));
///
/// Effect::new(move |_| {
/// // each use_context clones the value
/// let value = use_context::<String>()
/// .expect("could not find String in context");
/// assert_eq!(value, "foo");
/// let value2 = use_context::<String>()
/// .expect("could not find String in context");
/// assert_eq!(value2, "foo");
/// });
/// });
/// # });
/// ```
pub fn use_context<T: Clone + 'static>() -> Option<T> {
Owner::current().and_then(|owner| owner.use_context())
}
/// Extracts a context value of type `T` from the reactive system, and
/// panics if it can't be found.
///
/// This traverses the reactive ownership graph, beginning from the current reactive
/// [`Owner`] and iterating through its parents, if any. When the value is found, it is cloned.
///
/// Panics if no value is found.
///
/// The context value should have been provided elsewhere using
/// [`provide_context`](provide_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
/// arguments to a function or properties of a component.
///
/// Context works similarly to variable scope: a context that is provided higher in
/// the reactive graph can be used lower down, but a context that is provided lower
/// in the tree cannot be used higher up.
///
/// While the term “consume” is sometimes used, note that [`use_context`] clones the value, rather
/// than removing it; it is still accessible to other users.
///
/// ```rust
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::owner::*;
/// # let owner = Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # futures::executor::block_on(async move {
/// # any_spawner::Executor::init_futures_executor();
/// Effect::new(move |_| {
/// provide_context(String::from("foo"));
///
/// Effect::new(move |_| {
/// // each use_context clones the value
/// let value = use_context::<String>()
/// .expect("could not find String in context");
/// assert_eq!(value, "foo");
/// let value2 = use_context::<String>()
/// .expect("could not find String in context");
/// assert_eq!(value2, "foo");
/// });
/// });
/// # });
/// ```
/// ## Panics
/// Panics if a context of this type is not found in the current reactive
/// owner or its ancestors.
#[track_caller]
pub fn expect_context<T: Clone + 'static>() -> T {
let location = std::panic::Location::caller();
use_context().unwrap_or_else(|| {
panic!(
"{:?} expected context of type {:?} to be present",
location,
std::any::type_name::<T>()
)
})
}
/// Extracts a context value of type `T` from the reactive system, and takes ownership,
/// removing it from the context system.
///
/// This traverses the reactive ownership graph, beginning from the current reactive
/// [`Owner`] and iterating through its parents, if any. When the value is found, it is removed,
/// and is not available to any other [`use_context`] or [`take_context`] calls.
///
/// If the value is `Clone`, use [`use_context`] instead.
///
/// The context value should have been provided elsewhere using
/// [`provide_context`](provide_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
/// arguments to a function or properties of a component.
///
/// Context works similarly to variable scope: a context that is provided higher in
/// the reactive graph can be used lower down, but a context that is provided lower
/// in the tree cannot be used higher up.
/// ```rust
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::owner::*;
/// # let owner = Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # futures::executor::block_on(async move {
/// # any_spawner::Executor::init_futures_executor();
///
/// #[derive(Debug, PartialEq)]
/// struct NotClone(String);
///
/// Effect::new(move |_| {
/// provide_context(NotClone(String::from("foo")));
///
/// Effect::new(move |_| {
/// // take_context removes the value from context without needing to clone
/// let value = take_context::<NotClone>();
/// assert_eq!(value, Some(NotClone(String::from("foo"))));
/// let value2 = take_context::<NotClone>();
/// assert_eq!(value2, None);
/// });
/// });
/// # });
/// ```
pub fn take_context<T: 'static>() -> Option<T> {
Owner::current().and_then(|owner| owner.take_context())
}
/// Access a reference to a context value of type `T` in the reactive system.
///
/// This traverses the reactive ownership graph, beginning from the current reactive
/// [`Owner`] and iterating through its parents, if any. When the value is found,
/// the function that you pass is applied to an immutable reference to it.
///
/// The context value should have been provided elsewhere using
/// [`provide_context`](provide_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
/// arguments to a function or properties of a component.
///
/// Context works similarly to variable scope: a context that is provided higher in
/// the reactive graph can be used lower down, but a context that is provided lower
/// in the tree cannot be used higher up.
///
/// ```rust
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::owner::*;
/// # let owner = Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # futures::executor::block_on(async move {
/// # any_spawner::Executor::init_futures_executor();
/// Effect::new(move |_| {
/// provide_context(String::from("foo"));
///
/// Effect::new(move |_| {
/// let value = with_context::<String, _>(|val| val.to_string())
/// .expect("could not find String in context");
/// assert_eq!(value, "foo");
/// });
/// });
/// # });
/// ```
pub fn with_context<T: 'static, R>(cb: impl FnOnce(&T) -> R) -> Option<R> {
Owner::current().and_then(|owner| owner.with_context(cb))
}
/// Update a context value of type `T` in the reactive system.
///
/// This traverses the reactive ownership graph, beginning from the current reactive
/// [`Owner`] and iterating through its parents, if any. When the value is found,
/// the function that you pass is applied to a mutable reference to it.
///
/// The context value should have been provided elsewhere using
/// [`provide_context`](provide_context).
///
/// This is useful for passing values down to components or functions lower in a
/// hierarchy without needs to “prop drill” by passing them through each layer as
/// arguments to a function or properties of a component.
///
/// Context works similarly to variable scope: a context that is provided higher in
/// the reactive graph can be used lower down, but a context that is provided lower
/// in the tree cannot be used higher up.
///
/// ```rust
/// # use reactive_graph::prelude::*;
/// # use reactive_graph::owner::*;
/// # let owner = Owner::new(); owner.set();
/// # use reactive_graph::effect::Effect;
/// # futures::executor::block_on(async move {
/// # any_spawner::Executor::init_futures_executor();
/// Effect::new(move |_| {
/// provide_context(String::from("foo"));
///
/// Effect::new(move |_| {
/// let value = update_context::<String, _>(|val| {
/// std::mem::replace(val, "bar".to_string())
/// })
/// .expect("could not find String in context");
/// assert_eq!(value, "foo");
/// assert_eq!(expect_context::<String>(), "bar");
/// });
/// });
/// # });
/// ```
pub fn update_context<T: 'static, R>(
cb: impl FnOnce(&mut T) -> R,
) -> Option<R> {
Owner::current().and_then(|owner| owner.update_context(cb))
}
| 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/subscriber_traits.rs | reactive_graph/src/signal/subscriber_traits.rs | //! Traits to reduce the boilerplate when implementing the [`ReactiveNode`], [`Source`], and
//! [`ToAnySource`] traits for signal types.
//!
//! These traits can be automatically derived for any type that
//! 1) is a root node in the reactive graph, with no sources (i.e., a signal, not a memo)
//! 2) contains an `Arc<RwLock<SubscriberSet>>`
//!
//! This makes it easy to implement a variety of different signal primitives, as long as they share
//! these characteristics.
use crate::{
graph::{
AnySource, AnySubscriber, ReactiveNode, Source, SubscriberSet,
ToAnySource,
},
traits::{DefinedAt, IsDisposed},
unwrap_signal,
};
use or_poisoned::OrPoisoned;
use std::{
borrow::Borrow,
sync::{Arc, RwLock, Weak},
};
pub(crate) trait AsSubscriberSet {
type Output: Borrow<RwLock<SubscriberSet>>;
fn as_subscriber_set(&self) -> Option<Self::Output>;
}
impl<'a> AsSubscriberSet for &'a RwLock<SubscriberSet> {
type Output = &'a RwLock<SubscriberSet>;
#[inline(always)]
fn as_subscriber_set(&self) -> Option<Self::Output> {
Some(self)
}
}
impl DefinedAt for RwLock<SubscriberSet> {
fn defined_at(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
}
// Implement reactive types for RwLock<SubscriberSet>
// This is used so that Weak<RwLock<SubscriberSet>> is a Weak<dyn ReactiveNode> and Weak<dyn
// Source>
impl<T: AsSubscriberSet + DefinedAt> ReactiveNode for T {
fn mark_dirty(&self) {
self.mark_subscribers_check();
}
fn mark_check(&self) {}
fn mark_subscribers_check(&self) {
if let Some(inner) = self.as_subscriber_set() {
let subs = inner.borrow().read().unwrap().clone();
for sub in subs {
sub.mark_dirty();
}
}
}
fn update_if_necessary(&self) -> bool {
// a signal will always mark its dependents Dirty when it runs, so they know
// that they may have changed and need to check themselves at least
//
// however, it's always possible that *another* signal or memo has triggered any
// given effect/memo, and so this signal should *not* say that it is dirty, as it
// may also be checked but has not changed
false
}
}
impl<T: AsSubscriberSet + DefinedAt> Source for T {
fn clear_subscribers(&self) {
if let Some(inner) = self.as_subscriber_set() {
inner.borrow().write().unwrap().take();
}
}
fn add_subscriber(&self, subscriber: AnySubscriber) {
if let Some(inner) = self.as_subscriber_set() {
inner.borrow().write().unwrap().subscribe(subscriber)
}
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
if let Some(inner) = self.as_subscriber_set() {
inner.borrow().write().unwrap().unsubscribe(subscriber)
}
}
}
impl<T: AsSubscriberSet + DefinedAt + IsDisposed> ToAnySource for T
where
T::Output: Borrow<Arc<RwLock<SubscriberSet>>>,
{
#[track_caller]
fn to_any_source(&self) -> AnySource {
self.as_subscriber_set()
.map(|subs| {
let subs = subs.borrow();
AnySource(
Arc::as_ptr(subs) as usize,
Arc::downgrade(subs) as Weak<dyn Source + Send + Sync>,
#[cfg(any(debug_assertions, leptos_debuginfo))]
self.defined_at().expect("no DefinedAt in debug mode"),
)
})
.unwrap_or_else(unwrap_signal!(self))
}
}
impl ReactiveNode for RwLock<SubscriberSet> {
fn mark_dirty(&self) {
self.mark_subscribers_check();
}
fn mark_check(&self) {}
fn mark_subscribers_check(&self) {
let subs = self.write().unwrap().take();
for sub in subs {
sub.mark_dirty();
}
}
fn update_if_necessary(&self) -> bool {
// a signal will always mark its dependents Dirty when it runs, so they know
// that they may have changed and need to check themselves at least
//
// however, it's always possible that *another* signal or memo has triggered any
// given effect/memo, and so this signal should *not* say that it is dirty, as it
// may also be checked but has not changed
false
}
}
impl Source for RwLock<SubscriberSet> {
fn clear_subscribers(&self) {
self.write().or_poisoned().take();
}
fn add_subscriber(&self, subscriber: AnySubscriber) {
self.write().or_poisoned().subscribe(subscriber)
}
fn remove_subscriber(&self, subscriber: &AnySubscriber) {
self.write().or_poisoned().unsubscribe(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/signal/trigger.rs | reactive_graph/src/signal/trigger.rs | use super::{subscriber_traits::AsSubscriberSet, ArcTrigger};
use crate::{
graph::{ReactiveNode, SubscriberSet},
owner::ArenaItem,
traits::{DefinedAt, Dispose, IsDisposed, Notify},
};
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.
///
/// This is an arena-allocated Trigger, which is `Copy` and is disposed when its reactive
/// [`Owner`](crate::owner::Owner) cleans up. For a reference-counted trigger that lives
/// as long as a reference to it is alive, see [`ArcTrigger`].
pub struct Trigger {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) inner: ArenaItem<ArcTrigger>,
}
impl Trigger {
/// Creates a new trigger.
#[track_caller]
pub fn new() -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new(ArcTrigger::new()),
}
}
}
impl Default for Trigger {
fn default() -> Self {
Self::new()
}
}
impl Clone for Trigger {
#[track_caller]
fn clone(&self) -> Self {
*self
}
}
impl Copy for Trigger {}
impl Debug for Trigger {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("Trigger").finish()
}
}
impl Dispose for Trigger {
fn dispose(self) {
self.inner.dispose()
}
}
impl IsDisposed for Trigger {
#[inline(always)]
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl AsSubscriberSet for Trigger {
type Output = Arc<RwLock<SubscriberSet>>;
#[inline(always)]
fn as_subscriber_set(&self) -> Option<Self::Output> {
self.inner
.try_get_value()
.and_then(|arc_trigger| arc_trigger.as_subscriber_set())
}
}
impl DefinedAt for Trigger {
#[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 Trigger {
fn notify(&self) {
if let Some(inner) = self.inner.try_get_value() {
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/guards.rs | reactive_graph/src/signal/guards.rs | //! Guards that integrate with the reactive system, wrapping references to the values of signals.
use crate::{
computed::BlockingLock,
traits::{Notify, UntrackableGuard},
};
use core::fmt::Debug;
use guardian::{ArcRwLockReadGuardian, ArcRwLockWriteGuardian};
use std::{
borrow::Borrow,
fmt::Display,
marker::PhantomData,
ops::{Deref, DerefMut},
sync::{Arc, RwLock},
};
/// A wrapper type for any kind of guard returned by [`Read`](crate::traits::Read).
///
/// If `Inner` implements `Deref`, so does `ReadGuard<_, Inner>`.
#[derive(Debug)]
pub struct ReadGuard<T, Inner> {
ty: PhantomData<T>,
inner: Inner,
}
impl<T, Inner> ReadGuard<T, Inner> {
/// Creates a new wrapper around another guard type.
pub fn new(inner: Inner) -> Self {
Self {
inner,
ty: PhantomData,
}
}
/// Returns the inner guard type.
pub fn into_inner(self) -> Inner {
self.inner
}
}
impl<T, Inner> Clone for ReadGuard<T, Inner>
where
Inner: Clone,
{
fn clone(&self) -> Self {
Self {
ty: self.ty,
inner: self.inner.clone(),
}
}
}
impl<T, Inner> Deref for ReadGuard<T, Inner>
where
Inner: Deref<Target = T>,
{
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner.deref()
}
}
impl<T, Inner> Borrow<T> for ReadGuard<T, Inner>
where
Inner: Deref<Target = T>,
{
fn borrow(&self) -> &T {
self.deref()
}
}
impl<T, Inner> PartialEq<T> for ReadGuard<T, Inner>
where
Inner: Deref<Target = T>,
T: PartialEq,
{
fn eq(&self, other: &Inner::Target) -> bool {
self.deref() == other
}
}
impl<T, Inner> Display for ReadGuard<T, Inner>
where
Inner: Deref<Target = T>,
T: Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
/// A guard that provides access to a signal's inner value.
pub struct Plain<T: 'static> {
guard: ArcRwLockReadGuardian<T>,
}
impl<T: 'static> Debug for Plain<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Plain").finish()
}
}
impl<T: 'static> Plain<T> {
/// Takes a reference-counted read guard on the given lock.
pub fn try_new(inner: Arc<RwLock<T>>) -> Option<Self> {
ArcRwLockReadGuardian::try_take(inner)?
.ok()
.map(|guard| Plain { guard })
}
}
impl<T> Deref for Plain<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.guard.deref()
}
}
impl<T: PartialEq> PartialEq for Plain<T> {
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl<T: PartialEq> PartialEq<T> for Plain<T> {
fn eq(&self, other: &T) -> bool {
**self == *other
}
}
impl<T: Display> Display for Plain<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
/// A guard that provides access to an async signal's value.
pub struct AsyncPlain<T: 'static> {
pub(crate) guard: async_lock::RwLockReadGuardArc<T>,
}
impl<T: 'static> Debug for AsyncPlain<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AsyncPlain").finish()
}
}
impl<T: 'static> AsyncPlain<T> {
/// Takes a reference-counted async read guard on the given lock.
pub fn try_new(inner: &Arc<async_lock::RwLock<T>>) -> Option<Self> {
Some(Self {
guard: inner.blocking_read_arc(),
})
}
}
impl<T> Deref for AsyncPlain<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.guard.deref()
}
}
impl<T: PartialEq> PartialEq for AsyncPlain<T> {
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl<T: PartialEq> PartialEq<T> for AsyncPlain<T> {
fn eq(&self, other: &T) -> bool {
**self == *other
}
}
impl<T: Display> Display for AsyncPlain<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
/// A guard that maps over another guard.
#[derive(Debug)]
pub struct Mapped<Inner, U>
where
Inner: Deref,
{
inner: Inner,
map_fn: fn(&Inner::Target) -> &U,
}
impl<T: 'static, U> Mapped<Plain<T>, U> {
/// Creates a mapped read guard from the inner lock.
pub fn try_new(
inner: Arc<RwLock<T>>,
map_fn: fn(&T) -> &U,
) -> Option<Self> {
let inner = Plain::try_new(inner)?;
Some(Self { inner, map_fn })
}
}
impl<Inner, U> Mapped<Inner, U>
where
Inner: Deref,
{
/// Creates a mapped read guard from the inner guard.
pub fn new_with_guard(
inner: Inner,
map_fn: fn(&Inner::Target) -> &U,
) -> Self {
Self { inner, map_fn }
}
}
impl<Inner, U> Deref for Mapped<Inner, U>
where
Inner: Deref,
{
type Target = U;
fn deref(&self) -> &Self::Target {
(self.map_fn)(self.inner.deref())
}
}
impl<Inner, U: PartialEq> PartialEq for Mapped<Inner, U>
where
Inner: Deref,
{
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl<Inner, U: PartialEq> PartialEq<U> for Mapped<Inner, U>
where
Inner: Deref,
{
fn eq(&self, other: &U) -> bool {
**self == *other
}
}
impl<Inner, U: Display> Display for Mapped<Inner, U>
where
Inner: Deref,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
/// A guard that provides mutable access to a signal's value, triggering some reactive change
/// when it is dropped.
#[derive(Debug)]
pub struct WriteGuard<S, G>
where
S: Notify,
{
pub(crate) triggerable: Option<S>,
pub(crate) guard: Option<G>,
}
impl<S, G> WriteGuard<S, G>
where
S: Notify,
{
/// Creates a new guard from the inner mutable guard type, and the signal that should be
/// triggered on drop.
pub fn new(triggerable: S, guard: G) -> Self {
Self {
triggerable: Some(triggerable),
guard: Some(guard),
}
}
}
impl<S, G> UntrackableGuard for WriteGuard<S, G>
where
S: Notify,
G: DerefMut,
{
/// Removes the triggerable type, so that it is no longer notifies when dropped.
fn untrack(&mut self) {
self.triggerable.take();
}
}
impl<S, G> Deref for WriteGuard<S, G>
where
S: Notify,
G: Deref,
{
type Target = G::Target;
fn deref(&self) -> &Self::Target {
self.guard
.as_ref()
.expect(
"the guard should always be in place until the Drop \
implementation",
)
.deref()
}
}
impl<S, G> DerefMut for WriteGuard<S, G>
where
S: Notify,
G: DerefMut,
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.guard
.as_mut()
.expect(
"the guard should always be in place until the Drop \
implementation",
)
.deref_mut()
}
}
/// A guard that provides mutable access to a signal's inner value, but does not notify of any
/// changes.
pub struct UntrackedWriteGuard<T: 'static>(ArcRwLockWriteGuardian<T>);
impl<T: 'static> UntrackedWriteGuard<T> {
/// Creates a write guard from the given lock.
pub fn try_new(inner: Arc<RwLock<T>>) -> Option<Self> {
ArcRwLockWriteGuardian::try_take(inner)?
.ok()
.map(UntrackedWriteGuard)
}
}
impl<T> Deref for UntrackedWriteGuard<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl<T> DerefMut for UntrackedWriteGuard<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.deref_mut()
}
}
// Dropping the write guard will notify dependencies.
impl<S, T> Drop for WriteGuard<S, T>
where
S: Notify,
{
fn drop(&mut self) {
// first, drop the inner guard
drop(self.guard.take());
// then, notify about a change
if let Some(triggerable) = self.triggerable.as_ref() {
triggerable.notify();
}
}
}
/// A mutable guard that maps over an inner mutable guard.
#[derive(Debug)]
pub struct MappedMut<Inner, U>
where
Inner: Deref,
{
inner: Inner,
map_fn: fn(&Inner::Target) -> &U,
map_fn_mut: fn(&mut Inner::Target) -> &mut U,
}
impl<Inner, U> UntrackableGuard for MappedMut<Inner, U>
where
Inner: UntrackableGuard,
{
fn untrack(&mut self) {
self.inner.untrack();
}
}
impl<Inner, U> MappedMut<Inner, U>
where
Inner: DerefMut,
{
/// Creates a new writable guard from the inner guard.
pub fn new(
inner: Inner,
map_fn: fn(&Inner::Target) -> &U,
map_fn_mut: fn(&mut Inner::Target) -> &mut U,
) -> Self {
Self {
inner,
map_fn,
map_fn_mut,
}
}
}
impl<Inner, U> Deref for MappedMut<Inner, U>
where
Inner: Deref,
{
type Target = U;
fn deref(&self) -> &Self::Target {
(self.map_fn)(self.inner.deref())
}
}
impl<Inner, U> DerefMut for MappedMut<Inner, U>
where
Inner: DerefMut,
{
fn deref_mut(&mut self) -> &mut Self::Target {
(self.map_fn_mut)(self.inner.deref_mut())
}
}
impl<Inner, U: PartialEq> PartialEq for MappedMut<Inner, U>
where
Inner: Deref,
{
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl<Inner, U: Display> Display for MappedMut<Inner, U>
where
Inner: Deref,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
/// A mapped read guard in which the mapping function is a closure. If the mapping function is a
/// function pointer, use [`Mapped`].
pub struct MappedArc<Inner, U>
where
Inner: Deref,
{
inner: Inner,
#[allow(clippy::type_complexity)]
map_fn: Arc<dyn Fn(&Inner::Target) -> &U>,
}
impl<Inner, U> Clone for MappedArc<Inner, U>
where
Inner: Clone + Deref,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
map_fn: self.map_fn.clone(),
}
}
}
impl<Inner, U> Debug for MappedArc<Inner, U>
where
Inner: Debug + Deref,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MappedArc")
.field("inner", &self.inner)
.finish_non_exhaustive()
}
}
impl<Inner, U> MappedArc<Inner, U>
where
Inner: Deref,
{
/// Creates a new mapped guard from the inner guard and the map function.
pub fn new(
inner: Inner,
map_fn: impl Fn(&Inner::Target) -> &U + 'static,
) -> Self {
Self {
inner,
map_fn: Arc::new(map_fn),
}
}
}
impl<Inner, U> Deref for MappedArc<Inner, U>
where
Inner: Deref,
{
type Target = U;
fn deref(&self) -> &Self::Target {
(self.map_fn)(self.inner.deref())
}
}
impl<Inner, U: PartialEq> PartialEq for MappedArc<Inner, U>
where
Inner: Deref,
{
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl<Inner, U: Display> Display for MappedArc<Inner, U>
where
Inner: Deref,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
/// A mapped write guard in which the mapping function is a closure. If the mapping function is a
/// function pointer, use [`MappedMut`].
pub struct MappedMutArc<Inner, U>
where
Inner: Deref,
{
inner: Inner,
#[allow(clippy::type_complexity)]
map_fn: Arc<dyn Fn(&Inner::Target) -> &U>,
#[allow(clippy::type_complexity)]
map_fn_mut: Arc<dyn Fn(&mut Inner::Target) -> &mut U>,
}
impl<Inner, U> Clone for MappedMutArc<Inner, U>
where
Inner: Clone + Deref,
{
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
map_fn: self.map_fn.clone(),
map_fn_mut: self.map_fn_mut.clone(),
}
}
}
impl<Inner, U> Debug for MappedMutArc<Inner, U>
where
Inner: Debug + Deref,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MappedMutArc")
.field("inner", &self.inner)
.finish_non_exhaustive()
}
}
impl<Inner, U> UntrackableGuard for MappedMutArc<Inner, U>
where
Inner: UntrackableGuard,
{
fn untrack(&mut self) {
self.inner.untrack();
}
}
impl<Inner, U> MappedMutArc<Inner, U>
where
Inner: Deref,
{
/// Creates the new mapped mutable guard from the inner guard and mapping functions.
pub fn new(
inner: Inner,
map_fn: impl Fn(&Inner::Target) -> &U + 'static,
map_fn_mut: impl Fn(&mut Inner::Target) -> &mut U + 'static,
) -> Self {
Self {
inner,
map_fn: Arc::new(map_fn),
map_fn_mut: Arc::new(map_fn_mut),
}
}
}
impl<Inner, U> Deref for MappedMutArc<Inner, U>
where
Inner: Deref,
{
type Target = U;
fn deref(&self) -> &Self::Target {
(self.map_fn)(self.inner.deref())
}
}
impl<Inner, U> DerefMut for MappedMutArc<Inner, U>
where
Inner: DerefMut,
{
fn deref_mut(&mut self) -> &mut Self::Target {
(self.map_fn_mut)(self.inner.deref_mut())
}
}
impl<Inner, U: PartialEq> PartialEq for MappedMutArc<Inner, U>
where
Inner: Deref,
{
fn eq(&self, other: &Self) -> bool {
**self == **other
}
}
impl<Inner, U: Display> Display for MappedMutArc<Inner, U>
where
Inner: Deref,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
/// A wrapper that implements [`Deref`] and [`Borrow`] for itself.
pub struct Derefable<T>(pub T);
impl<T> Clone for Derefable<T>
where
T: Clone,
{
fn clone(&self) -> Self {
Derefable(self.0.clone())
}
}
impl<T> std::ops::Deref for Derefable<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> Borrow<T> for Derefable<T> {
fn borrow(&self) -> &T {
self.deref()
}
}
impl<T> PartialEq<T> for Derefable<T>
where
T: PartialEq,
{
fn eq(&self, other: &T) -> bool {
self.deref() == other
}
}
impl<T> Display for Derefable<T>
where
T: Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
| 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/write.rs | reactive_graph/src/signal/write.rs | use super::{guards::WriteGuard, ArcWriteSignal};
use crate::{
owner::{ArenaItem, FromLocal, LocalStorage, Storage, SyncStorage},
traits::{
DefinedAt, Dispose, IntoInner, IsDisposed, Notify, UntrackableGuard,
Write,
},
};
use core::fmt::Debug;
use guardian::ArcRwLockWriteGuardian;
use std::{hash::Hash, ops::DerefMut, panic::Location, sync::Arc};
/// An arena-allocated setter for a reactive signal.
///
/// A signal is a piece of data that may change over time,
/// and notifies other code when it has changed.
///
/// 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 [`ArcWriteSignal`].
///
/// ## Core Trait Implementations
/// - [`.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, use [`ArenaItem`] instead.
///
/// ## Examples
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let (count, set_count) = signal(0);
///
/// // ✅ calling the setter sets the value
/// // `set_count(1)` on nightly
/// set_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
/// set_count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count.get(), 2);
///
/// // ✅ `.write()` returns a guard that implements `DerefMut` and will notify when dropped
/// *set_count.write() += 1;
/// assert_eq!(count.get(), 3);
/// ```
pub struct WriteSignal<T, S = SyncStorage> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) inner: ArenaItem<ArcWriteSignal<T>, S>,
}
impl<T, S> Dispose for WriteSignal<T, S> {
fn dispose(self) {
self.inner.dispose()
}
}
impl<T, S> Copy for WriteSignal<T, S> {}
impl<T, S> Clone for WriteSignal<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Debug for WriteSignal<T, S>
where
S: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WriteSignal")
.field("type", &std::any::type_name::<T>())
.field("store", &self.inner)
.finish()
}
}
impl<T, S> PartialEq for WriteSignal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, S> Eq for WriteSignal<T, S> {}
impl<T, S> Hash for WriteSignal<T, S> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.hash(state);
}
}
impl<T, S> DefinedAt for WriteSignal<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> From<ArcWriteSignal<T>> for WriteSignal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcWriteSignal<T>) -> Self {
WriteSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T> FromLocal<ArcWriteSignal<T>> for WriteSignal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from_local(value: ArcWriteSignal<T>) -> Self {
WriteSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T, S> IsDisposed for WriteSignal<T, S> {
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<T, S> IntoInner for WriteSignal<T, S>
where
S: Storage<ArcWriteSignal<T>>,
{
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
self.inner.into_inner()?.into_inner()
}
}
impl<T, S> Notify for WriteSignal<T, S>
where
T: 'static,
S: Storage<ArcWriteSignal<T>>,
{
fn notify(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.notify();
}
}
}
impl<T, S> Write for WriteSignal<T, S>
where
T: 'static,
S: Storage<ArcWriteSignal<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))
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.inner
.try_with_value(|n| n.try_write_untracked())
.flatten()
}
}
| 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/mapped.rs | reactive_graph/src/signal/mapped.rs | use super::{
guards::{Mapped, MappedMutArc},
ArcRwSignal, RwSignal,
};
use crate::{
owner::{StoredValue, SyncStorage},
signal::guards::WriteGuard,
traits::{
DefinedAt, GetValue, IsDisposed, Notify, ReadUntracked, Track,
UntrackableGuard, Write,
},
};
use guardian::ArcRwLockWriteGuardian;
use std::{
fmt::Debug,
ops::{Deref, DerefMut},
panic::Location,
sync::Arc,
};
/// A derived signal type that wraps an [`ArcRwSignal`] with a mapping function,
/// allowing you to read or write directly to one of its field.
///
/// Tracking the mapped signal tracks changes to *any* part of the signal, and updating the signal notifies
/// and notifies *all* dependencies of the signal. This is not a mechanism for fine-grained reactive updates
/// to more complex data structures. Instead, it allows you to provide a signal-like API for wrapped types
/// without exposing the original type directly to users.
pub struct ArcMappedSignal<T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
#[allow(clippy::type_complexity)]
try_read_untracked: Arc<
dyn Fn() -> Option<DoubleDeref<Box<dyn Deref<Target = T>>>>
+ Send
+ Sync,
>,
try_write: Arc<
dyn Fn() -> Option<Box<dyn UntrackableGuard<Target = T>>> + Send + Sync,
>,
notify: Arc<dyn Fn() + Send + Sync>,
track: Arc<dyn Fn() + Send + Sync>,
}
impl<T> Clone for ArcMappedSignal<T> {
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
try_read_untracked: self.try_read_untracked.clone(),
try_write: self.try_write.clone(),
notify: self.notify.clone(),
track: self.track.clone(),
}
}
}
impl<T> ArcMappedSignal<T> {
/// Wraps a signal with the given mapping functions for shared and exclusive references.
#[track_caller]
pub fn new<U>(
inner: ArcRwSignal<U>,
map: fn(&U) -> &T,
map_mut: fn(&mut U) -> &mut T,
) -> Self
where
T: 'static,
U: Send + Sync + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
try_read_untracked: {
let this = inner.clone();
Arc::new(move || {
this.try_read_untracked().map(|guard| DoubleDeref {
inner: Box::new(Mapped::new_with_guard(guard, map))
as Box<dyn Deref<Target = T>>,
})
})
},
try_write: {
let this = inner.clone();
Arc::new(move || {
let guard = ArcRwLockWriteGuardian::try_take(Arc::clone(
&this.value,
))?
.ok()?;
let mapped = WriteGuard::new(
this.clone(),
MappedMutArc::new(guard, map, map_mut),
);
Some(Box::new(mapped))
})
},
notify: {
let this = inner.clone();
Arc::new(move || {
this.notify();
})
},
track: {
Arc::new(move || {
inner.track();
})
},
}
}
}
impl<T> Debug for ArcMappedSignal<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut partial = f.debug_struct("ArcMappedSignal");
#[cfg(any(debug_assertions, leptos_debuginfo))]
partial.field("defined_at", &self.defined_at);
partial.finish()
}
}
impl<T> DefinedAt for ArcMappedSignal<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> Notify for ArcMappedSignal<T> {
fn notify(&self) {
(self.notify)()
}
}
impl<T> Track for ArcMappedSignal<T> {
fn track(&self) {
(self.track)()
}
}
impl<T> ReadUntracked for ArcMappedSignal<T> {
type Value = DoubleDeref<Box<dyn Deref<Target = T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
(self.try_read_untracked)()
}
}
impl<T> IsDisposed for ArcMappedSignal<T> {
fn is_disposed(&self) -> bool {
false
}
}
impl<T> Write for ArcMappedSignal<T>
where
T: 'static,
{
type Value = T;
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
let mut guard = self.try_write()?;
guard.untrack();
Some(guard)
}
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
let inner = (self.try_write)()?;
let inner = DoubleDeref { inner };
Some(inner)
}
}
/// A wrapper for a smart pointer that implements [`Deref`] and [`DerefMut`]
/// by dereferencing the type *inside* the smart pointer.
///
/// This is quite obscure and mostly useful for situations in which we want
/// a wrapper for `Box<dyn Deref<Target = T>>` that dereferences to `T` rather
/// than dereferencing to `dyn Deref<Target = T>`.
///
/// This is used internally in [`MappedSignal`] and [`ArcMappedSignal`].
pub struct DoubleDeref<T> {
inner: T,
}
impl<T> Deref for DoubleDeref<T>
where
T: Deref,
T::Target: Deref,
{
type Target = <T::Target as Deref>::Target;
fn deref(&self) -> &Self::Target {
self.inner.deref().deref()
}
}
impl<T> DerefMut for DoubleDeref<T>
where
T: DerefMut,
T::Target: DerefMut,
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.inner.deref_mut().deref_mut()
}
}
impl<T> UntrackableGuard for DoubleDeref<T>
where
T: UntrackableGuard,
T::Target: DerefMut,
{
fn untrack(&mut self) {
self.inner.untrack();
}
}
/// A derived signal type that wraps an [`RwSignal`] with a mapping function,
/// allowing you to read or write directly to one of its field.
///
/// Tracking the mapped signal tracks changes to *any* part of the signal, and updating the signal notifies
/// and notifies *all* dependencies of the signal. This is not a mechanism for fine-grained reactive updates
/// to more complex data structures. Instead, it allows you to provide a signal-like API for wrapped types
/// without exposing the original type directly to users.
pub struct MappedSignal<T, S = SyncStorage> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: StoredValue<ArcMappedSignal<T>, S>,
}
impl<T> MappedSignal<T> {
/// Wraps a signal with the given mapping functions for shared and exclusive references.
#[track_caller]
pub fn new<U>(
inner: RwSignal<U>,
map: fn(&U) -> &T,
map_mut: fn(&mut U) -> &mut T,
) -> Self
where
T: Send + Sync + 'static,
U: Send + Sync + 'static,
{
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: {
let this = ArcRwSignal::from(inner);
StoredValue::new_with_storage(ArcMappedSignal::new(
this, map, map_mut,
))
},
}
}
}
impl<T> Copy for MappedSignal<T> {}
impl<T> Clone for MappedSignal<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Debug for MappedSignal<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut partial = f.debug_struct("MappedSignal");
#[cfg(any(debug_assertions, leptos_debuginfo))]
partial.field("defined_at", &self.defined_at);
partial.finish()
}
}
impl<T> DefinedAt for MappedSignal<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> Notify for MappedSignal<T>
where
T: 'static,
{
fn notify(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.notify();
}
}
}
impl<T> Track for MappedSignal<T>
where
T: 'static,
{
fn track(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.track();
}
}
}
impl<T> ReadUntracked for MappedSignal<T>
where
T: 'static,
{
type Value = DoubleDeref<Box<dyn Deref<Target = T>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.inner
.try_get_value()
.and_then(|inner| inner.try_read_untracked())
}
}
impl<T> Write for MappedSignal<T>
where
T: 'static,
{
type Value = T;
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
let mut guard = self.try_write()?;
guard.untrack();
Some(guard)
}
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
let inner = self.inner.try_get_value()?;
let inner = (inner.try_write)()?;
let inner = DoubleDeref { inner };
Some(inner)
}
}
impl<T> From<ArcMappedSignal<T>> for MappedSignal<T>
where
T: 'static,
{
#[track_caller]
fn from(value: ArcMappedSignal<T>) -> Self {
MappedSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: StoredValue::new(value),
}
}
}
impl<T> IsDisposed for MappedSignal<T> {
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
| 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/arc_rw.rs | reactive_graph/src/signal/arc_rw.rs | use super::{
guards::{Plain, ReadGuard, UntrackedWriteGuard, WriteGuard},
subscriber_traits::AsSubscriberSet,
ArcReadSignal, ArcWriteSignal,
};
use crate::{
graph::{ReactiveNode, SubscriberSet},
prelude::{IsDisposed, Notify},
traits::{DefinedAt, IntoInner, ReadUntracked, UntrackableGuard, Write},
};
use core::fmt::{Debug, Formatter, Result};
use std::{
hash::Hash,
panic::Location,
sync::{Arc, RwLock},
};
/// A reference-counted 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 a reference-counted signal, which is `Clone` but not `Copy`.
/// For arena-allocated `Copy` signals, use [`RwSignal`](super::RwSignal).
///
/// ## 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`](crate::owner::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 ArcRwSignal<T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) value: Arc<RwLock<T>>,
pub(crate) inner: Arc<RwLock<SubscriberSet>>,
}
impl<T> Clone for ArcRwSignal<T> {
#[track_caller]
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
value: Arc::clone(&self.value),
inner: Arc::clone(&self.inner),
}
}
}
impl<T> Debug for ArcRwSignal<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("ArcRwSignal")
.field("type", &std::any::type_name::<T>())
.field("value", &Arc::as_ptr(&self.value))
.finish()
}
}
impl<T> PartialEq for ArcRwSignal<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.value, &other.value)
}
}
impl<T> Eq for ArcRwSignal<T> {}
impl<T> Hash for ArcRwSignal<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(&Arc::as_ptr(&self.value), state);
}
}
impl<T> Default for ArcRwSignal<T>
where
T: Default,
{
#[track_caller]
fn default() -> Self {
Self::new(T::default())
}
}
impl<T> ArcRwSignal<T> {
/// 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 {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::new(RwLock::new(value)),
inner: Arc::new(RwLock::new(SubscriberSet::new())),
}
}
/// Returns a read-only handle to the signal.
#[track_caller]
pub fn read_only(&self) -> ArcReadSignal<T> {
ArcReadSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::clone(&self.value),
inner: Arc::clone(&self.inner),
}
}
/// Returns a write-only handle to the signal.
#[track_caller]
pub fn write_only(&self) -> ArcWriteSignal<T> {
ArcWriteSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::clone(&self.value),
inner: Arc::clone(&self.inner),
}
}
/// Splits the signal into its readable and writable halves.
#[track_caller]
pub fn split(&self) -> (ArcReadSignal<T>, ArcWriteSignal<T>) {
(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: ArcReadSignal<T>,
write: ArcWriteSignal<T>,
) -> Option<Self> {
if Arc::ptr_eq(&read.inner, &write.inner) {
Some(Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: read.value,
inner: read.inner,
})
} else {
None
}
}
}
impl<T> DefinedAt for ArcRwSignal<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> IsDisposed for ArcRwSignal<T> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T> IntoInner for ArcRwSignal<T> {
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
Some(Arc::into_inner(self.value)?.into_inner().unwrap())
}
}
impl<T> AsSubscriberSet for ArcRwSignal<T> {
type Output = Arc<RwLock<SubscriberSet>>;
#[inline(always)]
fn as_subscriber_set(&self) -> Option<Self::Output> {
Some(Arc::clone(&self.inner))
}
}
impl<T: 'static> ReadUntracked for ArcRwSignal<T> {
type Value = ReadGuard<T, Plain<T>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
Plain::try_new(Arc::clone(&self.value)).map(ReadGuard::new)
}
}
impl<T> Notify for ArcRwSignal<T> {
fn notify(&self) {
self.mark_dirty();
}
}
impl<T: 'static> Write for ArcRwSignal<T> {
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.value
.write()
.ok()
.map(|guard| WriteGuard::new(self.clone(), guard))
}
#[allow(refining_impl_trait)]
fn try_write_untracked(&self) -> Option<UntrackedWriteGuard<Self::Value>> {
UntrackedWriteGuard::try_new(Arc::clone(&self.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/signal/arc_write.rs | reactive_graph/src/signal/arc_write.rs | use super::guards::{UntrackedWriteGuard, WriteGuard};
use crate::{
graph::{ReactiveNode, SubscriberSet},
prelude::{IsDisposed, Notify},
traits::{DefinedAt, IntoInner, UntrackableGuard, Write},
};
use core::fmt::{Debug, Formatter, Result};
use std::{
hash::Hash,
panic::Location,
sync::{Arc, RwLock},
};
/// A reference-counted setter for a reactive signal.
///
/// A signal is a piece of data that may change over time,
/// and notifies other code when it has changed.
///
/// This is a reference-counted signal, which is `Clone` but not `Copy`.
/// For arena-allocated `Copy` signals, use [`WriteSignal`](super::WriteSignal).
///
/// ## Core Trait Implementations
/// - [`.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`](crate::owner::ArenaItem)
/// > instead.
///
/// ## Examples
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::signal::*;
/// let (count, set_count) = arc_signal(0);
///
/// // ✅ calling the setter sets the value
/// // `set_count(1)` on nightly
/// set_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
/// set_count.update(|count: &mut i32| *count += 1);
/// assert_eq!(count.get(), 2);
///
/// // ✅ `.write()` returns a guard that implements `DerefMut` and will notify when dropped
/// *set_count.write() += 1;
/// assert_eq!(count.get(), 3);
/// ```
pub struct ArcWriteSignal<T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) value: Arc<RwLock<T>>,
pub(crate) inner: Arc<RwLock<SubscriberSet>>,
}
impl<T> Clone for ArcWriteSignal<T> {
#[track_caller]
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
value: Arc::clone(&self.value),
inner: Arc::clone(&self.inner),
}
}
}
impl<T> Debug for ArcWriteSignal<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("ArcWriteSignal")
.field("type", &std::any::type_name::<T>())
.field("value", &Arc::as_ptr(&self.value))
.finish()
}
}
impl<T> PartialEq for ArcWriteSignal<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.value, &other.value)
}
}
impl<T> Eq for ArcWriteSignal<T> {}
impl<T> Hash for ArcWriteSignal<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(&Arc::as_ptr(&self.value), state);
}
}
impl<T> DefinedAt for ArcWriteSignal<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> IsDisposed for ArcWriteSignal<T> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T> IntoInner for ArcWriteSignal<T> {
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
Some(Arc::into_inner(self.value)?.into_inner().unwrap())
}
}
impl<T> Notify for ArcWriteSignal<T> {
fn notify(&self) {
self.inner.mark_dirty();
}
}
impl<T: 'static> Write for ArcWriteSignal<T> {
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.value
.write()
.ok()
.map(|guard| WriteGuard::new(self.clone(), guard))
}
#[allow(refining_impl_trait)]
fn try_write_untracked(&self) -> Option<UntrackedWriteGuard<Self::Value>> {
UntrackedWriteGuard::try_new(Arc::clone(&self.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/signal/arc_read.rs | reactive_graph/src/signal/arc_read.rs | use super::{
guards::{Plain, ReadGuard},
subscriber_traits::AsSubscriberSet,
};
use crate::{
graph::SubscriberSet,
traits::{DefinedAt, IntoInner, IsDisposed, ReadUntracked},
};
use core::fmt::{Debug, Formatter, Result};
use std::{
hash::Hash,
panic::Location,
sync::{Arc, RwLock},
};
/// A reference-counted getter for a reactive signal.
///
/// A signal is a piece of data that may change over time,
/// and notifies other code when it has changed.
///
/// This is a reference-counted signal, which is `Clone` but not `Copy`.
/// For arena-allocated `Copy` signals, use [`ReadSignal`](super::ReadSignal).
///
/// ## Core Trait Implementations
/// - [`.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.
/// - [`::from_stream()`](crate::traits::FromStream) converts an `async` stream
/// of values into a signal containing the latest value.
///
/// ## Examples
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::signal::*;
/// let (count, set_count) = arc_signal(0);
///
/// // calling .get() clones and returns the value
/// assert_eq!(count.get(), 0);
/// // calling .read() accesses the value by reference
/// assert_eq!(count.read(), 0);
/// ```
pub struct ArcReadSignal<T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) value: Arc<RwLock<T>>,
pub(crate) inner: Arc<RwLock<SubscriberSet>>,
}
impl<T> Clone for ArcReadSignal<T> {
#[track_caller]
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
value: Arc::clone(&self.value),
inner: Arc::clone(&self.inner),
}
}
}
impl<T> Debug for ArcReadSignal<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.debug_struct("ArcReadSignal")
.field("type", &std::any::type_name::<T>())
.field("value", &Arc::as_ptr(&self.value))
.finish()
}
}
impl<T: Default> Default for ArcReadSignal<T> {
#[track_caller]
fn default() -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::new(RwLock::new(T::default())),
inner: Arc::new(RwLock::new(SubscriberSet::new())),
}
}
}
impl<T> PartialEq for ArcReadSignal<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.value, &other.value)
}
}
impl<T> Eq for ArcReadSignal<T> {}
impl<T> Hash for ArcReadSignal<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::ptr::hash(&Arc::as_ptr(&self.value), state);
}
}
impl<T> DefinedAt for ArcReadSignal<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> IsDisposed for ArcReadSignal<T> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T> IntoInner for ArcReadSignal<T> {
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
Some(Arc::into_inner(self.value)?.into_inner().unwrap())
}
}
impl<T> AsSubscriberSet for ArcReadSignal<T> {
type Output = Arc<RwLock<SubscriberSet>>;
#[inline(always)]
fn as_subscriber_set(&self) -> Option<Self::Output> {
Some(Arc::clone(&self.inner))
}
}
impl<T: 'static> ReadUntracked for ArcReadSignal<T> {
type Value = ReadGuard<T, Plain<T>>;
#[track_caller]
fn try_read_untracked(&self) -> Option<Self::Value> {
Plain::try_new(Arc::clone(&self.value)).map(ReadGuard::new)
}
}
| 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/read.rs | reactive_graph/src/signal/read.rs | use super::{
guards::{Plain, ReadGuard},
subscriber_traits::AsSubscriberSet,
ArcReadSignal,
};
use crate::{
graph::SubscriberSet,
owner::{ArenaItem, FromLocal, LocalStorage, Storage, SyncStorage},
traits::{DefinedAt, Dispose, IntoInner, IsDisposed, ReadUntracked},
unwrap_signal,
};
use core::fmt::Debug;
use std::{
hash::Hash,
panic::Location,
sync::{Arc, RwLock},
};
/// An arena-allocated getter for a reactive signal.
///
/// A signal is a piece of data that may change over time,
/// and notifies other code when it has changed.
///
/// 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 [`ArcReadSignal`].
///
/// ## Core Trait Implementations
/// - [`.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.
/// - [`::from_stream()`](crate::traits::FromStream) converts an `async` stream
/// of values into a signal containing the latest value.
///
/// ## Examples
/// ```
/// # use reactive_graph::prelude::*; use reactive_graph::signal::*; let owner = reactive_graph::owner::Owner::new(); owner.set();
/// let (count, set_count) = signal(0);
///
/// // calling .get() clones and returns the value
/// assert_eq!(count.get(), 0);
/// // calling .read() accesses the value by reference
/// assert_eq!(count.read(), 0);
/// ```
pub struct ReadSignal<T, S = SyncStorage> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
pub(crate) defined_at: &'static Location<'static>,
pub(crate) inner: ArenaItem<ArcReadSignal<T>, S>,
}
impl<T, S> Dispose for ReadSignal<T, S> {
fn dispose(self) {
self.inner.dispose()
}
}
impl<T, S> Copy for ReadSignal<T, S> {}
impl<T, S> Clone for ReadSignal<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Debug for ReadSignal<T, S>
where
S: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReadSignal")
.field("type", &std::any::type_name::<T>())
.field("store", &self.inner)
.finish()
}
}
impl<T, S> PartialEq for ReadSignal<T, S> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, S> Eq for ReadSignal<T, S> {}
impl<T, S> Hash for ReadSignal<T, S> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.inner.hash(state);
}
}
impl<T, S> DefinedAt for ReadSignal<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, S> IsDisposed for ReadSignal<T, S> {
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<T, S> IntoInner for ReadSignal<T, S>
where
S: Storage<ArcReadSignal<T>>,
{
type Value = T;
#[inline(always)]
fn into_inner(self) -> Option<Self::Value> {
self.inner.into_inner()?.into_inner()
}
}
impl<T, S> AsSubscriberSet for ReadSignal<T, S>
where
S: Storage<ArcReadSignal<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 ReadSignal<T, S>
where
T: 'static,
S: Storage<ArcReadSignal<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> From<ArcReadSignal<T>> for ReadSignal<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcReadSignal<T>) -> Self {
ReadSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T> FromLocal<ArcReadSignal<T>> for ReadSignal<T, LocalStorage>
where
T: 'static,
{
#[track_caller]
fn from_local(value: ArcReadSignal<T>) -> Self {
ReadSignal {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T, S> From<ReadSignal<T, S>> for ArcReadSignal<T>
where
T: 'static,
S: Storage<ArcReadSignal<T>>,
{
#[track_caller]
fn from(value: ReadSignal<T, S>) -> Self {
value
.inner
.try_get_value()
.unwrap_or_else(unwrap_signal!(value))
}
}
| 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.