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/tachys/src/html/element/inner_html.rs | tachys/src/html/element/inner_html.rs | use super::{ElementWithChildren, HtmlElement};
use crate::{
html::attribute::{
maybe_next_attr_erasure_macros::{
next_attr_combine, next_attr_output_type,
},
Attribute, NamedAttributeKey, NextAttribute,
},
renderer::Rndr,
view::add_attr::AddAnyAttr,
};
use std::{future::Future, sync::Arc};
/// Returns an [`Attribute`] that sets the inner HTML of an element.
///
/// No children should be given to this element, as this HTML will be used instead.
///
/// # Security
/// Be very careful when using this method. Always remember to
/// sanitize the input to avoid a cross-site scripting (XSS)
/// vulnerability.
#[inline(always)]
pub fn inner_html<T>(value: T) -> InnerHtml<T>
where
T: InnerHtmlValue,
{
InnerHtml { value }
}
/// Sets the inner HTML of an element.
#[derive(Debug)]
pub struct InnerHtml<T> {
value: T,
}
impl<T> Clone for InnerHtml<T>
where
T: Clone,
{
fn clone(&self) -> Self {
Self {
value: self.value.clone(),
}
}
}
impl<T> Attribute for InnerHtml<T>
where
T: InnerHtmlValue,
{
const MIN_LENGTH: usize = 0;
type AsyncOutput = InnerHtml<T::AsyncOutput>;
type State = T::State;
type Cloneable = InnerHtml<T::Cloneable>;
type CloneableOwned = InnerHtml<T::CloneableOwned>;
fn html_len(&self) -> usize {
self.value.html_len()
}
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
inner_html: &mut String,
) {
self.value.to_html(inner_html);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
self.value.hydrate::<FROM_SERVER>(el)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
self.value.build(el)
}
fn rebuild(self, state: &mut Self::State) {
self.value.rebuild(state);
}
fn into_cloneable(self) -> Self::Cloneable {
InnerHtml {
value: self.value.into_cloneable(),
}
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
InnerHtml {
value: self.value.into_cloneable_owned(),
}
}
fn dry_resolve(&mut self) {
self.value.dry_resolve();
}
async fn resolve(self) -> Self::AsyncOutput {
InnerHtml {
value: self.value.resolve().await,
}
}
fn keys(&self) -> Vec<NamedAttributeKey> {
vec![NamedAttributeKey::InnerHtml]
}
}
impl<T> NextAttribute for InnerHtml<T>
where
T: InnerHtmlValue,
{
next_attr_output_type!(Self, NewAttr);
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
next_attr_combine!(self, new_attr)
}
}
/// Sets the inner HTML of an element.
pub trait InnerHtmlAttribute<T>
where
T: InnerHtmlValue,
Self: Sized + AddAnyAttr,
{
/// Sets the inner HTML of this element.
///
/// No children should be given to this element, as this HTML will be used instead.
///
/// # Security
/// Be very careful when using this method. Always remember to
/// sanitize the input to avoid a cross-site scripting (XSS)
/// vulnerability.
fn inner_html(
self,
value: T,
) -> <Self as AddAnyAttr>::Output<InnerHtml<T>> {
self.add_any_attr(inner_html(value))
}
}
impl<T, E, At> InnerHtmlAttribute<T> for HtmlElement<E, At, ()>
where
Self: AddAnyAttr,
E: ElementWithChildren,
At: Attribute,
T: InnerHtmlValue,
{
fn inner_html(
self,
value: T,
) -> <Self as AddAnyAttr>::Output<InnerHtml<T>> {
self.add_any_attr(inner_html(value))
}
}
/// A possible value for [`InnerHtml`].
pub trait InnerHtmlValue: Send {
/// The type after all async data have resolved.
type AsyncOutput: InnerHtmlValue;
/// The view state retained between building and rebuilding.
type State;
/// An equivalent value that can be cloned.
type Cloneable: InnerHtmlValue + Clone;
/// An equivalent value that can be cloned and is `'static`.
type CloneableOwned: InnerHtmlValue + Clone + 'static;
/// The estimated length of the HTML.
fn html_len(&self) -> usize;
/// Renders the class to HTML.
fn to_html(self, buf: &mut String);
/// Renders the class to HTML for a `<template>`.
fn to_template(buf: &mut String);
/// Adds interactivity as necessary, given DOM nodes that were created from HTML that has
/// either been rendered on the server, or cloned for a `<template>`.
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State;
/// Adds this class to the element during client-side rendering.
fn build(self, el: &crate::renderer::types::Element) -> Self::State;
/// Updates the value.
fn rebuild(self, state: &mut Self::State);
/// Converts this to a cloneable type.
fn into_cloneable(self) -> Self::Cloneable;
/// Converts this to a cloneable, owned type.
fn into_cloneable_owned(self) -> Self::CloneableOwned;
/// “Runs” the attribute without other side effects. For primitive types, this is a no-op. For
/// reactive types, this can be used to gather data about reactivity or about asynchronous data
/// that needs to be loaded.
fn dry_resolve(&mut self);
/// “Resolves” this into a type that is not waiting for any asynchronous data.
fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send;
}
impl InnerHtmlValue for String {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Self);
type Cloneable = Arc<str>;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, buf: &mut String) {
buf.push_str(&self);
}
fn to_template(_buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
if !FROM_SERVER {
Rndr::set_inner_html(el, &self);
}
(el.clone(), self)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
Rndr::set_inner_html(el, &self);
(el.clone(), self)
}
fn rebuild(self, state: &mut Self::State) {
if self != state.1 {
Rndr::set_inner_html(&state.0, &self);
state.1 = self;
}
}
fn into_cloneable(self) -> Self::Cloneable {
self.into()
}
fn into_cloneable_owned(self) -> Self::Cloneable {
self.into()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl InnerHtmlValue for Arc<str> {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Self);
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, buf: &mut String) {
buf.push_str(&self);
}
fn to_template(_buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
if !FROM_SERVER {
Rndr::set_inner_html(el, &self);
}
(el.clone(), self)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
Rndr::set_inner_html(el, &self);
(el.clone(), self)
}
fn rebuild(self, state: &mut Self::State) {
if self != state.1 {
Rndr::set_inner_html(&state.0, &self);
state.1 = self;
}
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::Cloneable {
self
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl InnerHtmlValue for &str {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Self);
type Cloneable = Self;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, buf: &mut String) {
buf.push_str(self);
}
fn to_template(_buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
if !FROM_SERVER {
Rndr::set_inner_html(el, self);
}
(el.clone(), self)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
Rndr::set_inner_html(el, self);
(el.clone(), self)
}
fn rebuild(self, state: &mut Self::State) {
if self != state.1 {
Rndr::set_inner_html(&state.0, self);
state.1 = self;
}
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl<T> InnerHtmlValue for Option<T>
where
T: InnerHtmlValue,
{
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Option<T::State>);
type Cloneable = Option<T::Cloneable>;
type CloneableOwned = Option<T::CloneableOwned>;
fn html_len(&self) -> usize {
match self {
Some(i) => i.html_len(),
None => 0,
}
}
fn to_html(self, buf: &mut String) {
if let Some(value) = self {
value.to_html(buf);
}
}
fn to_template(_buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
(el.clone(), self.map(|n| n.hydrate::<FROM_SERVER>(el)))
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
(el.clone(), self.map(|n| n.build(el)))
}
fn rebuild(self, state: &mut Self::State) {
let new_state = match (self, &mut state.1) {
(None, None) => None,
(None, Some(_)) => {
Rndr::set_inner_html(&state.0, "");
Some(None)
}
(Some(new), None) => Some(Some(new.build(&state.0))),
(Some(new), Some(state)) => {
new.rebuild(state);
None
}
};
if let Some(new_state) = new_state {
state.1 = new_state;
}
}
fn into_cloneable(self) -> Self::Cloneable {
self.map(|inner| inner.into_cloneable())
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.map(|inner| inner.into_cloneable_owned())
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/element/custom.rs | tachys/src/html/element/custom.rs | use super::ElementWithChildren;
use crate::html::element::{ElementType, HtmlElement};
use std::fmt::Debug;
/// Creates a custom element.
#[track_caller]
pub fn custom<E>(tag: E) -> HtmlElement<Custom<E>, (), ()>
where
E: AsRef<str>,
{
HtmlElement {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
tag: Custom(tag),
attributes: (),
children: (),
}
}
/// A custom HTML element.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Custom<E>(E);
impl<E: 'static> ElementType for Custom<E>
where
E: AsRef<str> + Send,
{
type Output = web_sys::HtmlElement;
const SELF_CLOSING: bool = false;
const ESCAPE_CHILDREN: bool = true;
const TAG: &'static str = "";
const NAMESPACE: Option<&'static str> = None;
fn tag(&self) -> &str {
self.0.as_ref()
}
}
impl<E> ElementWithChildren for Custom<E> {}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/key.rs | tachys/src/html/attribute/key.rs | use super::{Attr, AttributeValue};
use std::fmt::Debug;
/// An HTML attribute key.
pub trait AttributeKey: Clone + Send + 'static {
/// The name of the attribute.
const KEY: &'static str;
}
macro_rules! attributes {
($(#[$meta:meta] $key:ident $html:literal),* $(,)?) => {
paste::paste! {
$(
#[$meta]
#[track_caller]
pub fn $key<V>(value: V) -> Attr<[<$key:camel>], V>
where V: AttributeValue,
{
Attr([<$key:camel>], value)
}
#[$meta]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct [<$key:camel>];
impl AttributeKey for [<$key:camel>] {
const KEY: &'static str = $html;
}
)*
}
}
}
attributes! {
// HTML
/// The `abbr` attribute specifies an abbreviated form of the element's content.
abbr "abbr",
/// The `accept-charset` attribute specifies the character encodings that are to be used for the form submission.
accept_charset "accept-charset",
/// The `accept` attribute specifies a list of types the server accepts, typically a file type.
accept "accept",
/// The `accesskey` attribute specifies a shortcut key to activate or focus an element.
accesskey "accesskey",
/// The `action` attribute defines the URL to which the form data will be sent.
action "action",
/// The `align` attribute specifies the alignment of an element.
align "align",
/// The `allow` attribute defines a feature policy for the content in an iframe.
allow "allow",
/// The `allowfullscreen` attribute allows the iframe to be displayed in fullscreen mode.
allowfullscreen "allowfullscreen",
/// The `allowpaymentrequest` attribute allows a cross-origin iframe to invoke the Payment Request API.
allowpaymentrequest "allowpaymentrequest",
/// The `alt` attribute provides alternative text for an image, if the image cannot be displayed.
alt "alt",
// ARIA
/// The `aria-activedescendant` attribute identifies the currently active element when DOM focus is on a composite widget, textbox, group, or application.
aria_activedescendant "aria-activedescendant",
/// The `aria-atomic` attribute indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the aria-relevant attribute.
aria_atomic "aria-atomic",
/// The `aria-autocomplete` attribute indicates whether user input completion suggestions are provided.
aria_autocomplete "aria-autocomplete",
/// The `aria-busy` attribute indicates whether an element, and its subtree, are currently being updated.
aria_busy "aria-busy",
/// The `aria-checked` attribute indicates the current "checked" state of checkboxes, radio buttons, and other widgets.
aria_checked "aria-checked",
/// The `aria-colcount` attribute defines the total number of columns in a table, grid, or treegrid.
aria_colcount "aria-colcount",
/// The `aria-colindex` attribute defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.
aria_colindex "aria-colindex",
/// The `aria-colspan` attribute defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.
aria_colspan "aria-colspan",
/// The `aria-controls` attribute identifies the element (or elements) whose contents or presence are controlled by the current element.
aria_controls "aria-controls",
/// The `aria-current` attribute indicates the element representing the current item within a container or set of related elements.
aria_current "aria-current",
/// The `aria-describedby` attribute identifies the element (or elements) that describes the object.
aria_describedby "aria-describedby",
/// The `aria-description` attribute provides a string value that describes or annotates the current element.
aria_description "aria-description",
/// The `aria-details` attribute identifies the element that provides a detailed, extended description for the object.
aria_details "aria-details",
/// The `aria-disabled` attribute indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.
aria_disabled "aria-disabled",
/// The `aria-dropeffect` attribute indicates what functions can be performed when a dragged object is released on the drop target.
aria_dropeffect "aria-dropeffect",
/// The `aria-errormessage` attribute identifies the element that provides an error message for the object.
aria_errormessage "aria-errormessage",
/// The `aria-expanded` attribute indicates whether an element, or another grouping element it controls, is currently expanded or collapsed.
aria_expanded "aria-expanded",
/// The `aria-flowto` attribute identifies the next element (or elements) in an alternate reading order of content.
aria_flowto "aria-flowto",
/// The `aria-grabbed` attribute indicates an element's "grabbed" state in a drag-and-drop operation.
aria_grabbed "aria-grabbed",
/// The `aria-haspopup` attribute indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.
aria_haspopup "aria-haspopup",
/// The `aria-hidden` attribute indicates whether the element is exposed to an accessibility API.
aria_hidden "aria-hidden",
/// The `aria-invalid` attribute indicates the entered value does not conform to the format expected by the application.
aria_invalid "aria-invalid",
/// The `aria-keyshortcuts` attribute indicates keyboard shortcuts that an author has implemented to activate or give focus to an element.
aria_keyshortcuts "aria-keyshortcuts",
/// The `aria-label` attribute defines a string value that labels the current element.
aria_label "aria-label",
/// The `aria-labelledby` attribute identifies the element (or elements) that labels the current element.
aria_labelledby "aria-labelledby",
/// The `aria-live` attribute indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.
aria_live "aria-live",
/// The `aria-modal` attribute indicates whether an element is modal when displayed.
aria_modal "aria-modal",
/// The `aria-multiline` attribute indicates whether a text box accepts multiple lines of input or only a single line.
aria_multiline "aria-multiline",
/// The `aria-multiselectable` attribute indicates that the user may select more than one item from the current selectable descendants.
aria_multiselectable "aria-multiselectable",
/// The `aria-orientation` attribute indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous.
aria_orientation "aria-orientation",
/// The `aria-owns` attribute identifies an element (or elements) in order to define a relationship between the element with `aria-owns` and the target element.
aria_owns "aria-owns",
/// The `aria-placeholder` attribute defines a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value.
aria_placeholder "aria-placeholder",
/// The `aria-posinset` attribute defines an element's position within a set or treegrid.
aria_posinset "aria-posinset",
/// The `aria-pressed` attribute indicates the current "pressed" state of toggle buttons.
aria_pressed "aria-pressed",
/// The `aria-readonly` attribute indicates that the element is not editable, but is otherwise operable.
aria_readonly "aria-readonly",
/// The `aria-relevant` attribute indicates what user agent changes to the accessibility tree should be monitored.
aria_relevant "aria-relevant",
/// The `aria-required` attribute indicates that user input is required on the element before a form may be submitted.
aria_required "aria-required",
/// The `aria-roledescription` attribute defines a human-readable, author-localized description for the role of an element.
aria_roledescription "aria-roledescription",
/// The `aria-rowcount` attribute defines the total number of rows in a table, grid, or treegrid.
aria_rowcount "aria-rowcount",
/// The `aria-rowindex` attribute defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.
aria_rowindex "aria-rowindex",
/// The `aria-rowspan` attribute defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.
aria_rowspan "aria-rowspan",
/// The `aria-selected` attribute indicates the current "selected" state of various widgets.
aria_selected "aria-selected",
/// The `aria-setsize` attribute defines the number of items in the current set of listitems or treeitems.
aria_setsize "aria-setsize",
/// The `aria-sort` attribute indicates if items in a table or grid are sorted in ascending or descending order.
aria_sort "aria-sort",
/// The `aria-valuemax` attribute defines the maximum allowed value for a range widget.
aria_valuemax "aria-valuemax",
/// The `aria-valuemin` attribute defines the minimum allowed value for a range widget.
aria_valuemin "aria-valuemin",
/// The `aria-valuenow` attribute defines the current value for a range widget.
aria_valuenow "aria-valuenow",
/// The `aria-valuetext` attribute defines the human-readable text alternative of aria-valuenow for a range widget.
aria_valuetext "aria-valuetext",
/// The `as` attribute specifies the type of destination for the content of the link.
r#as "as",
/// The `async` attribute indicates that the script should be executed asynchronously.
r#async "async",
/// The `attributionsrc` attribute indicates that you want the browser to send an `Attribution-Reporting-Eligible` header along with a request.
attributionsrc "attributionsrc",
/// The `autocapitalize` attribute controls whether and how text input is automatically capitalized as it is entered/edited by the user.
autocapitalize "autocapitalize",
/// The `autocomplete` attribute indicates whether an input field can have its value automatically completed by the browser.
autocomplete "autocomplete",
/// The `autofocus` attribute indicates that an element should be focused on page load.
autofocus "autofocus",
/// The `autoplay` attribute indicates that the media should start playing as soon as it is loaded.
autoplay "autoplay",
/// The `background` attribute sets the URL of the background image for the document.
background "background",
/// The `bgcolor` attribute sets the background color of an element.
bgcolor "bgcolor",
/// The `blocking` attribute indicates that the script will block the page loading until it is executed.
blocking "blocking",
/// The `border` attribute sets the width of an element's border.
border "border",
/// The `buffered` attribute contains the time ranges that the media has been buffered.
buffered "buffered",
/// The `capture` attribute indicates that the user must capture media using a camera or microphone instead of selecting a file from the file picker.
capture "capture",
/// The `challenge` attribute specifies the challenge string that is paired with the keygen element.
challenge "challenge",
/// The `charset` attribute specifies the character encoding of the HTML document.
charset "charset",
/// The `checked` attribute indicates whether an input element is checked or not.
checked "checked",
/// The `cite` attribute contains a URL that points to the source of the quotation or change.
cite "cite",
// class is handled in ../class.rs instead
//class "class",
/// The `code` attribute specifies the URL of the applet's class file to be loaded and executed.
code "code",
/// The `color` attribute specifies the color of an element's text.
color "color",
/// The `cols` attribute specifies the visible width of a text area.
cols "cols",
/// The `colspan` attribute defines the number of columns a cell should span.
colspan "colspan",
/// The `command` attribute defines the command to be invoked when user clicks the `<button>` element which has `commandfor` attribute specified.
command "command",
/// The `commandfor` attribute defines the id of the element which button is controlling. It is generic version of `popovertarget`.
commandfor "commandfor",
/// The `content` attribute gives the value associated with the http-equiv or name attribute.
content "content",
/// The `contenteditable` attribute indicates whether the element's content is editable.
contenteditable "contenteditable",
/// The `contextmenu` attribute specifies the ID of a `<menu>` element to open as a context menu.
contextmenu "contextmenu",
/// The `controls` attribute indicates whether the browser should display playback controls for the media.
controls "controls",
/// The `controlslist` attribute allows the control of which controls to show on the media element whenever the browser shows its native controls.
controlslist "controlslist",
/// The `coords` attribute specifies the coordinates of an area in an image map.
coords "coords",
/// The `crossorigin` attribute indicates whether the resource should be fetched with a CORS request.
crossorigin "crossorigin",
/// The `csp` attribute allows the embedding document to define the Content Security Policy that an embedded document must agree to enforce upon itself.
csp "csp",
/// The `data` attribute specifies the URL of the resource that is being embedded.
data "data",
/// The `datetime` attribute specifies the date and time.
datetime "datetime",
/// The `decoding` attribute indicates the preferred method for decoding images.
decoding "decoding",
/// The `default` attribute indicates that the track should be enabled unless the user's preferences indicate that another track is more appropriate.
default "default",
/// The `defer` attribute indicates that the script should be executed after the document has been parsed.
defer "defer",
/// The `dir` attribute specifies the text direction for the content in an element.
dir "dir",
/// The `dirname` attribute identifies the text directionality of an input element.
dirname "dirname",
/// The `disabled` attribute indicates whether the element is disabled.
disabled "disabled",
/// The `disablepictureinpicture` attribute indicates that the element is not allowed to be displayed in Picture-in-Picture mode.
disablepictureinpicture "disablepictureinpicture",
/// The `disableremoteplayback` attribute indicates that the element is not allowed to be displayed using remote playback.
disableremoteplayback "disableremoteplayback",
/// The `download` attribute indicates that the linked resource is intended to be downloaded rather than displayed in the browser.
download "download",
/// The `draggable` attribute indicates whether the element is draggable.
draggable "draggable",
/// The `elementtiming` attributes marks the element for observation by the `PerformanceElementTiming` API.
elementtiming "elementtiming",
/// The `enctype` attribute specifies the MIME type of the form submission.
enctype "enctype",
/// The `enterkeyhint` attribute allows authors to specify what kind of action label or icon will be presented to users in a virtual keyboard's enter key.
enterkeyhint "enterkeyhint",
/// The `exportparts` attribute enables the sharing of parts of an element's shadow DOM with a containing document.
exportparts "exportparts",
/// The `fetchpriority` attribute allows developers to specify the priority of a resource fetch request.
fetchpriority "fetchpriority",
/// The `for` attribute specifies which form element a label is bound to.
r#for "for",
/// The `form` attribute associates the element with a form element.
form "form",
/// The `formaction` attribute specifies the URL that processes the form submission.
formaction "formaction",
/// The `formenctype` attribute specifies how the form data should be encoded when submitted.
formenctype "formenctype",
/// The `formmethod` attribute specifies the HTTP method to use when submitting the form.
formmethod "formmethod",
/// The `formnovalidate` attribute indicates that the form should not be validated when submitted.
formnovalidate "formnovalidate",
/// The `formtarget` attribute specifies where to display the response after submitting the form.
formtarget "formtarget",
/// The `headers` attribute specifies the headers associated with the element.
headers "headers",
/// The `height` attribute specifies the height of an element.
height "height",
/// The `hidden` attribute indicates that the element is not yet, or is no longer, relevant.
hidden "hidden",
/// The `high` attribute specifies the range that is considered to be a high value.
high "high",
/// The `href` attribute specifies the URL of a linked resource.
href "href",
/// The `hreflang` attribute specifies the language of the linked resource.
hreflang "hreflang",
/// The `http-equiv` attribute provides an HTTP header for the information/value of the content attribute.
http_equiv "http-equiv",
/// The `icon` attribute specifies the URL of an image to be used as a graphical icon for the element.
icon "icon",
/// The `id` attribute specifies a unique id for an element.
id "id",
/// The `imagesizes` attribute specifies image sizes for different page layouts.
imagesizes "imagesizes",
/// The `imagesrcset` attribute specifies the URLs of multiple images to be used in different situations.
imagesrcset "imagesrcset",
/// The `importance` attribute specifies the relative importance of the element.
importance "importance",
/// The `inert` attribute indicates that the element is non-interactive and won't be accessible to user interactions or assistive technologies.
inert "inert",
/// The `inputmode` attribute specifies the type of data that the user will enter.
inputmode "inputmode",
/// The `integrity` attribute contains a hash value that the browser can use to verify that the resource hasn't been altered.
integrity "integrity",
/// The `intrinsicsize` attribute specifies the intrinsic size of an image or video.
intrinsicsize "intrinsicsize",
/// The `is` attribute allows you to specify the name of a custom element.
is "is",
/// The `ismap` attribute indicates that the image is part of a server-side image map.
ismap "ismap",
/// The `itemid` attribute assigns a unique identifier to an item.
itemid "itemid",
/// The `itemprop` attribute adds a property to an item.
itemprop "itemprop",
/// The `itemref` attribute provides a list of element IDs that have additional properties for the item.
itemref "itemref",
/// The `itemscope` attribute creates a new item and adds it to the page's items.
itemscope "itemscope",
/// The `itemtype` attribute specifies the type of an item.
itemtype "itemtype",
/// The `keytype` attribute specifies the type of key used by the `<keygen>` element.
keytype "keytype",
/// The `kind` attribute specifies the kind of text track.
kind "kind",
/// The `label` attribute provides a user-readable title for an element.
label "label",
/// The `lang` attribute specifies the language of the element's content.
lang "lang",
/// The `language` attribute specifies the scripting language used for the script.
language "language",
/// The `list` attribute identifies a `<datalist>` element that contains pre-defined options for an `<input>` element.
list "list",
/// The `loading` attribute indicates how the browser should load the image.
loading "loading",
/// The `loop` attribute indicates whether the media should start over again when it reaches the end.
r#loop "loop",
/// The `low` attribute specifies the range that is considered to be a low value.
low "low",
/// The `manifest` attribute specifies the URL of a document's cache manifest.
manifest "manifest",
/// The `max` attribute specifies the maximum value for an input element.
max "max",
/// The `maxlength` attribute specifies the maximum number of characters that an input element can accept.
maxlength "maxlength",
/// The `media` attribute specifies what media/device the linked resource is optimized for.
media "media",
/// The `method` attribute specifies the HTTP method to use when submitting the form.
method "method",
/// The `min` attribute specifies the minimum value for an input element.
min "min",
/// The `minlength` attribute specifies the minimum number of characters that an input element can accept.
minlength "minlength",
/// The `multiple` attribute indicates whether the user can enter more than one value.
multiple "multiple",
/// The `muted` attribute indicates whether the audio will be initially silenced on page load.
muted "muted",
/// The `name` attribute specifies the name of the element.
name "name",
/// The `nomodule` attribute indicates that the script should not be executed in browsers that support ES modules.
nomodule "nomodule",
/// The `nonce` attribute provides a cryptographic nonce to ensure that a script or style is approved for execution.
nonce "nonce",
/// The `novalidate` attribute indicates that the form should not be validated when submitted.
novalidate "novalidate",
/// The `open` attribute indicates whether the details element is open or closed.
open "open",
/// The `optimum` attribute specifies the range that is considered to be an optimum value.
optimum "optimum",
/// The `part` attribute identifies the element as a shadow DOM part.
part "part",
/// The `pattern` attribute specifies a regular expression that the input element's value is checked against.
pattern "pattern",
/// The `ping` attribute contains a space-separated list of URLs to be notified if the user follows the hyperlink.
ping "ping",
/// The `placeholder` attribute provides a short hint that describes the expected value of the input element.
placeholder "placeholder",
/// The `playsinline` attribute indicates that the video should play inline in the element's playback area.
playsinline "playsinline",
/// The `popover` attribute indicates that an element is a popover and specifies the event that causes the popover to be shown.
popover "popover",
/// The `popovertarget` attribute specifies the ID of an element to toggle a popover.
popovertarget "popovertarget",
/// The `popovertargetaction` attribute specifies the action that shows the popover.
popovertargetaction "popovertargetaction",
/// The `poster` attribute specifies an image to be shown while the video is downloading or until the user hits the play button.
poster "poster",
/// The `preload` attribute specifies if and how the author thinks that the media file should be loaded when the page loads.
preload "preload",
/// The `radiogroup` attribute specifies the name of the group to which the element belongs.
radiogroup "radiogroup",
/// The `readonly` attribute indicates that the user cannot modify the value of the input element.
readonly "readonly",
/// The `referrerpolicy` attribute specifies which referrer information to include with requests.
referrerpolicy "referrerpolicy",
/// The `rel` attribute specifies the relationship between the current document and the linked document.
rel "rel",
/// The `required` attribute indicates that the user must fill in the input element before submitting the form.
required "required",
/// The `reversed` attribute indicates that the list should be displayed in a descending order.
reversed "reversed",
/// The `role` attribute defines the role of an element in the context of a web application.
role "role",
/// The `rows` attribute specifies the number of visible text lines for a text area.
rows "rows",
/// The `rowspan` attribute defines the number of rows a cell should span.
rowspan "rowspan",
/// The `sandbox` attribute applies extra restrictions to the content in the `<iframe>`.
sandbox "sandbox",
/// The `scope` attribute specifies whether a header cell is a header for a column, row, or group of columns or rows.
scope "scope",
/// The `scoped` attribute indicates that the styles in a `<style>` element are scoped to the parent element.
scoped "scoped",
/// The `selected` attribute indicates that the option is selected.
selected "selected",
/// The `shape` attribute specifies the shape of the area.
shape "shape",
/// The `size` attribute specifies the width of the input element.
size "size",
/// The `sizes` attribute specifies the sizes of icons for visual media.
sizes "sizes",
/// The `slot` attribute assigns a slot to an element.
slot "slot",
/// The `span` attribute defines the number of columns in a `<colgroup>` or the number of rows in a `<rowgroup>`.
span "span",
/// The `spellcheck` attribute indicates whether spell checking is allowed for the element.
spellcheck "spellcheck",
/// The `src` attribute specifies the URL of the media resource.
src "src",
/// The `srcdoc` attribute specifies the HTML content of the page to show in the `<iframe>`.
srcdoc "srcdoc",
/// The `srclang` attribute specifies the language of the text track.
srclang "srclang",
/// The `srcset` attribute specifies the URLs of multiple images to be used in different situations.
srcset "srcset",
/// The `start` attribute specifies the start value of the list.
start "start",
/// The `step` attribute specifies the legal number intervals for an input element.
step "step",
// style is handled in ../style.rs instead
// style "style",
/// The `summary` attribute provides a summary of the content of the table.
summary "summary",
/// The `tabindex` attribute specifies the tab order of an element.
tabindex "tabindex",
/// The `target` attribute specifies where to open the linked document.
target "target",
/// The `title` attribute provides additional information about an element.
title "title",
/// The `translate` attribute specifies whether the content of an element should be translated or not.
translate "translate",
/// The `type` attribute specifies the type of the element.
r#type "type",
/// The `usemap` attribute specifies the image map to be used by an `<img>` element.
usemap "usemap",
/// The `value` attribute specifies the value of the element.
value "value",
/// The `virtualkeyboardpolicy` attribute controls the policy for virtual keyboards.
virtualkeyboardpolicy "virtualkeyboardpolicy",
/// The `width` attribute specifies the width of an element.
width "width",
/// The `wrap` attribute specifies how the text in a text area is to be wrapped when submitted in a form.
wrap "wrap",
// Event Handler Attributes
/// The `onabort` attribute specifies the event handler for the abort event.
onabort "onabort",
/// The `onautocomplete` attribute specifies the event handler for the autocomplete event.
onautocomplete "onautocomplete",
/// The `onautocompleteerror` attribute specifies the event handler for the autocompleteerror event.
onautocompleteerror "onautocompleteerror",
/// The `onblur` attribute specifies the event handler for the blur event.
onblur "onblur",
/// The `oncancel` attribute specifies the event handler for the cancel event.
oncancel "oncancel",
/// The `oncanplay` attribute specifies the event handler for the canplay event.
oncanplay "oncanplay",
/// The `oncanplaythrough` attribute specifies the event handler for the canplaythrough event.
oncanplaythrough "oncanplaythrough",
/// The `onchange` attribute specifies the event handler for the change event.
onchange "onchange",
/// The `onclick` attribute specifies the event handler for the click event.
onclick "onclick",
/// The `onclose` attribute specifies the event handler for the close event.
onclose "onclose",
/// The `oncontextmenu` attribute specifies the event handler for the contextmenu event.
oncontextmenu "oncontextmenu",
/// The `oncuechange` attribute specifies the event handler for the cuechange event.
oncuechange "oncuechange",
/// The `ondblclick` attribute specifies the event handler for the double click event.
ondblclick "ondblclick",
/// The `ondrag` attribute specifies the event handler for the drag event.
ondrag "ondrag",
/// The `ondragend` attribute specifies the event handler for the dragend event.
ondragend "ondragend",
/// The `ondragenter` attribute specifies the event handler for the dragenter event.
ondragenter "ondragenter",
/// The `ondragleave` attribute specifies the event handler for the dragleave event.
ondragleave "ondragleave",
/// The `ondragover` attribute specifies the event handler for the dragover event.
ondragover "ondragover",
/// The `ondragstart` attribute specifies the event handler for the dragstart event.
ondragstart "ondragstart",
/// The `ondrop` attribute specifies the event handler for the drop event.
ondrop "ondrop",
/// The `ondurationchange` attribute specifies the event handler for the durationchange event.
ondurationchange "ondurationchange",
/// The `onemptied` attribute specifies the event handler for the emptied event.
onemptied "onemptied",
/// The `onended` attribute specifies the event handler for the ended event.
onended "onended",
/// The `onerror` attribute specifies the event handler for the error event.
onerror "onerror",
/// The `onfocus` attribute specifies the event handler for the focus event.
onfocus "onfocus",
/// The `onformdata` attribute specifies the event handler for the formdata event.
onformdata "onformdata",
/// The `oninput` attribute specifies the event handler for the input event.
oninput "oninput",
/// The `oninvalid` attribute specifies the event handler for the invalid event.
oninvalid "oninvalid",
/// The `onkeydown` attribute specifies the event handler for the keydown event.
onkeydown "onkeydown",
/// The `onkeypress` attribute specifies the event handler for the keypress event.
onkeypress "onkeypress",
/// The `onkeyup` attribute specifies the event handler for the keyup event.
onkeyup "onkeyup",
/// The `onlanguagechange` attribute specifies the event handler for the languagechange event.
onlanguagechange "onlanguagechange",
/// The `onload` attribute specifies the event handler for the load event.
onload "onload",
/// The `onloadeddata` attribute specifies the event handler for the loadeddata event.
onloadeddata "onloadeddata",
/// The `onloadedmetadata` attribute specifies the event handler for the loadedmetadata event.
onloadedmetadata "onloadedmetadata",
/// The `onloadstart` attribute specifies the event handler for the loadstart event.
onloadstart "onloadstart",
/// The `onmousedown` attribute specifies the event handler for the mousedown event.
onmousedown "onmousedown",
/// The `onmouseenter` attribute specifies the event handler for the mouseenter event.
onmouseenter "onmouseenter",
/// The `onmouseleave` attribute specifies the event handler for the mouseleave event.
onmouseleave "onmouseleave",
/// The `onmousemove` attribute specifies the event handler for the mousemove event.
onmousemove "onmousemove",
/// The `onmouseout` attribute specifies the event handler for the mouseout event.
onmouseout "onmouseout",
/// The `onmouseover` attribute specifies the event handler for the mouseover event.
onmouseover "onmouseover",
/// The `onmouseup` attribute specifies the event handler for the mouseup event.
onmouseup "onmouseup",
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/global.rs | tachys/src/html/attribute/global.rs | use super::Lang;
use crate::{
html::{
attribute::*,
class::{class, Class, IntoClass},
element::{ElementType, HasElementType, HtmlElement},
event::{on, on_target, EventDescriptor, On, Targeted},
property::{prop, IntoProperty, Property},
style::{style, IntoStyle, Style},
},
prelude::RenderHtml,
view::add_attr::AddAnyAttr,
};
use core::convert::From;
/// Adds an attribute that modifies the `class`.
pub trait ClassAttribute<C>
where
C: IntoClass,
{
/// The type of the element with the new attribute added.
type Output;
/// Adds a CSS class to an element.
fn class(self, value: C) -> Self::Output;
}
impl<E, At, Ch, C> ClassAttribute<C> for HtmlElement<E, At, Ch>
where
E: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
C: IntoClass,
{
type Output = <Self as AddAnyAttr>::Output<Class<C>>;
fn class(self, value: C) -> Self::Output {
self.add_any_attr(class(value))
}
}
/// Adds an attribute that modifies the DOM properties.
pub trait PropAttribute<K, P>
where
P: IntoProperty,
{
/// The type of the element with the new attribute added.
type Output;
/// Adds a DOM property to an element.
fn prop(self, key: K, value: P) -> Self::Output;
}
impl<E, At, Ch, K, P> PropAttribute<K, P> for HtmlElement<E, At, Ch>
where
E: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
K: AsRef<str> + Send,
P: IntoProperty,
{
type Output = <Self as AddAnyAttr>::Output<Property<K, P>>;
fn prop(self, key: K, value: P) -> Self::Output {
self.add_any_attr(prop(key, value))
}
}
/// Adds an attribute that modifies the CSS styles.
pub trait StyleAttribute<S>
where
S: IntoStyle,
{
/// The type of the element with the new attribute added.
type Output;
/// Adds a CSS style to an element.
fn style(self, value: S) -> Self::Output;
}
impl<E, At, Ch, S> StyleAttribute<S> for HtmlElement<E, At, Ch>
where
E: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
S: IntoStyle,
{
type Output = <Self as AddAnyAttr>::Output<Style<S>>;
fn style(self, value: S) -> Self::Output {
self.add_any_attr(style(value))
}
}
/// Adds an event listener to an element definition.
pub trait OnAttribute<E, F> {
/// The type of the element with the event listener added.
type Output;
/// Adds an event listener to an element.
fn on(self, event: E, cb: F) -> Self::Output;
}
impl<El, At, Ch, E, F> OnAttribute<E, F> for HtmlElement<El, At, Ch>
where
El: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
E: EventDescriptor + Send + 'static,
E::EventType: 'static,
E::EventType: From<crate::renderer::types::Event>,
F: FnMut(E::EventType) + 'static,
{
type Output = <Self as AddAnyAttr>::Output<On<E, F>>;
fn on(self, event: E, cb: F) -> Self::Output {
self.add_any_attr(on(event, cb))
}
}
/// Adds an event listener with a typed target to an element definition.
pub trait OnTargetAttribute<E, F, T> {
/// The type of the element with the new attribute added.
type Output;
/// Adds an event listener with a typed target to an element definition.
fn on_target(self, event: E, cb: F) -> Self::Output;
}
impl<El, At, Ch, E, F> OnTargetAttribute<E, F, Self> for HtmlElement<El, At, Ch>
where
El: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
E: EventDescriptor + Send + 'static,
E::EventType: 'static,
E::EventType: From<crate::renderer::types::Event>,
F: FnMut(Targeted<E::EventType, <Self as HasElementType>::ElementType>)
+ 'static,
{
type Output =
<Self as AddAnyAttr>::Output<On<E, Box<dyn FnMut(E::EventType)>>>;
fn on_target(self, event: E, cb: F) -> Self::Output {
self.add_any_attr(on_target::<E, HtmlElement<El, At, Ch>, F>(event, cb))
}
}
/// Global attributes can be added to any HTML element.
pub trait GlobalAttributes<V>
where
Self: Sized + AddAnyAttr,
V: AttributeValue,
{
/// The `accesskey` global attribute provides a hint for generating a keyboard shortcut for the current element.
fn accesskey(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Accesskey, V>> {
self.add_any_attr(accesskey(value))
}
/// The `autocapitalize` global attribute controls whether and how text input is automatically capitalized as it is entered/edited by the user.
fn autocapitalize(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Autocapitalize, V>> {
self.add_any_attr(autocapitalize(value))
}
/// The `autofocus` global attribute is a Boolean attribute indicating that an element should receive focus as soon as the page is loaded.
fn autofocus(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Autofocus, V>> {
self.add_any_attr(autofocus(value))
}
/// The `contenteditable` global attribute is an enumerated attribute indicating if the element should be editable by the user.
fn contenteditable(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Contenteditable, V>> {
self.add_any_attr(contenteditable(value))
}
/// The `dir` global attribute is an enumerated attribute indicating the directionality of the element's text.
fn dir(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Dir, V>> {
self.add_any_attr(dir(value))
}
/// The `draggable` global attribute is an enumerated attribute indicating whether the element can be dragged.
fn draggable(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Draggable, V>> {
self.add_any_attr(draggable(value))
}
/// The `enterkeyhint` global attribute is used to customize the enter key on virtual keyboards.
fn enterkeyhint(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Enterkeyhint, V>> {
self.add_any_attr(enterkeyhint(value))
}
/// The `exportparts` attribute enables the sharing of parts of an element's shadow DOM with a containing document.
fn exportparts(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Exportparts, V>> {
self.add_any_attr(exportparts(value))
}
/// The `hidden` global attribute is a Boolean attribute indicating that the element is not yet, or is no longer, relevant.
fn hidden(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Hidden, V>> {
self.add_any_attr(hidden(value))
}
/// The `id` global attribute defines a unique identifier (ID) which must be unique in the whole document.
fn id(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Id, V>> {
self.add_any_attr(id(value))
}
/// The `inert` global attribute is a Boolean attribute that makes an element behave inertly.
fn inert(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Inert, V>> {
self.add_any_attr(inert(value))
}
/// The `inputmode` global attribute provides a hint to browsers for which virtual keyboard to display.
fn inputmode(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Inputmode, V>> {
self.add_any_attr(inputmode(value))
}
/// The `is` global attribute allows you to specify that a standard HTML element should behave like a custom built-in element.
fn is(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Is, V>> {
self.add_any_attr(is(value))
}
/// The `itemid` global attribute is used to specify the unique, global identifier of an item.
fn itemid(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Itemid, V>> {
self.add_any_attr(itemid(value))
}
/// The `itemprop` global attribute is used to add properties to an item.
fn itemprop(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Itemprop, V>> {
self.add_any_attr(itemprop(value))
}
/// The `itemref` global attribute is used to refer to other elements.
fn itemref(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Itemref, V>> {
self.add_any_attr(itemref(value))
}
/// The `itemscope` global attribute is used to create a new item.
fn itemscope(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Itemscope, V>> {
self.add_any_attr(itemscope(value))
}
/// The `itemtype` global attribute is used to specify the types of items.
fn itemtype(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Itemtype, V>> {
self.add_any_attr(itemtype(value))
}
/// The `lang` global attribute helps define the language of an element.
fn lang(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Lang, V>> {
self.add_any_attr(lang(value))
}
/// The `nonce` global attribute is used to specify a cryptographic nonce.
fn nonce(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Nonce, V>> {
self.add_any_attr(nonce(value))
}
/// The `part` global attribute identifies the element as a part of a component.
fn part(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Part, V>> {
self.add_any_attr(part(value))
}
/// The `popover` global attribute defines the popover's behavior.
fn popover(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Popover, V>> {
self.add_any_attr(popover(value))
}
/// The `role` global attribute defines the role of an element in ARIA.
fn role(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Role, V>> {
self.add_any_attr(role(value))
}
/// The `slot` global attribute assigns a slot in a shadow DOM.
fn slot(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Slot, V>> {
self.add_any_attr(slot(value))
}
/// The `spellcheck` global attribute is an enumerated attribute that defines whether the element may be checked for spelling errors.
fn spellcheck(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Spellcheck, V>> {
self.add_any_attr(spellcheck(value))
}
/// The `tabindex` global attribute indicates if the element can take input focus.
fn tabindex(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Tabindex, V>> {
self.add_any_attr(tabindex(value))
}
/// The `title` global attribute contains text representing advisory information.
fn title(self, value: V) -> <Self as AddAnyAttr>::Output<Attr<Title, V>> {
self.add_any_attr(title(value))
}
/// The `translate` global attribute is an enumerated attribute that specifies whether an element's attribute values and text content should be translated when the page is localized.
fn translate(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Translate, V>> {
self.add_any_attr(translate(value))
}
/// The `virtualkeyboardpolicy` global attribute specifies the behavior of the virtual keyboard.
fn virtualkeyboardpolicy(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<Virtualkeyboardpolicy, V>> {
self.add_any_attr(virtualkeyboardpolicy(value))
}
}
impl<El, At, Ch, V> GlobalAttributes<V> for HtmlElement<El, At, Ch>
where
El: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
V: AttributeValue,
{
}
macro_rules! on_definitions {
($(#[$meta:meta] $key:ident $html:literal),* $(,)?) => {
paste::paste! {
$(
#[doc = concat!("Adds the HTML `", $html, "` attribute to the element.\n\n**Note**: This is the HTML attribute, which takes a JavaScript string, not an `on:` listener that takes application logic written in Rust.")]
#[track_caller]
fn $key(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<[<$key:camel>], V>>
{
self.add_any_attr($key(value))
}
)*
}
}
}
/// Provides methods for HTML event listener attributes.
pub trait GlobalOnAttributes<V>
where
Self: Sized + AddAnyAttr,
V: AttributeValue,
{
on_definitions! {
/// The `onabort` attribute specifies the event handler for the abort event.
onabort "onabort",
/// The `onautocomplete` attribute specifies the event handler for the autocomplete event.
onautocomplete "onautocomplete",
/// The `onautocompleteerror` attribute specifies the event handler for the autocompleteerror event.
onautocompleteerror "onautocompleteerror",
/// The `onblur` attribute specifies the event handler for the blur event.
onblur "onblur",
/// The `oncancel` attribute specifies the event handler for the cancel event.
oncancel "oncancel",
/// The `oncanplay` attribute specifies the event handler for the canplay event.
oncanplay "oncanplay",
/// The `oncanplaythrough` attribute specifies the event handler for the canplaythrough event.
oncanplaythrough "oncanplaythrough",
/// The `onchange` attribute specifies the event handler for the change event.
onchange "onchange",
/// The `onclick` attribute specifies the event handler for the click event.
onclick "onclick",
/// The `onclose` attribute specifies the event handler for the close event.
onclose "onclose",
/// The `oncontextmenu` attribute specifies the event handler for the contextmenu event.
oncontextmenu "oncontextmenu",
/// The `oncuechange` attribute specifies the event handler for the cuechange event.
oncuechange "oncuechange",
/// The `ondblclick` attribute specifies the event handler for the double click event.
ondblclick "ondblclick",
/// The `ondrag` attribute specifies the event handler for the drag event.
ondrag "ondrag",
/// The `ondragend` attribute specifies the event handler for the dragend event.
ondragend "ondragend",
/// The `ondragenter` attribute specifies the event handler for the dragenter event.
ondragenter "ondragenter",
/// The `ondragleave` attribute specifies the event handler for the dragleave event.
ondragleave "ondragleave",
/// The `ondragover` attribute specifies the event handler for the dragover event.
ondragover "ondragover",
/// The `ondragstart` attribute specifies the event handler for the dragstart event.
ondragstart "ondragstart",
/// The `ondrop` attribute specifies the event handler for the drop event.
ondrop "ondrop",
/// The `ondurationchange` attribute specifies the event handler for the durationchange event.
ondurationchange "ondurationchange",
/// The `onemptied` attribute specifies the event handler for the emptied event.
onemptied "onemptied",
/// The `onended` attribute specifies the event handler for the ended event.
onended "onended",
/// The `onerror` attribute specifies the event handler for the error event.
onerror "onerror",
/// The `onfocus` attribute specifies the event handler for the focus event.
onfocus "onfocus",
/// The `onformdata` attribute specifies the event handler for the formdata event.
onformdata "onformdata",
/// The `oninput` attribute specifies the event handler for the input event.
oninput "oninput",
/// The `oninvalid` attribute specifies the event handler for the invalid event.
oninvalid "oninvalid",
/// The `onkeydown` attribute specifies the event handler for the keydown event.
onkeydown "onkeydown",
/// The `onkeypress` attribute specifies the event handler for the keypress event.
onkeypress "onkeypress",
/// The `onkeyup` attribute specifies the event handler for the keyup event.
onkeyup "onkeyup",
/// The `onlanguagechange` attribute specifies the event handler for the languagechange event.
onlanguagechange "onlanguagechange",
/// The `onload` attribute specifies the event handler for the load event.
onload "onload",
/// The `onloadeddata` attribute specifies the event handler for the loadeddata event.
onloadeddata "onloadeddata",
/// The `onloadedmetadata` attribute specifies the event handler for the loadedmetadata event.
onloadedmetadata "onloadedmetadata",
/// The `onloadstart` attribute specifies the event handler for the loadstart event.
onloadstart "onloadstart",
/// The `onmousedown` attribute specifies the event handler for the mousedown event.
onmousedown "onmousedown",
/// The `onmouseenter` attribute specifies the event handler for the mouseenter event.
onmouseenter "onmouseenter",
/// The `onmouseleave` attribute specifies the event handler for the mouseleave event.
onmouseleave "onmouseleave",
/// The `onmousemove` attribute specifies the event handler for the mousemove event.
onmousemove "onmousemove",
/// The `onmouseout` attribute specifies the event handler for the mouseout event.
onmouseout "onmouseout",
/// The `onmouseover` attribute specifies the event handler for the mouseover event.
onmouseover "onmouseover",
/// The `onmouseup` attribute specifies the event handler for the mouseup event.
onmouseup "onmouseup",
/// The `onpause` attribute specifies the event handler for the pause event.
onpause "onpause",
/// The `onplay` attribute specifies the event handler for the play event.
onplay "onplay",
/// The `onplaying` attribute specifies the event handler for the playing event.
onplaying "onplaying",
/// The `onprogress` attribute specifies the event handler for the progress event.
onprogress "onprogress",
/// The `onratechange` attribute specifies the event handler for the ratechange event.
onratechange "onratechange",
/// The `onreset` attribute specifies the event handler for the reset event.
onreset "onreset",
/// The `onresize` attribute specifies the event handler for the resize event.
onresize "onresize",
/// The `onscroll` attribute specifies the event handler for the scroll event.
onscroll "onscroll",
/// The `onsecuritypolicyviolation` attribute specifies the event handler for the securitypolicyviolation event.
onsecuritypolicyviolation "onsecuritypolicyviolation",
/// The `onseeked` attribute specifies the event handler for the seeked event.
onseeked "onseeked",
/// The `onseeking` attribute specifies the event handler for the seeking event.
onseeking "onseeking",
/// The `onselect` attribute specifies the event handler for the select event.
onselect "onselect",
/// The `onslotchange` attribute specifies the event handler for the slotchange event.
onslotchange "onslotchange",
/// The `onstalled` attribute specifies the event handler for the stalled event.
onstalled "onstalled",
/// The `onsubmit` attribute specifies the event handler for the submit event.
onsubmit "onsubmit",
/// The `onsuspend` attribute specifies the event handler for the suspend event.
onsuspend "onsuspend",
/// The `ontimeupdate` attribute specifies the event handler for the timeupdate event.
ontimeupdate "ontimeupdate",
/// The `ontoggle` attribute specifies the event handler for the toggle event.
ontoggle "ontoggle",
/// The `onvolumechange` attribute specifies the event handler for the volumechange event.
onvolumechange "onvolumechange",
/// The `onwaiting` attribute specifies the event handler for the waiting event.
onwaiting "onwaiting",
/// The `onwebkitanimationend` attribute specifies the event handler for the webkitanimationend event.
onwebkitanimationend "onwebkitanimationend",
/// The `onwebkitanimationiteration` attribute specifies the event handler for the webkitanimationiteration event.
onwebkitanimationiteration "onwebkitanimationiteration",
/// The `onwebkitanimationstart` attribute specifies the event handler for the webkitanimationstart event.
onwebkitanimationstart "onwebkitanimationstart",
/// The `onwebkittransitionend` attribute specifies the event handler for the webkittransitionend event.
onwebkittransitionend "onwebkittransitionend",
/// The `onwheel` attribute specifies the event handler for the wheel event.
onwheel "onwheel",
}
}
impl<El, At, Ch, V> GlobalOnAttributes<V> for HtmlElement<El, At, Ch>
where
El: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
V: AttributeValue,
{
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/aria.rs | tachys/src/html/attribute/aria.rs | use crate::{
html::{
attribute::{Attr, *},
element::{ElementType, HtmlElement},
},
renderer::Rndr,
view::{add_attr::AddAnyAttr, RenderHtml},
};
/// Applies ARIA attributes to an HTML element.
pub trait AriaAttributes<Rndr, V>
where
Self: Sized + AddAnyAttr,
V: AttributeValue,
{
/// Identifies the currently active descendant of a composite widget.
fn aria_activedescendant(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaActivedescendant, V>> {
self.add_any_attr(aria_activedescendant(value))
}
/// Indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the `aria-relevant` attribute.
fn aria_atomic(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaAtomic, V>> {
self.add_any_attr(aria_atomic(value))
}
/// Indicates whether user input completion suggestions are provided.
fn aria_autocomplete(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaAutocomplete, V>> {
self.add_any_attr(aria_autocomplete(value))
}
/// Indicates whether an element, and its subtree, are currently being updated.
fn aria_busy(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaBusy, V>> {
self.add_any_attr(aria_busy(value))
}
/// Indicates the current "checked" state of checkboxes, radio buttons, and other widgets.
fn aria_checked(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaChecked, V>> {
self.add_any_attr(aria_checked(value))
}
/// Defines the number of columns in a table, grid, or treegrid.
fn aria_colcount(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaColcount, V>> {
self.add_any_attr(aria_colcount(value))
}
/// Defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.
fn aria_colindex(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaColindex, V>> {
self.add_any_attr(aria_colindex(value))
}
/// Defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.
fn aria_colspan(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaColspan, V>> {
self.add_any_attr(aria_colspan(value))
}
/// Identifies the element (or elements) whose contents or presence are controlled by the current element.
fn aria_controls(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaControls, V>> {
self.add_any_attr(aria_controls(value))
}
/// Indicates the element that represents the current item within a container or set of related elements.
fn aria_current(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaCurrent, V>> {
self.add_any_attr(aria_current(value))
}
/// Identifies the element (or elements) that describes the object.
fn aria_describedby(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaDescribedby, V>> {
self.add_any_attr(aria_describedby(value))
}
/// Defines a string value that describes or annotates the current element.
fn aria_description(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaDescription, V>> {
self.add_any_attr(aria_description(value))
}
/// Identifies the element that provides additional information related to the object.
fn aria_details(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaDetails, V>> {
self.add_any_attr(aria_details(value))
}
/// Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.
fn aria_disabled(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaDisabled, V>> {
self.add_any_attr(aria_disabled(value))
}
/// Indicates what functions can be performed when a dragged object is released on the drop target.
fn aria_dropeffect(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaDropeffect, V>> {
self.add_any_attr(aria_dropeffect(value))
}
/// Defines the element that provides an error message related to the object.
fn aria_errormessage(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaErrormessage, V>> {
self.add_any_attr(aria_errormessage(value))
}
/// Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed.
fn aria_expanded(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaExpanded, V>> {
self.add_any_attr(aria_expanded(value))
}
/// Identifies the next element (or elements) in an alternate reading order of content.
fn aria_flowto(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaFlowto, V>> {
self.add_any_attr(aria_flowto(value))
}
/// Indicates an element's "grabbed" state in a drag-and-drop operation.
fn aria_grabbed(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaGrabbed, V>> {
self.add_any_attr(aria_grabbed(value))
}
/// Indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.
fn aria_haspopup(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaHaspopup, V>> {
self.add_any_attr(aria_haspopup(value))
}
/// Indicates whether the element is exposed to an accessibility API.
fn aria_hidden(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaHidden, V>> {
self.add_any_attr(aria_hidden(value))
}
/// Indicates the entered value does not conform to the format expected by the application.
fn aria_invalid(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaInvalid, V>> {
self.add_any_attr(aria_invalid(value))
}
/// Indicates keyboard shortcuts that an author has implemented to activate or give focus to an element.
fn aria_keyshortcuts(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaKeyshortcuts, V>> {
self.add_any_attr(aria_keyshortcuts(value))
}
/// Defines a string value that labels the current element.
fn aria_label(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaLabel, V>> {
self.add_any_attr(aria_label(value))
}
/// Identifies the element (or elements) that labels the current element.
fn aria_labelledby(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaLabelledby, V>> {
self.add_any_attr(aria_labelledby(value))
}
/// Indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.
fn aria_live(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaLive, V>> {
self.add_any_attr(aria_live(value))
}
/// Indicates whether an element is modal when displayed.
fn aria_modal(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaModal, V>> {
self.add_any_attr(aria_modal(value))
}
/// Indicates whether a text box accepts multiple lines of input or only a single line.
fn aria_multiline(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaMultiline, V>> {
self.add_any_attr(aria_multiline(value))
}
/// Indicates that the user may select more than one item from the current selectable descendants.
fn aria_multiselectable(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaMultiselectable, V>> {
self.add_any_attr(aria_multiselectable(value))
}
/// Indicates whether the element's orientation is horizontal, vertical, or undefined.
fn aria_orientation(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaOrientation, V>> {
self.add_any_attr(aria_orientation(value))
}
/// Identifies an element (or elements) in order to define a visual, functional, or contextual parent/child relationship between DOM elements where the DOM hierarchy cannot be used to represent the relationship.
fn aria_owns(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaOwns, V>> {
self.add_any_attr(aria_owns(value))
}
/// Defines a short hint (a word or short phrase) intended to help the user with data entry when the control has no value.
fn aria_placeholder(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaPlaceholder, V>> {
self.add_any_attr(aria_placeholder(value))
}
/// Defines an element's number or position in the current set of listitems or treeitems.
fn aria_posinset(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaPosinset, V>> {
self.add_any_attr(aria_posinset(value))
}
/// Indicates the current "pressed" state of toggle buttons.
fn aria_pressed(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaPressed, V>> {
self.add_any_attr(aria_pressed(value))
}
/// Indicates that the element is not editable, but is otherwise operable.
fn aria_readonly(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaReadonly, V>> {
self.add_any_attr(aria_readonly(value))
}
/// Indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified.
fn aria_relevant(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaRelevant, V>> {
self.add_any_attr(aria_relevant(value))
}
/// Indicates that user input is required on the element before a form may be submitted.
fn aria_required(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaRequired, V>> {
self.add_any_attr(aria_required(value))
}
/// Defines a human-readable, author-localized description for the role of an element.
fn aria_roledescription(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaRoledescription, V>> {
self.add_any_attr(aria_roledescription(value))
}
/// Defines the total number of rows in a table, grid, or treegrid.
fn aria_rowcount(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaRowcount, V>> {
self.add_any_attr(aria_rowcount(value))
}
/// Defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.
fn aria_rowindex(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaRowindex, V>> {
self.add_any_attr(aria_rowindex(value))
}
/// Defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.
fn aria_rowspan(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaRowspan, V>> {
self.add_any_attr(aria_rowspan(value))
}
/// Indicates the current "selected" state of various widgets.
fn aria_selected(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaSelected, V>> {
self.add_any_attr(aria_selected(value))
}
/// Defines the number of items in the current set of listitems or treeitems.
fn aria_setsize(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaSetsize, V>> {
self.add_any_attr(aria_setsize(value))
}
/// Indicates if items in a table or grid are sorted in ascending or descending order.
fn aria_sort(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaSort, V>> {
self.add_any_attr(aria_sort(value))
}
/// Defines the maximum allowed value for a range widget.
fn aria_valuemax(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaValuemax, V>> {
self.add_any_attr(aria_valuemax(value))
}
/// Defines the minimum allowed value for a range widget.
fn aria_valuemin(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaValuemin, V>> {
self.add_any_attr(aria_valuemin(value))
}
/// Defines the current value for a range widget.
fn aria_valuenow(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaValuenow, V>> {
self.add_any_attr(aria_valuenow(value))
}
/// Defines the human-readable text alternative of `aria-valuenow` for a range widget.
fn aria_valuetext(
self,
value: V,
) -> <Self as AddAnyAttr>::Output<Attr<AriaValuetext, V>> {
self.add_any_attr(aria_valuetext(value))
}
}
impl<El, At, Ch, V> AriaAttributes<Rndr, V> for HtmlElement<El, At, Ch>
where
El: ElementType + Send,
At: Attribute + Send,
Ch: RenderHtml + Send,
V: AttributeValue,
{
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/any_attribute.rs | tachys/src/html/attribute/any_attribute.rs | use super::{Attribute, NextAttribute};
use crate::{
erased::{Erased, ErasedLocal},
html::attribute::NamedAttributeKey,
renderer::{dom::Element, Rndr},
};
use std::{any::TypeId, fmt::Debug, mem};
#[cfg(feature = "ssr")]
use std::{future::Future, pin::Pin};
/// A type-erased container for any [`Attribute`].
pub struct AnyAttribute {
type_id: TypeId,
html_len: usize,
value: Erased,
clone: fn(&Erased) -> AnyAttribute,
#[cfg(feature = "ssr")]
to_html: fn(Erased, &mut String, &mut String, &mut String, &mut String),
build: fn(Erased, el: crate::renderer::types::Element) -> AnyAttributeState,
rebuild: fn(Erased, &mut AnyAttributeState),
#[cfg(feature = "hydrate")]
hydrate_from_server:
fn(Erased, crate::renderer::types::Element) -> AnyAttributeState,
#[cfg(feature = "hydrate")]
hydrate_from_template:
fn(Erased, crate::renderer::types::Element) -> AnyAttributeState,
#[cfg(feature = "ssr")]
#[allow(clippy::type_complexity)]
resolve: fn(Erased) -> Pin<Box<dyn Future<Output = AnyAttribute> + Send>>,
#[cfg(feature = "ssr")]
dry_resolve: fn(&mut Erased),
keys: fn(&Erased) -> Vec<NamedAttributeKey>,
}
impl Clone for AnyAttribute {
fn clone(&self) -> Self {
(self.clone)(&self.value)
}
}
impl Debug for AnyAttribute {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnyAttribute").finish_non_exhaustive()
}
}
/// View state for [`AnyAttribute`].
pub struct AnyAttributeState {
type_id: TypeId,
state: ErasedLocal,
el: crate::renderer::types::Element,
keys: Vec<NamedAttributeKey>,
}
/// Converts an [`Attribute`] into [`AnyAttribute`].
pub trait IntoAnyAttribute {
/// Wraps the given attribute.
fn into_any_attr(self) -> AnyAttribute;
}
impl<T> IntoAnyAttribute for T
where
Self: Send,
T: Attribute,
crate::renderer::types::Element: Clone,
{
fn into_any_attr(self) -> AnyAttribute {
fn clone<T: Attribute + Clone + 'static>(
value: &Erased,
) -> AnyAttribute {
value.get_ref::<T>().clone().into_any_attr()
}
#[cfg(feature = "ssr")]
fn to_html<T: Attribute + 'static>(
value: Erased,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
) {
value
.into_inner::<T>()
.to_html(buf, class, style, inner_html);
}
fn build<T: Attribute + 'static>(
value: Erased,
el: crate::renderer::types::Element,
) -> AnyAttributeState {
AnyAttributeState {
type_id: TypeId::of::<T>(),
keys: value.get_ref::<T>().keys(),
state: ErasedLocal::new(value.into_inner::<T>().build(&el)),
el,
}
}
#[cfg(feature = "hydrate")]
fn hydrate_from_server<T: Attribute + 'static>(
value: Erased,
el: crate::renderer::types::Element,
) -> AnyAttributeState {
AnyAttributeState {
type_id: TypeId::of::<T>(),
keys: value.get_ref::<T>().keys(),
state: ErasedLocal::new(
value.into_inner::<T>().hydrate::<true>(&el),
),
el,
}
}
#[cfg(feature = "hydrate")]
fn hydrate_from_template<T: Attribute + 'static>(
value: Erased,
el: crate::renderer::types::Element,
) -> AnyAttributeState {
AnyAttributeState {
type_id: TypeId::of::<T>(),
keys: value.get_ref::<T>().keys(),
state: ErasedLocal::new(
value.into_inner::<T>().hydrate::<true>(&el),
),
el,
}
}
fn rebuild<T: Attribute + 'static>(
value: Erased,
state: &mut AnyAttributeState,
) {
let value = value.into_inner::<T>();
let state = state.state.get_mut::<T::State>();
value.rebuild(state);
}
#[cfg(feature = "ssr")]
fn dry_resolve<T: Attribute + 'static>(value: &mut Erased) {
value.get_mut::<T>().dry_resolve();
}
#[cfg(feature = "ssr")]
fn resolve<T: Attribute + 'static>(
value: Erased,
) -> Pin<Box<dyn Future<Output = AnyAttribute> + Send>> {
use futures::FutureExt;
async move {value.into_inner::<T>().resolve().await.into_any_attr()}.boxed()
}
fn keys<T: Attribute + 'static>(
value: &Erased,
) -> Vec<NamedAttributeKey> {
value.get_ref::<T>().keys()
}
let value = self.into_cloneable_owned();
AnyAttribute {
type_id: TypeId::of::<T::CloneableOwned>(),
html_len: value.html_len(),
value: Erased::new(value),
clone: clone::<T::CloneableOwned>,
#[cfg(feature = "ssr")]
to_html: to_html::<T::CloneableOwned>,
build: build::<T::CloneableOwned>,
rebuild: rebuild::<T::CloneableOwned>,
#[cfg(feature = "hydrate")]
hydrate_from_server: hydrate_from_server::<T::CloneableOwned>,
#[cfg(feature = "hydrate")]
hydrate_from_template: hydrate_from_template::<T::CloneableOwned>,
#[cfg(feature = "ssr")]
resolve: resolve::<T::CloneableOwned>,
#[cfg(feature = "ssr")]
dry_resolve: dry_resolve::<T::CloneableOwned>,
keys: keys::<T::CloneableOwned>,
}
}
}
impl NextAttribute for AnyAttribute {
type Output<NewAttr: Attribute> = Vec<AnyAttribute>;
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
vec![self, new_attr.into_any_attr()]
}
}
impl Attribute for AnyAttribute {
const MIN_LENGTH: usize = 0;
type AsyncOutput = AnyAttribute;
type State = AnyAttributeState;
type Cloneable = AnyAttribute;
type CloneableOwned = AnyAttribute;
fn html_len(&self) -> usize {
self.html_len
}
#[allow(unused)] // they are used in SSR
fn to_html(
self,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
) {
#[cfg(feature = "ssr")]
{
(self.to_html)(self.value, buf, class, style, inner_html);
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyAttribute to HTML without the `ssr` feature \
enabled."
);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
#[cfg(feature = "hydrate")]
if FROM_SERVER {
(self.hydrate_from_server)(self.value, el.clone())
} else {
(self.hydrate_from_template)(self.value, el.clone())
}
#[cfg(not(feature = "hydrate"))]
{
_ = el;
panic!(
"You are trying to hydrate AnyAttribute without the `hydrate` \
feature enabled."
);
}
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
(self.build)(self.value, el.clone())
}
fn rebuild(self, state: &mut Self::State) {
if self.type_id == state.type_id {
(self.rebuild)(self.value, state)
} else {
let new = self.build(&state.el);
*state = new;
}
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self
}
fn dry_resolve(&mut self) {
#[cfg(feature = "ssr")]
{
(self.dry_resolve)(&mut self.value)
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyAttribute to HTML without the `ssr` feature \
enabled."
);
}
async fn resolve(self) -> Self::AsyncOutput {
#[cfg(feature = "ssr")]
{
(self.resolve)(self.value).await
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyAttribute to HTML without the `ssr` feature \
enabled."
);
}
fn keys(&self) -> Vec<NamedAttributeKey> {
(self.keys)(&self.value)
}
}
impl NextAttribute for Vec<AnyAttribute> {
type Output<NewAttr: Attribute> = Self;
fn add_any_attr<NewAttr: Attribute>(
mut self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
self.push(new_attr.into_any_attr());
self
}
}
impl Attribute for Vec<AnyAttribute> {
const MIN_LENGTH: usize = 0;
type AsyncOutput = Vec<AnyAttribute>;
type State = (Element, Vec<AnyAttributeState>);
type Cloneable = Vec<AnyAttribute>;
type CloneableOwned = Vec<AnyAttribute>;
fn html_len(&self) -> usize {
self.iter().map(|attr| attr.html_len()).sum()
}
#[allow(unused)] // they are used in SSR
fn to_html(
self,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
) {
#[cfg(feature = "ssr")]
{
for mut attr in self {
attr.to_html(buf, class, style, inner_html)
}
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyAttribute to HTML without the `ssr` feature \
enabled."
);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
#[cfg(feature = "hydrate")]
if FROM_SERVER {
(
el.clone(),
self.into_iter()
.map(|attr| attr.hydrate::<true>(el))
.collect(),
)
} else {
(
el.clone(),
self.into_iter()
.map(|attr| attr.hydrate::<false>(el))
.collect(),
)
}
#[cfg(not(feature = "hydrate"))]
{
_ = el;
panic!(
"You are trying to hydrate AnyAttribute without the `hydrate` \
feature enabled."
);
}
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
(
el.clone(),
self.into_iter().map(|attr| attr.build(el)).collect(),
)
}
fn rebuild(self, state: &mut Self::State) {
let (el, state) = state;
for old in mem::take(state) {
for key in old.keys {
match key {
NamedAttributeKey::InnerHtml => {
Rndr::set_inner_html(&old.el, "");
}
NamedAttributeKey::Property(prop_name) => {
Rndr::set_property(
&old.el,
&prop_name,
&wasm_bindgen::JsValue::UNDEFINED,
);
}
NamedAttributeKey::Attribute(key) => {
Rndr::remove_attribute(&old.el, &key);
}
}
}
}
*state = self.into_iter().map(|s| s.build(el)).collect();
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self
}
fn dry_resolve(&mut self) {
#[cfg(feature = "ssr")]
{
for attr in self.iter_mut() {
attr.dry_resolve()
}
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyAttribute to HTML without the `ssr` feature \
enabled."
);
}
async fn resolve(self) -> Self::AsyncOutput {
#[cfg(feature = "ssr")]
{
futures::future::join_all(
self.into_iter().map(|attr| attr.resolve()),
)
.await
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyAttribute to HTML without the `ssr` feature \
enabled."
);
}
fn keys(&self) -> Vec<NamedAttributeKey> {
self.iter().flat_map(|s| s.keys()).collect()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/value.rs | tachys/src/html/attribute/value.rs | use crate::renderer::Rndr;
use std::{
borrow::Cow,
future::Future,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8,
NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64,
NonZeroU8, NonZeroUsize,
},
sync::Arc,
};
/// Declares that this type can be converted into some other type, which is a valid attribute value.
pub trait IntoAttributeValue {
/// The attribute value into which this type can be converted.
type Output;
/// Consumes this value, transforming it into an attribute value.
fn into_attribute_value(self) -> Self::Output;
}
impl<T> IntoAttributeValue for T
where
T: AttributeValue,
{
type Output = Self;
fn into_attribute_value(self) -> Self::Output {
self
}
}
/// A possible value for an HTML attribute.
pub trait AttributeValue: Send {
/// The state that should be retained between building and rebuilding.
type State;
/// The type once all async data have loaded.
type AsyncOutput: AttributeValue;
/// A version of the value that can be cloned. This can be the same type, or a
/// reference-counted type. Generally speaking, this does *not* need to refer to the same data,
/// but should behave in the same way. So for example, making an event handler cloneable should
/// probably make it reference-counted (so that a `FnMut()` continues mutating the same
/// closure), but making a `String` cloneable does not necessarily need to make it an
/// `Arc<str>`, as two different clones of a `String` will still have the same value.
type Cloneable: AttributeValue + Clone;
/// A cloneable type that is also `'static`. This is used for spreading across types when the
/// spreadable attribute needs to be owned. In some cases (`&'a str` to `Arc<str>`, etc.) the owned
/// cloneable type has worse performance than the cloneable type, so they are separate.
type CloneableOwned: AttributeValue + Clone + 'static;
/// An approximation of the actual length of this attribute in HTML.
fn html_len(&self) -> usize;
/// Renders the attribute value to HTML.
fn to_html(self, key: &str, buf: &mut String);
/// Renders the attribute value to HTML for a `<template>`.
fn to_template(key: &str, buf: &mut String);
/// Adds interactivity as necessary, given DOM nodes that were created from HTML that has
/// either been rendered on the server, or cloned for a `<template>`.
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State;
/// Adds this attribute to the element during client-side rendering.
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State;
/// Applies a new value for the attribute.
fn rebuild(self, key: &str, state: &mut Self::State);
/// Converts this attribute into an equivalent that can be cloned.
fn into_cloneable(self) -> Self::Cloneable;
/// Converts this attributes into an equivalent that can be cloned and is `'static`.
fn into_cloneable_owned(self) -> Self::CloneableOwned;
/// “Runs” the attribute without other side effects. For primitive types, this is a no-op. For
/// reactive types, this can be used to gather data about reactivity or about asynchronous data
/// that needs to be loaded.
fn dry_resolve(&mut self);
/// “Resolves” this into a form that is not waiting for any asynchronous data.
fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send;
}
impl AttributeValue for () {
type State = ();
type AsyncOutput = ();
type Cloneable = ();
type CloneableOwned = ();
fn html_len(&self) -> usize {
0
}
fn to_html(self, _key: &str, _buf: &mut String) {}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
_key: &str,
_el: &crate::renderer::types::Element,
) {
}
fn build(
self,
_el: &crate::renderer::types::Element,
_key: &str,
) -> Self::State {
}
fn rebuild(self, _key: &str, _state: &mut Self::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) {}
}
impl<'a> AttributeValue for &'a str {
type State = (crate::renderer::types::Element, &'a str);
type AsyncOutput = &'a str;
type Cloneable = &'a str;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, key: &str, buf: &mut String) {
buf.push(' ');
buf.push_str(key);
buf.push_str("=\"");
buf.push_str(&escape_attr(self));
buf.push('"');
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
// if we're actually hydrating from SSRed HTML, we don't need to set the attribute
// if we're hydrating from a CSR-cloned <template>, we do need to set non-StaticAttr attributes
if !FROM_SERVER {
Rndr::set_attribute(el, key, self);
}
(el.clone(), self)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
Rndr::set_attribute(el, key, self);
(el.to_owned(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
Rndr::set_attribute(el, key, self);
}
*prev_value = self;
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl<'a> AttributeValue for Cow<'a, str> {
type State = (crate::renderer::types::Element, Self);
type AsyncOutput = Self;
type Cloneable = Arc<str>;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, key: &str, buf: &mut String) {
buf.push(' ');
buf.push_str(key);
buf.push_str("=\"");
buf.push_str(&escape_attr(&self));
buf.push('"');
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
// if we're actually hydrating from SSRed HTML, we don't need to set the attribute
// if we're hydrating from a CSR-cloned <template>, we do need to set non-StaticAttr attributes
if !FROM_SERVER {
Rndr::set_attribute(el, key, &self);
}
(el.clone(), self)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
Rndr::set_attribute(el, key, &self);
(el.to_owned(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
Rndr::set_attribute(el, key, &self);
}
*prev_value = self;
}
fn into_cloneable(self) -> Self::Cloneable {
self.into()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
#[cfg(all(feature = "nightly", rustc_nightly))]
impl<const V: &'static str> AttributeValue
for crate::view::static_types::Static<V>
{
type AsyncOutput = Self;
type State = ();
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
V.len()
}
fn to_html(self, key: &str, buf: &mut String) {
<&str as AttributeValue>::to_html(V, key, buf);
}
fn to_template(key: &str, buf: &mut String) {
buf.push(' ');
buf.push_str(key);
buf.push_str("=\"");
buf.push_str(V);
buf.push('"');
}
fn hydrate<const FROM_SERVER: bool>(
self,
_key: &str,
_el: &crate::renderer::types::Element,
) -> Self::State {
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
<&str as AttributeValue>::build(V, el, key);
}
fn rebuild(self, _key: &str, _state: &mut Self::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
}
}
impl<'a> AttributeValue for &'a String {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, &'a String);
type Cloneable = Self;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, key: &str, buf: &mut String) {
<&str as AttributeValue>::to_html(self.as_str(), key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
let (el, _) = <&str as AttributeValue>::hydrate::<FROM_SERVER>(
self.as_str(),
key,
el,
);
(el, self)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
Rndr::set_attribute(el, key, self);
(el.clone(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
Rndr::set_attribute(el, key, self);
}
*prev_value = self;
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.as_str().into()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl AttributeValue for String {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, String);
type Cloneable = Arc<str>;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, key: &str, buf: &mut String) {
<&str as AttributeValue>::to_html(self.as_str(), key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
let (el, _) = <&str as AttributeValue>::hydrate::<FROM_SERVER>(
self.as_str(),
key,
el,
);
(el, self)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
Rndr::set_attribute(el, key, &self);
(el.clone(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
Rndr::set_attribute(el, key, &self);
}
*prev_value = self;
}
fn into_cloneable(self) -> Self::Cloneable {
self.into()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl AttributeValue for Arc<str> {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, Arc<str>);
type Cloneable = Arc<str>;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, key: &str, buf: &mut String) {
<&str as AttributeValue>::to_html(self.as_ref(), key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
let (el, _) = <&str as AttributeValue>::hydrate::<FROM_SERVER>(
self.as_ref(),
key,
el,
);
(el, self)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
Rndr::set_attribute(el, key, &self);
(el.clone(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
Rndr::set_attribute(el, key, &self);
}
*prev_value = self;
}
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
}
}
// TODO impl AttributeValue for Rc<str> and Arc<str> too
impl AttributeValue for bool {
type AsyncOutput = Self;
type State = (crate::renderer::types::Element, bool);
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
0
}
fn to_html(self, key: &str, buf: &mut String) {
if self {
buf.push(' ');
buf.push_str(key);
}
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
// if we're actually hydrating from SSRed HTML, we don't need to set the attribute
// if we're hydrating from a CSR-cloned <template>, we do need to set non-StaticAttr attributes
if !FROM_SERVER {
Rndr::set_attribute(el, key, "");
}
(el.clone(), self)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
if self {
Rndr::set_attribute(el, key, "");
}
(el.clone(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
if self {
Rndr::set_attribute(el, key, "");
} else {
Rndr::remove_attribute(el, key);
}
}
*prev_value = self;
}
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
}
}
impl<V> AttributeValue for Option<V>
where
V: AttributeValue,
{
type AsyncOutput = Option<V::AsyncOutput>;
type State = (crate::renderer::types::Element, Option<V::State>);
type Cloneable = Option<V::Cloneable>;
type CloneableOwned = Option<V::CloneableOwned>;
fn html_len(&self) -> usize {
match self {
Some(i) => i.html_len(),
None => 0,
}
}
fn to_html(self, key: &str, buf: &mut String) {
if let Some(v) = self {
v.to_html(key, buf);
}
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
let state = self.map(|v| v.hydrate::<FROM_SERVER>(key, el));
(el.clone(), state)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
let el = el.clone();
let v = self.map(|v| v.build(&el, key));
(el, v)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev) = state;
match (self, prev.as_mut()) {
(None, None) => {}
(None, Some(_)) => {
Rndr::remove_attribute(el, key);
*prev = None;
}
(Some(value), None) => {
*prev = Some(value.build(el, key));
}
(Some(new), Some(old)) => {
new.rebuild(key, old);
}
}
}
fn into_cloneable(self) -> Self::Cloneable {
self.map(|value| value.into_cloneable())
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.map(|value| value.into_cloneable_owned())
}
fn dry_resolve(&mut self) {
if let Some(inner) = self.as_mut() {
inner.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
match self {
None => None,
Some(inner) => Some(inner.resolve().await),
}
}
}
pub(crate) fn escape_attr(value: &str) -> Cow<'_, str> {
html_escape::encode_double_quoted_attribute(value)
}
macro_rules! render_primitive {
($($child_type:ty),* $(,)?) => {
$(
impl AttributeValue for $child_type
where
{
type AsyncOutput = $child_type;
type State = (crate::renderer::types::Element, $child_type);
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
0
}
fn to_html(self, key: &str, buf: &mut String) {
<String as AttributeValue>::to_html(self.to_string(), key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
// if we're actually hydrating from SSRed HTML, we don't need to set the attribute
// if we're hydrating from a CSR-cloned <template>, we do need to set non-StaticAttr attributes
if !FROM_SERVER {
Rndr::set_attribute(el, key, &self.to_string());
}
(el.clone(), self)
}
fn build(self, el: &crate::renderer::types::Element, key: &str) -> Self::State {
Rndr::set_attribute(el, key, &self.to_string());
(el.to_owned(), self)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let (el, prev_value) = state;
if self != *prev_value {
Rndr::set_attribute(el, key, &self.to_string());
}
*prev_value = self;
}
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
}
}
)*
}
}
render_primitive![
usize,
u8,
u16,
u32,
u64,
u128,
isize,
i8,
i16,
i32,
i64,
i128,
f32,
f64,
char,
IpAddr,
SocketAddr,
SocketAddrV4,
SocketAddrV6,
Ipv4Addr,
Ipv6Addr,
NonZeroI8,
NonZeroU8,
NonZeroI16,
NonZeroU16,
NonZeroI32,
NonZeroU32,
NonZeroI64,
NonZeroU64,
NonZeroI128,
NonZeroU128,
NonZeroIsize,
NonZeroUsize,
];
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/mod.rs | tachys/src/html/attribute/mod.rs | /// A type-erased `AnyAttribute`.
pub mod any_attribute;
/// Types for ARIA attributes.
pub mod aria;
/// Types for custom attributes.
pub mod custom;
/// Traits to define global attribute methods on all HTML elements.
pub mod global;
mod key;
pub(crate) mod maybe_next_attr_erasure_macros;
mod value;
use crate::view::{Position, ToTemplate};
pub use key::*;
use maybe_next_attr_erasure_macros::{
next_attr_combine, next_attr_output_type,
};
use std::{borrow::Cow, fmt::Debug, future::Future};
pub use value::*;
/// Defines an attribute: anything that can modify an element.
pub trait Attribute: NextAttribute + Send {
/// The minimum length of this attribute in HTML.
const MIN_LENGTH: usize;
/// The state that should be retained between building and rebuilding.
type State;
/// The type once all async data have loaded.
type AsyncOutput: Attribute;
/// An equivalent to this attribute that can be cloned to be shared across elements.
type Cloneable: Attribute + Clone;
/// An equivalent to this attribute that can be cloned to be shared across elements, and
/// captures no references shorter than `'static`.
type CloneableOwned: Attribute + Clone + 'static;
/// An approximation of the actual length of this attribute in HTML.
fn html_len(&self) -> usize;
/// Renders the attribute to HTML.
///
/// This separates a general buffer for attribute values from the `class` and `style`
/// attributes, so that multiple classes or styles can be combined, and also allows for an
/// `inner_html` attribute that sets the child HTML instead of an attribute.
fn to_html(
self,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
);
/// Adds interactivity as necessary, given DOM nodes that were created from HTML that has
/// either been rendered on the server, or cloned for a `<template>`.
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State;
/// Adds this attribute to the element during client-side rendering.
fn build(self, el: &crate::renderer::types::Element) -> Self::State;
/// Applies a new value for the attribute.
fn rebuild(self, state: &mut Self::State);
/// Converts this attribute into an equivalent that can be cloned.
fn into_cloneable(self) -> Self::Cloneable;
/// Converts this attributes into an equivalent that can be cloned and is `'static`.
fn into_cloneable_owned(self) -> Self::CloneableOwned;
/// “Runs” the attribute without other side effects. For primitive types, this is a no-op. For
/// reactive types, this can be used to gather data about reactivity or about asynchronous data
/// that needs to be loaded.
fn dry_resolve(&mut self);
/// “Resolves” this into a type that is not waiting for any asynchronous data.
fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send;
/// Returns a set of attribute keys, associated with this attribute, if any.
///
/// This is only used to manage the removal of type-erased attributes, when needed.
fn keys(&self) -> Vec<NamedAttributeKey> {
// TODO: remove default implementation in 0.9, or fix this whole approach
// by making it easier to remove attributes
vec![]
}
}
/// An attribute key can be used to remove an attribute from an element.
pub enum NamedAttributeKey {
/// An ordinary attribute.
Attribute(Cow<'static, str>),
/// A DOM property.
Property(Cow<'static, str>),
/// The `inner_html` pseudo-attribute.
InnerHtml,
}
/// Adds another attribute to this one, returning a new attribute.
///
/// This is typically achieved by creating or extending a tuple of attributes.
pub trait NextAttribute {
/// The type of the new, combined attribute.
type Output<NewAttr: Attribute>: Attribute;
/// Adds a new attribute.
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr>;
}
impl Attribute for () {
const MIN_LENGTH: usize = 0;
type State = ();
type AsyncOutput = ();
type Cloneable = ();
type CloneableOwned = ();
fn html_len(&self) -> usize {
0
}
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
}
fn hydrate<const FROM_SERVER: bool>(
self,
_el: &crate::renderer::types::Element,
) -> Self::State {
}
fn build(self, _el: &crate::renderer::types::Element) -> Self::State {}
fn rebuild(self, _state: &mut Self::State) {}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::Cloneable {
self
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {}
fn keys(&self) -> Vec<NamedAttributeKey> {
vec![]
}
}
impl NextAttribute for () {
#[cfg(not(erase_components))]
type Output<NewAttr: Attribute> = (NewAttr,);
#[cfg(erase_components)]
type Output<NewAttr: Attribute> =
Vec<crate::html::attribute::any_attribute::AnyAttribute>;
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
#[cfg(not(erase_components))]
{
(new_attr,)
}
#[cfg(erase_components)]
{
use crate::html::attribute::any_attribute::IntoAnyAttribute;
vec![new_attr.into_any_attr()]
}
}
}
/// An attribute with a key and value.
#[derive(Debug)]
pub struct Attr<K, V>(pub K, pub V)
where
K: AttributeKey,
V: AttributeValue;
impl<K, V> Clone for Attr<K, V>
where
K: AttributeKey,
V: AttributeValue + Clone,
{
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<K, V> ToTemplate for Attr<K, V>
where
K: AttributeKey,
V: AttributeValue,
{
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
V::to_template(K::KEY, buf);
}
}
impl<K, V> Attribute for Attr<K, V>
where
K: AttributeKey + Send,
V: AttributeValue + Send,
{
const MIN_LENGTH: usize = 0;
type State = V::State;
type AsyncOutput = Attr<K, V::AsyncOutput>;
type Cloneable = Attr<K, V::Cloneable>;
type CloneableOwned = Attr<K, V::CloneableOwned>;
fn html_len(&self) -> usize {
K::KEY.len() + 3 + self.1.html_len()
}
fn to_html(
self,
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
self.1.to_html(K::KEY, buf);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
self.1.hydrate::<FROM_SERVER>(K::KEY, el)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
V::build(self.1, el, K::KEY)
}
fn rebuild(self, state: &mut Self::State) {
V::rebuild(self.1, K::KEY, state);
}
fn into_cloneable(self) -> Self::Cloneable {
Attr(self.0, self.1.into_cloneable())
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
Attr(self.0, self.1.into_cloneable_owned())
}
fn dry_resolve(&mut self) {
self.1.dry_resolve();
}
async fn resolve(self) -> Self::AsyncOutput {
Attr(self.0, self.1.resolve().await)
}
fn keys(&self) -> Vec<NamedAttributeKey> {
vec![NamedAttributeKey::Attribute(K::KEY.into())]
}
}
impl<K, V> NextAttribute for Attr<K, V>
where
K: AttributeKey,
V: AttributeValue,
{
next_attr_output_type!(Self, NewAttr);
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
next_attr_combine!(self, new_attr)
}
}
macro_rules! impl_attr_for_tuples {
($first:ident, $($ty:ident),* $(,)?) => {
impl<$first, $($ty),*> Attribute for ($first, $($ty,)*)
where
$first: Attribute,
$($ty: Attribute),*,
{
const MIN_LENGTH: usize = $first::MIN_LENGTH $(+ $ty::MIN_LENGTH)*;
type AsyncOutput = ($first::AsyncOutput, $($ty::AsyncOutput,)*);
type State = ($first::State, $($ty::State,)*);
type Cloneable = ($first::Cloneable, $($ty::Cloneable,)*);
type CloneableOwned = ($first::CloneableOwned, $($ty::CloneableOwned,)*);
fn html_len(&self) -> usize {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
$first.html_len() $(+ $ty.html_len())*
}
fn to_html(self, buf: &mut String, class: &mut String, style: &mut String, inner_html: &mut String,) {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
$first.to_html(buf, class, style, inner_html);
$($ty.to_html(buf, class, style, inner_html));*
}
fn hydrate<const FROM_SERVER: bool>(self, el: &crate::renderer::types::Element) -> Self::State {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
(
$first.hydrate::<FROM_SERVER>(el),
$($ty.hydrate::<FROM_SERVER>(el)),*
)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.build(el),
$($ty.build(el)),*
)
}
fn rebuild(self, state: &mut Self::State) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
let ([<view_ $first:lower>], $([<view_ $ty:lower>],)*) = state;
[<$first:lower>].rebuild([<view_ $first:lower>]);
$([<$ty:lower>].rebuild([<view_ $ty:lower>]));*
}
}
fn into_cloneable(self) -> Self::Cloneable {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.into_cloneable(),
$($ty.into_cloneable()),*
)
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.into_cloneable_owned(),
$($ty.into_cloneable_owned()),*
)
}
fn dry_resolve(&mut self) {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
$first.dry_resolve();
$($ty.dry_resolve());*
}
async fn resolve(self) -> Self::AsyncOutput {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
futures::join!(
$first.resolve(),
$($ty.resolve()),*
)
}
fn keys(&self) -> Vec<NamedAttributeKey> {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = &self;
let mut buf = $first.keys();
$(buf.extend($ty.keys());)*
buf
}
}
impl<$first, $($ty),*> NextAttribute for ($first, $($ty,)*)
where
$first: Attribute,
$($ty: Attribute),*,
{
type Output<NewAttr: Attribute> = ($first, $($ty,)* NewAttr);
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
($first, $($ty,)* new_attr)
}
}
};
}
macro_rules! impl_attr_for_tuples_truncate_additional {
($first:ident, $($ty:ident),* $(,)?) => {
impl<$first, $($ty),*> Attribute for ($first, $($ty,)*)
where
$first: Attribute,
$($ty: Attribute),*,
{
const MIN_LENGTH: usize = $first::MIN_LENGTH $(+ $ty::MIN_LENGTH)*;
type AsyncOutput = ($first::AsyncOutput, $($ty::AsyncOutput,)*);
type State = ($first::State, $($ty::State,)*);
type Cloneable = ($first::Cloneable, $($ty::Cloneable,)*);
type CloneableOwned = ($first::CloneableOwned, $($ty::CloneableOwned,)*);
fn html_len(&self) -> usize {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
$first.html_len() $(+ $ty.html_len())*
}
fn to_html(self, buf: &mut String, class: &mut String, style: &mut String, inner_html: &mut String,) {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
$first.to_html(buf, class, style, inner_html);
$($ty.to_html(buf, class, style, inner_html));*
}
fn hydrate<const FROM_SERVER: bool>(self, el: &crate::renderer::types::Element) -> Self::State {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
(
$first.hydrate::<FROM_SERVER>(el),
$($ty.hydrate::<FROM_SERVER>(el)),*
)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.build(el),
$($ty.build(el)),*
)
}
fn rebuild(self, state: &mut Self::State) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
let ([<view_ $first:lower>], $([<view_ $ty:lower>],)*) = state;
[<$first:lower>].rebuild([<view_ $first:lower>]);
$([<$ty:lower>].rebuild([<view_ $ty:lower>]));*
}
}
fn into_cloneable(self) -> Self::Cloneable {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.into_cloneable(),
$($ty.into_cloneable()),*
)
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.into_cloneable_owned(),
$($ty.into_cloneable_owned()),*
)
}
fn dry_resolve(&mut self) {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
$first.dry_resolve();
$($ty.dry_resolve());*
}
async fn resolve(self) -> Self::AsyncOutput {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
futures::join!(
$first.resolve(),
$($ty.resolve()),*
)
}
fn keys(&self) -> Vec<NamedAttributeKey> {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = &self;
let mut buf = $first.keys();
$(buf.extend($ty.keys());)*
buf
}
}
impl<$first, $($ty),*> NextAttribute for ($first, $($ty,)*)
where
$first: Attribute,
$($ty: Attribute),*,
{
type Output<NewAttr: Attribute> = ($first, $($ty,)*);
fn add_any_attr<NewAttr: Attribute>(
self,
_new_attr: NewAttr,
) -> Self::Output<NewAttr> {
todo!("adding more than 26 attributes is not supported");
//($first, $($ty,)*)
}
}
};
}
impl<A> Attribute for (A,)
where
A: Attribute,
{
const MIN_LENGTH: usize = A::MIN_LENGTH;
type AsyncOutput = (A::AsyncOutput,);
type State = A::State;
type Cloneable = (A::Cloneable,);
type CloneableOwned = (A::CloneableOwned,);
fn html_len(&self) -> usize {
self.0.html_len()
}
fn to_html(
self,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
) {
self.0.to_html(buf, class, style, inner_html);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
self.0.hydrate::<FROM_SERVER>(el)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
self.0.build(el)
}
fn rebuild(self, state: &mut Self::State) {
self.0.rebuild(state);
}
fn into_cloneable(self) -> Self::Cloneable {
(self.0.into_cloneable(),)
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
(self.0.into_cloneable_owned(),)
}
fn dry_resolve(&mut self) {
self.0.dry_resolve();
}
async fn resolve(self) -> Self::AsyncOutput {
(self.0.resolve().await,)
}
fn keys(&self) -> Vec<NamedAttributeKey> {
self.0.keys()
}
}
impl<A> NextAttribute for (A,)
where
A: Attribute,
{
next_attr_output_type!(A, NewAttr);
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
next_attr_combine!(self.0, new_attr)
}
}
impl_attr_for_tuples!(A, B);
impl_attr_for_tuples!(A, B, C);
impl_attr_for_tuples!(A, B, C, D);
impl_attr_for_tuples!(A, B, C, D, E);
impl_attr_for_tuples!(A, B, C, D, E, F);
impl_attr_for_tuples!(A, B, C, D, E, F, G);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_attr_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X
);
impl_attr_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
impl_attr_for_tuples_truncate_additional!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/maybe_next_attr_erasure_macros.rs | tachys/src/html/attribute/maybe_next_attr_erasure_macros.rs | macro_rules! next_attr_output_type {
($current:ty, $next:ty) => {
#[cfg(not(erase_components))]
type Output<NewAttr: Attribute> = ($current, $next);
#[cfg(erase_components)]
type Output<NewAttr: Attribute> =
Vec<$crate::html::attribute::any_attribute::AnyAttribute>;
};
}
macro_rules! next_attr_combine {
($self:expr, $next_attr:expr) => {{
#[cfg(not(erase_components))]
{
($self, $next_attr)
}
#[cfg(erase_components)]
{
use $crate::html::attribute::any_attribute::IntoAnyAttribute;
vec![$self.into_any_attr(), $next_attr.into_any_attr()]
}
}};
}
pub(crate) use next_attr_combine;
pub(crate) use next_attr_output_type;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/html/attribute/custom.rs | tachys/src/html/attribute/custom.rs | use super::{
maybe_next_attr_erasure_macros::next_attr_output_type, NextAttribute,
};
use crate::{
html::attribute::{
maybe_next_attr_erasure_macros::next_attr_combine, Attribute,
AttributeValue, NamedAttributeKey,
},
view::{add_attr::AddAnyAttr, Position, ToTemplate},
};
use std::{borrow::Cow, sync::Arc};
/// Adds a custom attribute with any key-value combination.
#[inline(always)]
pub fn custom_attribute<K, V>(key: K, value: V) -> CustomAttr<K, V>
where
K: CustomAttributeKey,
V: AttributeValue,
{
CustomAttr { key, value }
}
/// A custom attribute with any key-value combination.
#[derive(Debug)]
pub struct CustomAttr<K, V>
where
K: CustomAttributeKey,
V: AttributeValue,
{
key: K,
value: V,
}
impl<K, V> Clone for CustomAttr<K, V>
where
K: CustomAttributeKey,
V: AttributeValue + Clone,
{
fn clone(&self) -> Self {
Self {
key: self.key.clone(),
value: self.value.clone(),
}
}
}
impl<K, V> Attribute for CustomAttr<K, V>
where
K: CustomAttributeKey,
V: AttributeValue,
{
const MIN_LENGTH: usize = 0;
type AsyncOutput = CustomAttr<K, V::AsyncOutput>;
type State = V::State;
type Cloneable = CustomAttr<K, V::Cloneable>;
type CloneableOwned = CustomAttr<K, V::CloneableOwned>;
fn html_len(&self) -> usize {
self.key.as_ref().len() + 3 + self.value.html_len()
}
fn to_html(
self,
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
self.value.to_html(self.key.as_ref(), buf);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
if !K::KEY.is_empty() {
self.value.hydrate::<FROM_SERVER>(self.key.as_ref(), el)
} else {
self.value.build(el, self.key.as_ref())
}
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
self.value.build(el, self.key.as_ref())
}
fn rebuild(self, state: &mut Self::State) {
self.value.rebuild(self.key.as_ref(), state);
}
fn into_cloneable(self) -> Self::Cloneable {
CustomAttr {
key: self.key,
value: self.value.into_cloneable(),
}
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
CustomAttr {
key: self.key,
value: self.value.into_cloneable_owned(),
}
}
fn dry_resolve(&mut self) {
self.value.dry_resolve();
}
async fn resolve(self) -> Self::AsyncOutput {
CustomAttr {
key: self.key,
value: self.value.resolve().await,
}
}
fn keys(&self) -> Vec<NamedAttributeKey> {
vec![NamedAttributeKey::Attribute(
self.key.as_ref().to_string().into(),
)]
}
}
impl<K, V> NextAttribute for CustomAttr<K, V>
where
K: CustomAttributeKey,
V: AttributeValue,
{
next_attr_output_type!(Self, NewAttr);
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
next_attr_combine!(self, new_attr)
}
}
impl<K, V> ToTemplate for CustomAttr<K, V>
where
K: CustomAttributeKey,
V: AttributeValue,
{
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
if !K::KEY.is_empty() {
V::to_template(K::KEY, buf);
}
}
}
// TODO this needs to be a method, not a const
/// Defines a custom attribute key.
pub trait CustomAttributeKey: Clone + AsRef<str> + Send + 'static {
/// The attribute name.
const KEY: &'static str;
}
impl CustomAttributeKey for &'static str {
const KEY: &'static str = "";
}
impl CustomAttributeKey for Cow<'static, str> {
const KEY: &'static str = "";
}
impl CustomAttributeKey for String {
const KEY: &'static str = "";
}
impl CustomAttributeKey for Arc<str> {
const KEY: &'static str = "";
}
#[cfg(all(feature = "nightly", rustc_nightly))]
impl<const K: &'static str> CustomAttributeKey
for crate::view::static_types::Static<K>
{
const KEY: &'static str = K;
}
/// Adds a custom attribute to an element.
pub trait CustomAttribute<K, V>
where
K: CustomAttributeKey,
V: AttributeValue,
Self: Sized + AddAnyAttr,
{
/// Adds an HTML attribute by key and value.
fn attr(
self,
key: K,
value: V,
) -> <Self as AddAnyAttr>::Output<CustomAttr<K, V>> {
self.add_any_attr(custom_attribute(key, value))
}
}
impl<T, K, V> CustomAttribute<K, V> for T
where
T: AddAnyAttr,
K: CustomAttributeKey,
V: AttributeValue,
{
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/suspense.rs | tachys/src/reactive_graph/suspense.rs | use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr, iterators::OptionState, Mountable, Position,
PositionState, Render, RenderHtml,
},
};
use any_spawner::Executor;
use futures::{
future::{AbortHandle, Abortable},
select, FutureExt,
};
use or_poisoned::OrPoisoned;
use reactive_graph::{
computed::{
suspense::{LocalResourceNotifier, SuspenseContext},
ScopedFuture,
},
graph::{
AnySource, AnySubscriber, Observer, ReactiveNode, Source, Subscriber,
ToAnySubscriber, WithObserver,
},
owner::{on_cleanup, provide_context, use_context},
};
use std::{
cell::RefCell,
fmt::Debug,
future::{Future, IntoFuture},
mem,
pin::Pin,
rc::Rc,
sync::{Arc, Mutex, Weak},
};
use throw_error::ErrorHook;
/// A suspended `Future`, which can be used in the view.
pub struct Suspend<T> {
pub(crate) subscriber: SuspendSubscriber,
pub(crate) inner: Pin<Box<dyn Future<Output = T> + Send>>,
}
#[derive(Debug, Clone)]
pub(crate) struct SuspendSubscriber {
inner: Arc<SuspendSubscriberInner>,
}
#[derive(Debug)]
struct SuspendSubscriberInner {
outer_subscriber: Option<AnySubscriber>,
sources: Mutex<Vec<AnySource>>,
}
impl SuspendSubscriber {
pub fn new() -> Self {
let outer_subscriber = Observer::get();
Self {
inner: Arc::new(SuspendSubscriberInner {
outer_subscriber,
sources: Default::default(),
}),
}
}
/// Re-links all reactive sources from this to another subscriber.
///
/// This is used to collect reactive dependencies during the rendering phase, and only later
/// connect them to any outer effect, to prevent the completion of async resources from
/// triggering the render effect to run a second time.
pub fn forward(&self) {
if let Some(to) = &self.inner.outer_subscriber {
let sources =
mem::take(&mut *self.inner.sources.lock().or_poisoned());
for source in sources {
source.add_subscriber(to.clone());
to.add_source(source);
}
}
}
}
impl ReactiveNode for SuspendSubscriberInner {
fn mark_dirty(&self) {}
fn mark_check(&self) {}
fn mark_subscribers_check(&self) {}
fn update_if_necessary(&self) -> bool {
false
}
}
impl Subscriber for SuspendSubscriberInner {
fn add_source(&self, source: AnySource) {
self.sources.lock().or_poisoned().push(source);
}
fn clear_sources(&self, subscriber: &AnySubscriber) {
for source in mem::take(&mut *self.sources.lock().or_poisoned()) {
source.remove_subscriber(subscriber);
}
}
}
impl ToAnySubscriber for SuspendSubscriber {
fn to_any_subscriber(&self) -> AnySubscriber {
AnySubscriber(
Arc::as_ptr(&self.inner) as usize,
Arc::downgrade(&self.inner) as Weak<dyn Subscriber + Send + Sync>,
)
}
}
impl<T> Suspend<T> {
/// Creates a new suspended view.
pub fn new<Fut>(fut: Fut) -> Self
where
Fut: IntoFuture<Output = T>,
Fut::IntoFuture: Send + 'static,
{
let subscriber = SuspendSubscriber::new();
let any_subscriber = subscriber.to_any_subscriber();
let inner = any_subscriber
.with_observer(|| Box::pin(ScopedFuture::new(fut.into_future())));
Self { subscriber, inner }
}
}
impl<T> Debug for Suspend<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Suspend").finish()
}
}
/// Retained view state for [`Suspend`].
pub struct SuspendState<T>
where
T: Render,
{
inner: Rc<RefCell<OptionState<T>>>,
}
impl<T> Mountable for SuspendState<T>
where
T: Render,
{
fn unmount(&mut self) {
self.inner.borrow_mut().unmount();
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
self.inner.borrow_mut().mount(parent, marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.inner.borrow_mut().insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.inner.borrow().elements()
}
}
impl<T> Render for Suspend<T>
where
T: Render + 'static,
{
type State = SuspendState<T>;
fn build(self) -> Self::State {
let Self { subscriber, inner } = self;
// create a Future that will be aborted on on_cleanup
// this prevents trying to access signals or other resources inside the Suspend, after the
// await, if they have already been cleaned up
let (abort_handle, abort_registration) = AbortHandle::new_pair();
let mut fut = Box::pin(Abortable::new(inner, abort_registration));
on_cleanup(move || abort_handle.abort());
// poll the future once immediately
// if it's already available, start in the ready state
// otherwise, start with the fallback
let initial = fut.as_mut().now_or_never().and_then(Result::ok);
let initially_pending = initial.is_none();
let inner = Rc::new(RefCell::new(initial.build()));
// get a unique ID if there's a SuspenseContext
let id = use_context::<SuspenseContext>().map(|sc| sc.task_id());
let error_hook = use_context::<Arc<dyn ErrorHook>>();
// if the initial state was pending, spawn a future to wait for it
// spawning immediately means that our now_or_never poll result isn't lost
// if it wasn't pending at first, we don't need to poll the Future again
if initially_pending {
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&inner);
async move {
let _guard = error_hook.as_ref().map(|hook| {
throw_error::set_error_hook(Arc::clone(hook))
});
let value = fut.as_mut().await;
drop(id);
if let Ok(value) = value {
Some(value).rebuild(&mut *state.borrow_mut());
}
subscriber.forward();
}
});
} else {
subscriber.forward();
}
SuspendState { inner }
}
fn rebuild(self, state: &mut Self::State) {
let Self { subscriber, inner } = self;
// create a Future that will be aborted on on_cleanup
// this prevents trying to access signals or other resources inside the Suspend, after the
// await, if they have already been cleaned up
let (abort_handle, abort_registration) = AbortHandle::new_pair();
let fut = Abortable::new(inner, abort_registration);
on_cleanup(move || abort_handle.abort());
// get a unique ID if there's a SuspenseContext
let id = use_context::<SuspenseContext>().map(|sc| sc.task_id());
let error_hook = use_context::<Arc<dyn ErrorHook>>();
// spawn the future, and rebuild the state when it resolves
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&state.inner);
async move {
let _guard = error_hook
.as_ref()
.map(|hook| throw_error::set_error_hook(Arc::clone(hook)));
let value = fut.await;
drop(id);
// waiting a tick here allows Suspense to remount if necessary, which prevents some
// edge cases in which a rebuild can't happen while unmounted because the DOM node
// has no parent
Executor::tick().await;
if let Ok(value) = value {
Some(value).rebuild(&mut *state.borrow_mut());
}
subscriber.forward();
}
});
}
}
impl<T> AddAnyAttr for Suspend<T>
where
T: Send + AddAnyAttr + 'static,
{
type Output<SomeNewAttr: Attribute> =
Suspend<<T as AddAnyAttr>::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();
Suspend::new(async move {
let this = self.inner.await;
this.add_any_attr(attr)
})
}
}
impl<T> RenderHtml for Suspend<T>
where
T: RenderHtml + Sized + 'static,
{
type AsyncOutput = Option<T>;
type Owned = Self;
const MIN_LENGTH: usize = T::MIN_LENGTH;
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
// TODO wrap this with a Suspense as needed
// currently this is just used for Routes, which creates a Suspend but never actually needs
// it (because we don't lazy-load routes on the server)
if let Some(inner) = self.inner.now_or_never() {
inner.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,
{
let mut fut = Box::pin(self.inner);
match fut.as_mut().now_or_never() {
Some(inner) => inner.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
),
None => {
if use_context::<SuspenseContext>().is_none() {
buf.next_id();
let (local_tx, mut local_rx) =
futures::channel::oneshot::channel::<()>();
provide_context(LocalResourceNotifier::from(local_tx));
let mut fut = fut.fuse();
let fut = async move {
select! {
_ = local_rx => None,
value = fut => Some(value)
}
};
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::<()>(
(),
&mut fallback_position,
mark_branches,
extra_attrs.clone(),
);
// TODO in 0.8: this should include a nonce
// we do have access to nonces via context (because this is the `reactive_graph` module)
// but unfortunately the Nonce type is defined in `leptos`, not in `tachys`
//
// missing it here only affects top-level Suspend, not Suspense components
buf.push_async_out_of_order(
fut,
position,
mark_branches,
extra_attrs,
);
} else {
buf.push_async({
let mut position = *position;
async move {
let value = fut.await;
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;
}
}
}
}
}
// TODO cancellation
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let Self { subscriber, inner } = self;
// create a Future that will be aborted on on_cleanup
// this prevents trying to access signals or other resources inside the Suspend, after the
// await, if they have already been cleaned up
let (abort_handle, abort_registration) = AbortHandle::new_pair();
let mut fut = Box::pin(Abortable::new(inner, abort_registration));
on_cleanup(move || abort_handle.abort());
// poll the future once immediately
// if it's already available, start in the ready state
// otherwise, start with the fallback
let initial = fut.as_mut().now_or_never().and_then(Result::ok);
let initially_pending = initial.is_none();
let inner = Rc::new(RefCell::new(
initial.hydrate::<FROM_SERVER>(cursor, position),
));
// get a unique ID if there's a SuspenseContext
let id = use_context::<SuspenseContext>().map(|sc| sc.task_id());
let error_hook = use_context::<Arc<dyn ErrorHook>>();
// if the initial state was pending, spawn a future to wait for it
// spawning immediately means that our now_or_never poll result isn't lost
// if it wasn't pending at first, we don't need to poll the Future again
if initially_pending {
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&inner);
async move {
let _guard = error_hook.as_ref().map(|hook| {
throw_error::set_error_hook(Arc::clone(hook))
});
let value = fut.as_mut().await;
drop(id);
if let Ok(value) = value {
Some(value).rebuild(&mut *state.borrow_mut());
}
subscriber.forward();
}
});
} else {
subscriber.forward();
}
SuspendState { inner }
}
async fn resolve(self) -> Self::AsyncOutput {
Some(self.inner.await)
}
fn dry_resolve(&mut self) {
// this is a little crazy, but if a Suspend is immediately available, we end up
// with a situation where polling it multiple times (here in dry_resolve and then in
// resolve) causes a runtime panic
// (see https://github.com/leptos-rs/leptos/issues/3113)
//
// at the same time, we do need to dry_resolve Suspend so that we can register synchronous
// resource reads that happen inside them
// (see https://github.com/leptos-rs/leptos/issues/2917)
//
// fuse()-ing the Future doesn't work, because that will cause the subsequent resolve()
// simply to be pending forever
//
// in this case, though, we can simply... discover that the data are already here, and then
// stuff them back into a new Future, which can safely be polled after its completion
if let Some(mut inner) = self.inner.as_mut().now_or_never() {
inner.dry_resolve();
self.inner = Box::pin(async move { inner })
as Pin<Box<dyn Future<Output = T> + Send>>;
}
}
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/tachys/src/reactive_graph/bind.rs | tachys/src/reactive_graph/bind.rs | use crate::{
dom::{event_target_checked, event_target_value},
html::{
attribute::{
maybe_next_attr_erasure_macros::{
next_attr_combine, next_attr_output_type,
},
Attribute, AttributeKey, AttributeValue, NamedAttributeKey,
NextAttribute,
},
event::{change, input, on},
property::{prop, IntoProperty},
},
prelude::AddAnyAttr,
renderer::{types::Element, RemoveEventHandler},
view::{Position, ToTemplate},
};
use reactive_graph::{
signal::{ReadSignal, RwSignal, WriteSignal},
traits::{Get, Set},
wrappers::read::Signal,
};
use send_wrapper::SendWrapper;
use wasm_bindgen::JsValue;
#[cfg(feature = "reactive_stores")]
use {
reactive_graph::owner::Storage,
reactive_stores::{
ArcField, AtIndex, AtKeyed, DerefedField, Field, KeyedSubfield,
StoreField, Subfield,
},
std::ops::{Deref, DerefMut, IndexMut},
};
/// `group` attribute used for radio inputs with `bind`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Group;
impl AttributeKey for Group {
const KEY: &'static str = "group";
}
/// Adds a two-way binding to the element, which adds an attribute and an event listener to the
/// element when the element is created or hydrated.
pub trait BindAttribute<Key, Sig, T>
where
Key: AttributeKey,
Sig: IntoSplitSignal<Value = T>,
T: FromEventTarget + AttributeValue + 'static,
{
/// The type of the element with the two-way binding added.
type Output;
/// Adds a two-way binding to the element, which adds an attribute and an event listener to the
/// element when the element is created or hydrated.
///
/// Example:
///
/// ```ignore
/// // You can use `RwSignal`s
/// let is_awesome = RwSignal::new(true);
///
/// // And you can use split signals
/// let (text, set_text) = signal("Hello world".to_string());
///
/// // Use `Checked` and a `bool` signal for a checkbox
/// checkbox_element.bind(Checked, is_awesome);
///
/// // Use `Group` and `String` for radio inputs
/// radio_element.bind(Group, (text, set_text));
///
/// // Use `Value` and `String` for everything else
/// input_element.bind(Value, (text, set_text));
/// ```
///
/// Depending on the input different events are listened to.
/// - `<input type="checkbox">`, `<input type="radio">` and `<select>` use the `change` event;
/// - `<input>` with the rest of the types and `<textarea>` elements use the `input` event;
fn bind(self, key: Key, signal: Sig) -> Self::Output;
}
impl<V, Key, Sig, T> BindAttribute<Key, Sig, T> for V
where
V: AddAnyAttr,
Key: AttributeKey,
Sig: IntoSplitSignal<Value = T>,
T: FromEventTarget + AttributeValue + PartialEq + Sync + 'static,
Signal<BoolOrT<T>>: IntoProperty,
<Sig as IntoSplitSignal>::Read:
Get<Value = T> + Send + Sync + Clone + 'static,
<Sig as IntoSplitSignal>::Write: Send + Clone + 'static,
Element: GetValue<T>,
{
type Output = <Self as AddAnyAttr>::Output<
Bind<
Key,
T,
<Sig as IntoSplitSignal>::Read,
<Sig as IntoSplitSignal>::Write,
>,
>;
fn bind(self, key: Key, signal: Sig) -> Self::Output {
self.add_any_attr(bind(key, signal))
}
}
/// Adds a two-way binding to the element, which adds an attribute and an event listener to the
/// element when the element is created or hydrated.
#[inline(always)]
pub fn bind<Key, Sig, T>(
key: Key,
signal: Sig,
) -> Bind<Key, T, <Sig as IntoSplitSignal>::Read, <Sig as IntoSplitSignal>::Write>
where
Key: AttributeKey,
Sig: IntoSplitSignal<Value = T>,
T: FromEventTarget + AttributeValue + 'static,
<Sig as IntoSplitSignal>::Read: Get<Value = T> + Clone + 'static,
<Sig as IntoSplitSignal>::Write: Send + Clone + 'static,
{
let (read_signal, write_signal) = signal.into_split_signal();
Bind {
key,
read_signal,
write_signal,
}
}
/// Two-way binding of an attribute and an event listener
#[derive(Debug)]
pub struct Bind<Key, T, R, W>
where
Key: AttributeKey,
T: FromEventTarget + AttributeValue + 'static,
R: Get<Value = T> + Clone + 'static,
W: Set<Value = T>,
{
key: Key,
read_signal: R,
write_signal: W,
}
impl<Key, T, R, W> Clone for Bind<Key, T, R, W>
where
Key: AttributeKey,
T: FromEventTarget + AttributeValue + 'static,
R: Get<Value = T> + Clone + 'static,
W: Set<Value = T> + Clone,
{
fn clone(&self) -> Self {
Self {
key: self.key.clone(),
read_signal: self.read_signal.clone(),
write_signal: self.write_signal.clone(),
}
}
}
impl<Key, T, R, W> Bind<Key, T, R, W>
where
Key: AttributeKey,
T: FromEventTarget + AttributeValue + PartialEq + Sync + 'static,
R: Get<Value = T> + Clone + Send + Sync + 'static,
W: Set<Value = T> + Clone + 'static,
Element: ChangeEvent + GetValue<T>,
{
/// Attaches the event listener that updates the signal value to the element.
pub fn attach(self, el: &Element) -> RemoveEventHandler<Element> {
el.attach_change_event::<T, W>(Key::KEY, self.write_signal.clone())
}
/// Creates the signal to update the value of the attribute. This signal is different
/// when using a `"group"` attribute
pub fn read_signal(&self, el: &Element) -> Signal<BoolOrT<T>> {
let read_signal = self.read_signal.clone();
if Key::KEY == "group" {
let el = SendWrapper::new(el.clone());
Signal::derive(move || {
BoolOrT::Bool(el.get_value() == read_signal.get())
})
} else {
Signal::derive(move || BoolOrT::T(read_signal.get()))
}
}
/// Returns the key of the attribute. If the key is `"group"` it returns `"checked"`, otherwise
/// the one which was provided originally.
pub fn key(&self) -> &'static str {
if Key::KEY == "group" {
"checked"
} else {
Key::KEY
}
}
}
impl<Key, T, R, W> Attribute for Bind<Key, T, R, W>
where
Key: AttributeKey,
T: FromEventTarget + AttributeValue + PartialEq + Sync + 'static,
R: Get<Value = T> + Clone + Send + Sync + 'static,
Signal<BoolOrT<T>>: IntoProperty,
W: Set<Value = T> + Clone + Send + 'static,
Element: ChangeEvent + GetValue<T>,
{
const MIN_LENGTH: usize = 0;
type State = (
<Signal<BoolOrT<T>> as IntoProperty>::State,
(Element, Option<RemoveEventHandler<Element>>),
);
type AsyncOutput = Self;
type Cloneable = Bind<Key, T, R, W>;
type CloneableOwned = Bind<Key, T, R, W>;
fn html_len(&self) -> usize {
0
}
fn to_html(
self,
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
}
#[inline(always)]
fn hydrate<const FROM_SERVER: bool>(self, el: &Element) -> Self::State {
let signal = self.read_signal(el);
let attr_state = prop(self.key(), signal).hydrate::<FROM_SERVER>(el);
let cleanup = self.attach(el);
(attr_state, (el.clone(), Some(cleanup)))
}
#[inline(always)]
fn build(self, el: &Element) -> Self::State {
let signal = self.read_signal(el);
let attr_state = prop(self.key(), signal).build(el);
let cleanup = self.attach(el);
(attr_state, (el.clone(), Some(cleanup)))
}
#[inline(always)]
fn rebuild(self, state: &mut Self::State) {
let (attr_state, (el, prev_cleanup)) = state;
let signal = self.read_signal(el);
prop(self.key(), signal).rebuild(attr_state);
if let Some(prev) = prev_cleanup.take() {
if let Some(remove) = prev.into_inner() {
remove();
}
}
*prev_cleanup = Some(self.attach(el));
}
fn into_cloneable(self) -> Self::Cloneable {
self.into_cloneable_owned()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn keys(&self) -> Vec<NamedAttributeKey> {
vec![]
}
}
impl<Key, T, R, W> NextAttribute for Bind<Key, T, R, W>
where
Key: AttributeKey,
T: FromEventTarget + AttributeValue + PartialEq + Sync + 'static,
R: Get<Value = T> + Clone + Send + Sync + 'static,
Signal<BoolOrT<T>>: IntoProperty,
W: Set<Value = T> + Clone + Send + 'static,
Element: ChangeEvent + GetValue<T>,
{
next_attr_output_type!(Self, NewAttr);
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
next_attr_combine!(self, new_attr)
}
}
impl<Key, T, R, W> ToTemplate for Bind<Key, T, R, W>
where
Key: AttributeKey,
T: FromEventTarget + AttributeValue + 'static,
R: Get<Value = T> + Clone + 'static,
W: Set<Value = T> + Clone,
{
#[inline(always)]
fn to_template(
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
}
}
/// Splits a combined signal into its read and write parts.
///
/// This allows you to either provide a `RwSignal` or a tuple `(ReadSignal, WriteSignal)`.
pub trait IntoSplitSignal {
/// The actual contained value of the signal
type Value;
/// The read part of the signal
type Read: Get<Value = Self::Value>;
/// The write part of the signal
type Write: Set<Value = Self::Value>;
/// Splits a combined signal into its read and write parts.
fn into_split_signal(self) -> (Self::Read, Self::Write);
}
impl<T> IntoSplitSignal for RwSignal<T>
where
T: Send + Sync + 'static,
ReadSignal<T>: Get<Value = T>,
{
type Value = T;
type Read = ReadSignal<T>;
type Write = WriteSignal<T>;
fn into_split_signal(self) -> (ReadSignal<T>, WriteSignal<T>) {
self.split()
}
}
impl<T, R, W> IntoSplitSignal for (R, W)
where
R: Get<Value = T>,
W: Set<Value = T>,
{
type Value = T;
type Read = R;
type Write = W;
fn into_split_signal(self) -> (Self::Read, Self::Write) {
self
}
}
#[cfg(feature = "reactive_stores")]
impl<Inner, Prev, T> IntoSplitSignal for Subfield<Inner, Prev, T>
where
Self: Get<Value = T> + Set<Value = T> + Clone,
{
type Value = T;
type Read = Self;
type Write = Self;
fn into_split_signal(self) -> (Self::Read, Self::Write) {
(self.clone(), self.clone())
}
}
#[cfg(feature = "reactive_stores")]
impl<T, S> IntoSplitSignal for Field<T, S>
where
Self: Get<Value = T> + Set<Value = T> + Clone,
S: Storage<ArcField<T>>,
{
type Value = T;
type Read = Self;
type Write = Self;
fn into_split_signal(self) -> (Self::Read, Self::Write) {
(self, self)
}
}
#[cfg(feature = "reactive_stores")]
impl<Inner, Prev, K, T> IntoSplitSignal for KeyedSubfield<Inner, Prev, K, T>
where
Self: Get<Value = T> + Set<Value = T> + Clone,
for<'a> &'a T: IntoIterator,
{
type Value = T;
type Read = Self;
type Write = Self;
fn into_split_signal(self) -> (Self::Read, Self::Write) {
(self.clone(), self.clone())
}
}
#[cfg(feature = "reactive_stores")]
impl<Inner, Prev, K, T> IntoSplitSignal for AtKeyed<Inner, Prev, K, T>
where
Self: Get<Value = T> + Set<Value = T> + Clone,
for<'a> &'a T: IntoIterator,
{
type Value = T;
type Read = Self;
type Write = Self;
fn into_split_signal(self) -> (Self::Read, Self::Write) {
(self.clone(), self.clone())
}
}
#[cfg(feature = "reactive_stores")]
impl<Inner, Prev> IntoSplitSignal for AtIndex<Inner, Prev>
where
Prev: Send + Sync + IndexMut<usize> + 'static,
Inner: Send + Sync + Clone + 'static,
Self: Get<Value = Prev::Output> + Set<Value = Prev::Output> + Clone,
Prev::Output: Sized,
{
type Value = Prev::Output;
type Read = Self;
type Write = Self;
fn into_split_signal(self) -> (Self::Read, Self::Write) {
(self.clone(), self.clone())
}
}
#[cfg(feature = "reactive_stores")]
impl<S> IntoSplitSignal for DerefedField<S>
where
Self: Get<Value = <S::Value as Deref>::Target>
+ Set<Value = <S::Value as Deref>::Target>
+ Clone,
S: Clone + StoreField + Send + Sync + 'static,
<S as StoreField>::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized,
{
type Value = <S::Value as Deref>::Target;
type Read = Self;
type Write = Self;
fn into_split_signal(self) -> (Self::Read, Self::Write) {
(self.clone(), self.clone())
}
}
/// Returns self from an event target.
pub trait FromEventTarget {
/// Returns self from an event target.
fn from_event_target(evt: &web_sys::Event) -> Self;
}
impl FromEventTarget for bool {
fn from_event_target(evt: &web_sys::Event) -> Self {
event_target_checked(evt)
}
}
impl FromEventTarget for String {
fn from_event_target(evt: &web_sys::Event) -> Self {
event_target_value(evt)
}
}
/// Attaches the appropriate change event listener to the element.
/// - `<input>` with text types and `<textarea>` elements use the `input` event;
/// - `<input type="checkbox">`, `<input type="radio">` and `<select>` use the `change` event;
pub trait ChangeEvent {
/// Attaches the appropriate change event listener to the element.
fn attach_change_event<T, W>(
&self,
key: &str,
write_signal: W,
) -> RemoveEventHandler<Self>
where
T: FromEventTarget + AttributeValue + 'static,
W: Set<Value = T> + 'static,
Self: Sized;
}
impl ChangeEvent for web_sys::Element {
fn attach_change_event<T, W>(
&self,
key: &str,
write_signal: W,
) -> RemoveEventHandler<Self>
where
T: FromEventTarget + AttributeValue + 'static,
W: Set<Value = T> + 'static,
{
if key == "group" {
let handler = move |evt| {
let checked = event_target_checked(&evt);
if checked {
write_signal.try_set(T::from_event_target(&evt));
}
};
on::<_, _>(change, handler).attach(self)
} else {
let handler = move |evt| {
write_signal.try_set(T::from_event_target(&evt));
};
if key == "checked" || self.tag_name() == "SELECT" {
on::<_, _>(change, handler).attach(self)
} else {
on::<_, _>(input, handler).attach(self)
}
}
}
}
/// Get the value attribute of an element (input).
/// Reads `value` if `T` is `String` and `checked` if `T` is `bool`.
pub trait GetValue<T> {
/// Get the value attribute of an element (input).
fn get_value(&self) -> T;
}
impl GetValue<String> for web_sys::Element {
fn get_value(&self) -> String {
self.get_attribute("value").unwrap_or_default()
}
}
impl GetValue<bool> for web_sys::Element {
fn get_value(&self) -> bool {
self.get_attribute("checked").unwrap_or_default() == "true"
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// Bool or a type. Needed to make the `group` attribute work. It is decided at runtime
/// if the derived signal value is a bool or a type `T`.
pub enum BoolOrT<T> {
/// We have definitely a boolean value for the `group` attribute
Bool(bool),
/// Standard case with some type `T`
T(T),
}
impl<T> IntoProperty for BoolOrT<T>
where
T: IntoProperty<State = (Element, JsValue)>
+ Into<JsValue>
+ Clone
+ 'static,
{
type State = (Element, JsValue);
type Cloneable = Self;
type CloneableOwned = Self;
fn hydrate<const FROM_SERVER: bool>(
self,
el: &Element,
key: &str,
) -> Self::State {
match self.clone() {
Self::T(s) => {
s.hydrate::<FROM_SERVER>(el, key);
}
Self::Bool(b) => {
<bool as IntoProperty>::hydrate::<FROM_SERVER>(b, el, key);
}
};
(el.clone(), self.into())
}
fn build(self, el: &Element, key: &str) -> Self::State {
match self.clone() {
Self::T(s) => {
s.build(el, key);
}
Self::Bool(b) => {
<bool as IntoProperty>::build(b, el, key);
}
}
(el.clone(), self.into())
}
fn rebuild(self, state: &mut Self::State, key: &str) {
let (el, prev) = state;
match self {
Self::T(s) => s.rebuild(&mut (el.clone(), prev.clone()), key),
Self::Bool(b) => <bool as IntoProperty>::rebuild(
b,
&mut (el.clone(), prev.clone()),
key,
),
}
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self
}
}
impl<T> From<BoolOrT<T>> for JsValue
where
T: Into<JsValue>,
{
fn from(value: BoolOrT<T>) -> Self {
match value {
BoolOrT::Bool(b) => b.into(),
BoolOrT::T(t) => t.into(),
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/class.rs | tachys/src/reactive_graph/class.rs | use super::{ReactiveFunction, SharedReactiveFunction};
use crate::{html::class::IntoClass, renderer::Rndr};
use reactive_graph::effect::RenderEffect;
use std::borrow::Borrow;
pub struct RenderEffectWithClassName<T>
where
T: 'static,
{
name: &'static str,
effect: RenderEffect<T>,
}
impl<T> RenderEffectWithClassName<T>
where
T: 'static,
{
fn new(name: &'static str, effect: RenderEffect<T>) -> Self {
Self { effect, name }
}
}
impl<F, C> IntoClass for F
where
F: ReactiveFunction<Output = C>,
C: IntoClass + 'static,
C::State: 'static,
{
type AsyncOutput = C::AsyncOutput;
type State = RenderEffect<C::State>;
type Cloneable = SharedReactiveFunction<C>;
type CloneableOwned = SharedReactiveFunction<C>;
fn html_len(&self) -> usize {
0
}
fn to_html(mut self, class: &mut String) {
let value = self.invoke();
value.to_html(class);
}
fn hydrate<const FROM_SERVER: bool>(
mut self,
el: &crate::renderer::types::Element,
) -> Self::State {
// TODO FROM_SERVER vs template
let el = el.clone();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&el)
}
})
}
fn build(mut self, el: &crate::renderer::types::Element) -> Self::State {
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build(&el)
}
})
}
fn rebuild(mut self, state: &mut Self::State) {
let prev_value = state.take_value();
*state = RenderEffect::new_with_value(
move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
unreachable!()
}
},
prev_value,
);
}
fn into_cloneable(self) -> Self::Cloneable {
self.into_shared()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into_shared()
}
fn dry_resolve(&mut self) {
self.invoke().dry_resolve();
}
async fn resolve(mut self) -> Self::AsyncOutput {
self.invoke().resolve().await
}
fn reset(state: &mut Self::State) {
*state = RenderEffect::new_with_value(
move |prev| {
if let Some(mut state) = prev {
C::reset(&mut state);
state
} else {
unreachable!()
}
},
state.take_value(),
);
}
}
impl<F, T> IntoClass for (&'static str, F)
where
F: ReactiveFunction<Output = T>,
T: Borrow<bool> + Send + 'static,
{
type AsyncOutput = (&'static str, bool);
type State =
RenderEffectWithClassName<(crate::renderer::types::ClassList, bool)>;
type Cloneable = (&'static str, SharedReactiveFunction<T>);
type CloneableOwned = (&'static str, SharedReactiveFunction<T>);
fn html_len(&self) -> usize {
self.0.len()
}
fn to_html(self, class: &mut String) {
let (name, mut f) = self;
let include = *f.invoke().borrow();
if include {
<&str as IntoClass>::to_html(name, class);
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
// TODO FROM_SERVER vs template
let (name, mut f) = self;
let class_list = Rndr::class_list(el);
let name = Rndr::intern(name);
RenderEffectWithClassName::new(
name,
RenderEffect::new(
move |prev: Option<(
crate::renderer::types::ClassList,
bool,
)>| {
let include = *f.invoke().borrow();
if let Some((class_list, prev)) = prev {
if include {
if !prev {
Rndr::add_class(&class_list, name);
}
} else if prev {
Rndr::remove_class(&class_list, name);
}
}
(class_list.clone(), include)
},
),
)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
let (name, mut f) = self;
let class_list = Rndr::class_list(el);
let name = Rndr::intern(name);
RenderEffectWithClassName::new(
name,
RenderEffect::new(
move |prev: Option<(
crate::renderer::types::ClassList,
bool,
)>| {
let include = *f.invoke().borrow();
match prev {
Some((class_list, prev)) => {
if include {
if !prev {
Rndr::add_class(&class_list, name);
}
} else if prev {
Rndr::remove_class(&class_list, name);
}
}
None => {
if include {
Rndr::add_class(&class_list, name);
}
}
}
(class_list.clone(), include)
},
),
)
}
fn rebuild(self, state: &mut Self::State) {
let (name, mut f) = self;
let prev_name = state.name;
let prev_state = state.effect.take_value();
if let Some((list, prev_include)) = &prev_state {
if prev_name != name && *prev_include {
Rndr::remove_class(list, prev_name);
}
}
// Name might've updated:
state.name = name;
let mut first_run = true;
state.effect = RenderEffect::new_with_value(
move |prev| {
let include = *f.invoke().borrow();
match prev {
Some((class_list, prev)) => {
if include {
if !prev || first_run {
Rndr::add_class(&class_list, name);
}
} else if prev {
Rndr::remove_class(&class_list, name);
}
first_run = false;
(class_list.clone(), include)
}
None => {
unreachable!()
}
}
},
prev_state,
);
}
fn into_cloneable(self) -> Self::Cloneable {
(self.0, self.1.into_shared())
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
(self.0, self.1.into_shared())
}
fn dry_resolve(&mut self) {
self.1.invoke();
}
async fn resolve(mut self) -> Self::AsyncOutput {
(self.0, *self.1.invoke().borrow())
}
fn reset(state: &mut Self::State) {
let name = state.name;
state.effect = RenderEffect::new_with_value(
move |prev| {
if let Some(mut state) = prev {
let (class_list, prev) = &mut state;
Rndr::remove_class(class_list, name);
*prev = false;
state
} else {
unreachable!()
}
},
state.effect.take_value(),
);
}
}
// TODO this needs a non-reactive form too to be restored
/*
impl<F, T> IntoClass for (Vec<Cow<'static, str>>, F)
where
F: ReactiveFunction<Output = T>,
T: Borrow<bool> + Send + 'static,
{
type AsyncOutput = (Vec<Cow<'static, str>>, bool);
type State = RenderEffect<(crate::renderer::types::ClassList, bool)>;
type Cloneable = (Vec<Cow<'static, str>>, SharedReactiveFunction<T>);
type CloneableOwned = (Vec<Cow<'static, str>>, SharedReactiveFunction<T>);
fn html_len(&self) -> usize {
self.0.iter().map(|n| n.len()).sum()
}
fn to_html(self, class: &mut String) {
let (names, mut f) = self;
let include = *f.invoke().borrow();
if include {
for name in names {
<&str as IntoClass>::to_html(&name, class);
}
}
}
fn hydrate<const FROM_SERVER: bool>(self, el: &crate::renderer::types::Element) -> Self::State {
// TODO FROM_SERVER vs template
let (names, mut f) = self;
let class_list = Rndr::class_list(el);
RenderEffect::new(move |prev: Option<(crate::renderer::types::ClassList, bool)>| {
let include = *f.invoke().borrow();
if let Some((class_list, prev)) = prev {
if include {
if !prev {
for name in &names {
// TODO multi-class optimizations here
Rndr::add_class(&class_list, name);
}
}
} else if prev {
for name in &names {
Rndr::remove_class(&class_list, name);
}
}
}
(class_list.clone(), include)
})
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
let (names, mut f) = self;
let class_list = Rndr::class_list(el);
RenderEffect::new(move |prev: Option<(crate::renderer::types::ClassList, bool)>| {
let include = *f.invoke().borrow();
match prev {
Some((class_list, prev)) => {
if include {
for name in &names {
if !prev {
Rndr::add_class(&class_list, name);
}
}
} else if prev {
for name in &names {
Rndr::remove_class(&class_list, name);
}
}
}
None => {
if include {
for name in &names {
Rndr::add_class(&class_list, name);
}
}
}
}
(class_list.clone(), include)
})
}
fn rebuild(self, state: &mut Self::State) {
let (names, mut f) = self;
let prev_value = state.take_value();
*state = RenderEffect::new_with_value(
move |prev: Option<(crate::renderer::types::ClassList, bool)>| {
let include = *f.invoke().borrow();
match prev {
Some((class_list, prev)) => {
if include {
for name in &names {
if !prev {
Rndr::add_class(&class_list, name);
}
}
} else if prev {
for name in &names {
Rndr::remove_class(&class_list, name);
}
}
(class_list.clone(), include)
}
None => {
unreachable!()
}
}
},
prev_value,
);
}
fn into_cloneable(self) -> Self::Cloneable {
(self.0.clone(), self.1.into_shared())
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
(self.0.clone(), self.1.into_shared())
}
fn dry_resolve(&mut self) {
self.1.invoke();
}
async fn resolve(mut self) -> Self::AsyncOutput {
(self.0, *self.1.invoke().borrow())
}
}
*/
/*
impl<G> IntoClass for ReadGuard<String, G>
where
G: Deref<Target = String> + Send,
{
type AsyncOutput = Self;
type State = <String as IntoClass>::State;
type Cloneable = Arc<str>;
type CloneableOwned = Arc<str>;
fn html_len(&self) -> usize {
self.len()
}
fn to_html(self, class: &mut String) {
<&str as IntoClass>::to_html(self.deref().as_str(), class);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
<String as IntoClass>::hydrate::<FROM_SERVER>(
self.deref().to_owned(),
el,
)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
<String as IntoClass>::build(self.deref().to_owned(), el)
}
fn rebuild(self, state: &mut Self::State) {
<String as IntoClass>::rebuild(self.deref().to_owned(), state)
}
fn into_cloneable(self) -> Self::Cloneable {
self.as_str().into()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.as_str().into()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl<G> IntoClass for (&'static str, ReadGuard<bool, G>)
where
G: Deref<Target = bool> + Send,
{
type AsyncOutput = Self;
type State = <(&'static str, bool) as IntoClass>::State;
type Cloneable = (&'static str, bool);
type CloneableOwned = (&'static str, bool);
fn html_len(&self) -> usize {
self.0.len()
}
fn to_html(self, class: &mut String) {
<(&'static str, bool) as IntoClass>::to_html(
(self.0, *self.1.deref()),
class,
);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
<(&'static str, bool) as IntoClass>::hydrate::<FROM_SERVER>(
(self.0, *self.1.deref()),
el,
)
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
<(&'static str, bool) as IntoClass>::build(
(self.0, *self.1.deref()),
el,
)
}
fn rebuild(self, state: &mut Self::State) {
<(&'static str, bool) as IntoClass>::rebuild(
(self.0, *self.1.deref()),
state,
)
}
fn into_cloneable(self) -> Self::Cloneable {
(self.0, *self.1)
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
(self.0, *self.1)
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
*/
macro_rules! tuple_class_reactive {
($name:ident, <$($impl_gen:ident),*>, <$($gen:ident),*> , $( $where_clause:tt )*) =>
{
#[allow(deprecated)]
impl<$($impl_gen),*> IntoClass for (&'static str, $name<$($gen),*>)
where
$($where_clause)*
{
type AsyncOutput = Self;
type State = RenderEffectWithClassName<(
crate::renderer::types::ClassList,
bool,
)>;
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
self.0.len()
}
fn to_html(self, class: &mut String) {
let (name, f) = self;
let include = f.get();
if include {
<&str as IntoClass>::to_html(name, class);
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
IntoClass::hydrate::<FROM_SERVER>(
(self.0, move || self.1.get()),
el,
)
}
fn build(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
IntoClass::build((self.0, move || self.1.get()), el)
}
fn rebuild(self, state: &mut Self::State) {
IntoClass::rebuild((self.0, move || self.1.get()), 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
}
fn reset(state: &mut Self::State) {
let name = state.name;
*state = RenderEffectWithClassName::new(
state.name,
RenderEffect::new_with_value(
move |prev| {
if let Some(mut state) = prev {
let (class_list, prev) = &mut state;
Rndr::remove_class(class_list, name);
*prev = false;
state
} else {
unreachable!()
}
},
state.effect.take_value(),
),
);
}
}
};
}
macro_rules! class_reactive {
($name:ident, <$($gen:ident),*>, $v:ty, $( $where_clause:tt )*) =>
{
#[allow(deprecated)]
impl<$($gen),*> IntoClass for $name<$($gen),*>
where
$v: IntoClass + Clone + Send + Sync + 'static,
<$v as IntoClass>::State: 'static,
$($where_clause)*
{
type AsyncOutput = Self;
type State = RenderEffect<<$v as IntoClass>::State>;
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
0
}
fn to_html(self, class: &mut String) {
let value = self.get();
value.to_html(class);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
(move || self.get()).hydrate::<FROM_SERVER>(el)
}
fn build(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
(move || self.get()).build(el)
}
fn rebuild(self, state: &mut Self::State) {
(move || self.get()).rebuild(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
}
fn reset(state: &mut Self::State) {
*state = RenderEffect::new_with_value(
move |prev| {
if let Some(mut state) = prev {
<$v>::reset(&mut state);
state
} else {
unreachable!()
}
},
state.take_value(),
);
}
}
};
}
#[cfg(not(feature = "nightly"))]
mod stable {
use super::{RenderEffect, RenderEffectWithClassName};
use crate::{html::class::IntoClass, renderer::Rndr};
#[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},
};
class_reactive!(
RwSignal,
<V, S>,
V,
RwSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
class_reactive!(
ReadSignal,
<V, S>,
V,
ReadSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
class_reactive!(
Memo,
<V, S>,
V,
Memo<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
class_reactive!(
Signal,
<V, S>,
V,
Signal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
class_reactive!(
MaybeSignal,
<V, S>,
V,
MaybeSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
class_reactive!(ArcRwSignal, <V>, V, ArcRwSignal<V>: Get<Value = V>);
class_reactive!(ArcReadSignal, <V>, V, ArcReadSignal<V>: Get<Value = V>);
class_reactive!(ArcMemo, <V>, V, ArcMemo<V>: Get<Value = V>);
class_reactive!(ArcSignal, <V>, V, ArcSignal<V>: Get<Value = V>);
tuple_class_reactive!(
RwSignal,
<S>,
<bool, S>,
RwSignal<bool, S>: Get<Value = bool>,
S: Storage<bool>,
S: Send + 'static,
);
tuple_class_reactive!(
ReadSignal,
<S>,
<bool, S>,
ReadSignal<bool, S>: Get<Value = bool>,
S: Storage<bool>,
S: Send + 'static,
);
tuple_class_reactive!(
Memo,
<S>,
<bool, S>,
Memo<bool, S>: Get<Value = bool>,
S: Storage<bool>,
S: Send + 'static,
);
tuple_class_reactive!(
Signal,
<S>,
<bool, S>,
Signal<bool, S>: Get<Value = bool>,
S: Storage<bool>,
S: Send + 'static,
);
tuple_class_reactive!(
MaybeSignal,
<S>,
<bool, S>,
MaybeSignal<bool, S>: Get<Value = bool>,
S: Storage<bool>,
S: Send + 'static,
);
tuple_class_reactive!(ArcRwSignal,<>, <bool>, ArcRwSignal<bool>: Get<Value = bool>);
tuple_class_reactive!(ArcReadSignal,<>, <bool>, ArcReadSignal<bool>: Get<Value = bool>);
tuple_class_reactive!(ArcMemo,<>, <bool>, ArcMemo<bool>: Get<Value = bool>);
tuple_class_reactive!(ArcSignal,<>, <bool>, ArcSignal<bool>: Get<Value = bool>);
}
#[cfg(feature = "reactive_stores")]
mod reactive_stores {
use super::{RenderEffect, RenderEffectWithClassName};
use crate::{html::class::IntoClass, renderer::Rndr};
#[allow(deprecated)]
use reactive_graph::{owner::Storage, traits::Get};
use reactive_stores::{
ArcField, ArcStore, AtIndex, AtKeyed, DerefedField, Field,
KeyedSubfield, Store, StoreField, Subfield,
};
use std::ops::{Deref, DerefMut, Index, IndexMut};
class_reactive!(
Subfield,
<Inner, Prev, V>,
V,
Subfield<Inner, Prev, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
);
class_reactive!(
AtKeyed,
<Inner, Prev, K, V>,
V,
AtKeyed<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
class_reactive!(
KeyedSubfield,
<Inner, Prev, K, V>,
V,
KeyedSubfield<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
class_reactive!(
DerefedField,
<S>,
<S::Value as Deref>::Target,
S: Clone + StoreField + Send + Sync + 'static,
<S as StoreField>::Value: Deref + DerefMut
);
class_reactive!(
AtIndex,
<Inner, Prev>,
<Prev as Index<usize>>::Output,
AtIndex<Inner, Prev>: Get<Value = Prev::Output>,
Prev: Send + Sync + IndexMut<usize> + 'static,
Inner: Send + Sync + Clone + 'static,
);
class_reactive!(
Store,
<V, S>,
V,
Store<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
class_reactive!(
Field,
<V, S>,
V,
Field<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
class_reactive!(ArcStore, <V>, V, ArcStore<V>: Get<Value = V>);
class_reactive!(ArcField, <V>, V, ArcField<V>: Get<Value = V>);
tuple_class_reactive!(
Subfield,
<Inner, Prev>,
<Inner, Prev, bool>,
Subfield<Inner, Prev, bool>: Get<Value = bool>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
);
tuple_class_reactive!(
AtKeyed,
<Inner, Prev, K>,
<Inner, Prev, K, bool>,
AtKeyed<Inner, Prev, K, bool>: Get<Value = bool>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a bool: IntoIterator,
);
tuple_class_reactive!(
KeyedSubfield,
<Inner, Prev, K>,
<Inner, Prev, K, bool>,
KeyedSubfield<Inner, Prev, K, bool>: Get<Value = bool>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a bool: IntoIterator,
);
tuple_class_reactive!(
DerefedField,
<S>,
<S>,
S: Clone + StoreField + Send + Sync + 'static,
<S as StoreField>::Value: Deref<Target = bool> + DerefMut
);
tuple_class_reactive!(
AtIndex,
<Inner, Prev>,
<Inner, Prev>,
AtIndex<Inner, Prev>: Get<Value = Prev::Output>,
Prev: Send + Sync + IndexMut<usize,Output = bool> + 'static,
Inner: Send + Sync + Clone + 'static,
);
tuple_class_reactive!(
Store,
<S>,
<bool, S>,
Store<bool, S>: Get<Value = bool>,
S: Storage<bool>,
S: Send + 'static,
);
tuple_class_reactive!(
Field,
<S>,
<bool, S>,
Field<bool, S>: Get<Value = bool>,
S: Storage<bool>,
S: Send + 'static,
);
tuple_class_reactive!(ArcStore,<>, <bool>, ArcStore<bool>: Get<Value = bool>);
tuple_class_reactive!(ArcField,<>, <bool>, ArcField<bool>: Get<Value = bool>);
}
/*
impl<Fut> IntoClass for Suspend<Fut>
where
Fut: Clone + Future + Send + 'static,
Fut::Output: IntoClass,
{
type AsyncOutput = Fut::Output;
type State = Rc<RefCell<Option<<Fut::Output as IntoClass>::State>>>;
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
0
}
fn to_html(self, style: &mut String) {
if let Some(inner) = self.inner.now_or_never() {
inner.to_html(style);
} else {
panic!("You cannot use Suspend on an attribute outside Suspense");
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
let el = el.to_owned();
let state = Rc::new(RefCell::new(None));
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&state);
async move {
*state.borrow_mut() =
Some(self.inner.await.hydrate::<FROM_SERVER>(&el));
self.subscriber.forward();
}
});
state
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
let el = el.to_owned();
let state = Rc::new(RefCell::new(None));
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&state);
async move {
*state.borrow_mut() = Some(self.inner.await.build(&el));
self.subscriber.forward();
}
});
state
}
fn rebuild(self, state: &mut Self::State) {
reactive_graph::spawn_local_scoped({
let state = Rc::clone(state);
async move {
let value = self.inner.await;
let mut state = state.borrow_mut();
if let Some(state) = state.as_mut() {
value.rebuild(state);
}
self.subscriber.forward();
}
});
}
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.inner.await
}
}
*/
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/node_ref.rs | tachys/src/reactive_graph/node_ref.rs | use crate::html::{element::ElementType, node_ref::NodeRefContainer};
use reactive_graph::{
effect::Effect,
graph::untrack,
signal::{
guards::{Derefable, ReadGuard},
RwSignal,
},
traits::{
DefinedAt, Get, IsDisposed, Notify, ReadUntracked, Set, Track,
UntrackableGuard, Write,
},
};
use send_wrapper::SendWrapper;
use std::{cell::Cell, ops::DerefMut};
use wasm_bindgen::JsCast;
/// A reactive reference to a DOM node that can be used with the `node_ref` attribute.
#[derive(Debug)]
pub struct NodeRef<E>(RwSignal<Option<SendWrapper<E::Output>>>)
where
E: ElementType,
E::Output: 'static;
impl<E> NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
/// Creates a new node reference.
#[track_caller]
pub fn new() -> Self {
Self(RwSignal::new(None))
}
/// Runs the provided closure when the `NodeRef` has been connected
/// with its element.
#[inline(always)]
pub fn on_load<F>(self, f: F)
where
E: 'static,
F: FnOnce(E::Output) + 'static,
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
let f = Cell::new(Some(f));
Effect::new(move |_| {
if let Some(node_ref) = self.get() {
let f = f.take().unwrap();
untrack(move || {
f(node_ref);
});
}
});
}
}
impl<E> Default for NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
fn default() -> Self {
Self::new()
}
}
impl<E> Clone for NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<E> Copy for NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
}
impl<E> NodeRefContainer<E> for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + 'static,
{
fn load(self, el: &crate::renderer::types::Element) {
// safe to construct SendWrapper here, because it will only run in the browser
// so it will always be accessed or dropped from the main thread
self.0
.set(Some(SendWrapper::new(el.clone().unchecked_into())));
}
}
impl<E> DefinedAt for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + 'static,
{
fn defined_at(&self) -> Option<&'static std::panic::Location<'static>> {
self.0.defined_at()
}
}
impl<E> Notify for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
fn notify(&self) {
self.0.notify();
}
}
impl<E> Write for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
type Value = Option<SendWrapper<E::Output>>;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.0.try_write()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.0.try_write_untracked()
}
}
impl<E> ReadUntracked for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + Clone + 'static,
{
type Value = ReadGuard<Option<E::Output>, Derefable<Option<E::Output>>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
Some(ReadGuard::new(Derefable(
self.0.try_read_untracked()?.as_deref().cloned(),
)))
}
}
impl<E> Track for NodeRef<E>
where
E: ElementType,
E::Output: JsCast + 'static,
{
fn track(&self) {
self.0.track();
}
}
impl<E> IsDisposed for NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
fn is_disposed(&self) -> bool {
self.0.is_disposed()
}
}
/// Create a [NodeRef].
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
Please use `NodeRef::new()` instead."]
pub fn create_node_ref<E>() -> NodeRef<E>
where
E: ElementType,
E::Output: 'static,
{
NodeRef::new()
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/owned.rs | tachys/src/reactive_graph/owned.rs | use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
prelude::Mountable,
ssr::StreamBuilder,
view::{add_attr::AddAnyAttr, Position, PositionState, Render, RenderHtml},
};
use reactive_graph::{computed::ScopedFuture, owner::Owner};
/// A view wrapper that sets the reactive [`Owner`] to a particular owner whenever it is rendered.
#[derive(Debug, Clone)]
pub struct OwnedView<T> {
owner: Owner,
view: T,
}
impl<T> OwnedView<T> {
/// Wraps a view with the current owner.
pub fn new(view: T) -> Self {
let owner = Owner::current().expect("no reactive owner");
Self { owner, view }
}
/// Wraps a view with the given owner.
pub fn new_with_owner(view: T, owner: Owner) -> Self {
Self { owner, view }
}
}
/// Retained view state for an [`OwnedView`].
#[derive(Debug, Clone)]
pub struct OwnedViewState<T>
where
T: Mountable,
{
owner: Owner,
state: T,
}
impl<T> OwnedViewState<T>
where
T: Mountable,
{
/// Wraps a state with the given owner.
fn new(state: T, owner: Owner) -> Self {
Self { owner, state }
}
}
impl<T> Render for OwnedView<T>
where
T: Render,
{
type State = OwnedViewState<T::State>;
fn build(self) -> Self::State {
let state = self.owner.with(|| self.view.build());
OwnedViewState::new(state, self.owner)
}
fn rebuild(self, state: &mut Self::State) {
let OwnedView { owner, view, .. } = self;
owner.with(|| view.rebuild(&mut state.state));
state.owner = owner;
}
}
impl<T> AddAnyAttr for OwnedView<T>
where
T: AddAnyAttr,
{
type Output<SomeNewAttr: Attribute> = OwnedView<T::Output<SomeNewAttr>>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let OwnedView { owner, view } = self;
OwnedView {
owner,
view: view.add_any_attr(attr),
}
}
}
impl<T> RenderHtml for OwnedView<T>
where
T: RenderHtml,
{
// TODO
type AsyncOutput = OwnedView<T::AsyncOutput>;
type Owned = OwnedView<T::Owned>;
const MIN_LENGTH: usize = T::MIN_LENGTH;
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
self.owner.with(|| {
self.view.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.owner.with(|| {
self.view.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
)
});
// if self.owner drops here, it can be disposed before the asynchronous rendering process
// has actually happened
// instead, we'll stuff it into the cleanups of its parent so that it will remain alive at
// least as long as the parent does
Owner::on_cleanup(move || drop(self.owner));
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let state = self
.owner
.with(|| self.view.hydrate::<FROM_SERVER>(cursor, position));
OwnedViewState::new(state, self.owner)
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let state = self
.owner
.with(|| {
ScopedFuture::new(self.view.hydrate_async(cursor, position))
})
.await;
OwnedViewState::new(state, self.owner)
}
async fn resolve(self) -> Self::AsyncOutput {
let OwnedView { owner, view } = self;
let view = owner
.with(|| ScopedFuture::new(async move { view.resolve().await }))
.await;
OwnedView { owner, view }
}
fn dry_resolve(&mut self) {
self.owner.with(|| self.view.dry_resolve());
}
fn into_owned(self) -> Self::Owned {
OwnedView {
owner: self.owner,
view: self.view.into_owned(),
}
}
}
impl<T> Mountable for OwnedViewState<T>
where
T: Mountable,
{
fn unmount(&mut self) {
self.state.unmount();
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
self.state.mount(parent, marker);
}
fn try_mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) -> bool {
self.state.try_mount(parent, marker)
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.state.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.state.elements()
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/mod.rs | tachys/src/reactive_graph/mod.rs | use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute, AttributeValue},
hydration::Cursor,
renderer::Rndr,
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml, ToTemplate,
},
};
use reactive_graph::effect::RenderEffect;
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex},
};
/// Types for two way data binding.
pub mod bind;
mod class;
mod inner_html;
/// Provides a reactive [`NodeRef`](node_ref::NodeRef) type.
pub mod node_ref;
mod owned;
mod property;
mod style;
mod suspense;
pub use owned::*;
pub use suspense::*;
impl<F, V> ToTemplate for F
where
F: ReactiveFunction<Output = V>,
V: ToTemplate,
{
const TEMPLATE: &'static str = V::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
// FIXME this seems wrong
V::to_template(buf, class, style, inner_html, position)
}
}
impl<F, V> Render for F
where
F: ReactiveFunction<Output = V>,
V: Render,
V::State: 'static,
{
type State = RenderEffectState<V::State>;
#[track_caller]
fn build(mut self) -> Self::State {
let hook = throw_error::get_error_hook();
RenderEffect::new(move |prev| {
let _guard = hook
.as_ref()
.map(|h| throw_error::set_error_hook(Arc::clone(h)));
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build()
}
})
.into()
}
#[track_caller]
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();
}
}
/// Retained view state for a [`RenderEffect`].
pub struct RenderEffectState<T: 'static>(Option<RenderEffect<T>>);
impl<T> From<RenderEffect<T>> for RenderEffectState<T> {
fn from(value: RenderEffect<T>) -> Self {
Self(Some(value))
}
}
impl<T> Mountable for RenderEffectState<T>
where
T: Mountable,
{
fn unmount(&mut self) {
if let Some(ref mut inner) = self.0 {
inner.unmount();
}
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
if let Some(ref mut inner) = self.0 {
inner.mount(parent, marker);
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
if let Some(inner) = &self.0 {
inner.insert_before_this(child)
} else {
false
}
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.0
.as_ref()
.map(|inner| inner.elements())
.unwrap_or_default()
}
}
impl<F, V> RenderHtml for F
where
F: ReactiveFunction<Output = V>,
V: RenderHtml + 'static,
V::State: 'static,
{
type AsyncOutput = V::AsyncOutput;
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
self.invoke().dry_resolve();
}
async fn resolve(mut self) -> Self::AsyncOutput {
self.invoke().resolve().await
}
fn html_len(&self) -> usize {
V::MIN_LENGTH
}
fn to_html_with_buf(
mut self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
let value = self.invoke();
value.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 value = self.invoke();
value.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
fn hydrate<const FROM_SERVER: bool>(
mut self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
/// codegen optimisation:
fn prep(
cursor: &Cursor,
position: &PositionState,
) -> (
Cursor,
PositionState,
Option<Arc<dyn throw_error::ErrorHook>>,
) {
let cursor = cursor.clone();
let position = position.clone();
let hook = throw_error::get_error_hook();
(cursor, position, hook)
}
let (cursor, position, hook) = prep(cursor, position);
RenderEffect::new(move |prev| {
/// codegen optimisation:
fn get_guard(
hook: &Option<Arc<dyn throw_error::ErrorHook>>,
) -> Option<throw_error::ResetErrorHookOnDrop> {
hook.as_ref()
.map(|h| throw_error::set_error_hook(Arc::clone(h)))
}
let _guard = get_guard(&hook);
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&cursor, &position)
}
})
.into()
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
/// codegen optimisation:
fn prep(
cursor: &Cursor,
position: &PositionState,
) -> (
Cursor,
PositionState,
Option<Arc<dyn throw_error::ErrorHook>>,
) {
let cursor = cursor.clone();
let position = position.clone();
let hook = throw_error::get_error_hook();
(cursor, position, hook)
}
let (cursor, position, hook) = prep(cursor, position);
let mut fun = self.into_shared();
RenderEffect::new_with_async_value(
{
let mut fun = fun.clone();
move |prev| {
/// codegen optimisation:
fn get_guard(
hook: &Option<Arc<dyn throw_error::ErrorHook>>,
) -> Option<throw_error::ResetErrorHookOnDrop>
{
hook.as_ref()
.map(|h| throw_error::set_error_hook(Arc::clone(h)))
}
let _guard = get_guard(&hook);
let value = fun.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
unreachable!()
}
}
},
async move { fun.invoke().hydrate_async(&cursor, &position).await },
)
.await
.into()
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl<F, V> AddAnyAttr for F
where
F: ReactiveFunction<Output = V>,
V: RenderHtml + 'static,
{
type Output<SomeNewAttr: Attribute> =
Box<dyn FnMut() -> V::Output<SomeNewAttr::CloneableOwned> + Send>;
fn add_any_attr<NewAttr: Attribute>(
mut self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let attr = attr.into_cloneable_owned();
Box::new(move || self.invoke().add_any_attr(attr.clone()))
}
}
impl<M> Mountable for RenderEffect<M>
where
M: Mountable + 'static,
{
fn unmount(&mut self) {
self.with_value_mut(|state| state.unmount());
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
self.with_value_mut(|state| {
state.mount(parent, marker);
});
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.with_value_mut(|value| value.insert_before_this(child))
.unwrap_or(false)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.with_value_mut(|inner| inner.elements())
.unwrap_or_default()
}
}
impl<T> Drop for RenderEffectState<T> {
fn drop(&mut self) {
if let Some(effect) = self.0.take() {
drop(effect.take_value());
drop(effect);
}
}
}
impl<M, E> Mountable for Result<M, E>
where
M: Mountable,
{
fn unmount(&mut self) {
if let Ok(ref mut inner) = self {
inner.unmount();
}
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
if let Ok(ref mut inner) = self {
inner.mount(parent, marker);
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
if let Ok(inner) = &self {
inner.insert_before_this(child)
} else {
false
}
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.as_ref()
.map(|inner| inner.elements())
.unwrap_or_default()
}
}
// Dynamic attributes
impl<F, V> AttributeValue for F
where
F: ReactiveFunction<Output = V>,
V: AttributeValue + 'static,
V::State: 'static,
{
type AsyncOutput = V::AsyncOutput;
type State = RenderEffect<V::State>;
type Cloneable = SharedReactiveFunction<V>;
type CloneableOwned = SharedReactiveFunction<V>;
fn html_len(&self) -> usize {
0
}
fn to_html(mut self, key: &str, buf: &mut String) {
let value = self.invoke();
value.to_html(key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
mut self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
let key = Rndr::intern(key);
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&key, &mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&key, &el)
}
})
}
fn build(
mut self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
let key = Rndr::intern(key);
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&key, &mut state);
state
} else {
value.build(&el, &key)
}
})
}
fn rebuild(mut self, key: &str, state: &mut Self::State) {
let key = Rndr::intern(key);
let key = key.to_owned();
let prev_value = state.take_value();
*state = RenderEffect::new_with_value(
move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&key, &mut state);
state
} else {
unreachable!()
}
},
prev_value,
);
}
fn into_cloneable(self) -> Self::Cloneable {
self.into_shared()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into_shared()
}
fn dry_resolve(&mut self) {
self.invoke();
}
async fn resolve(mut self) -> Self::AsyncOutput {
self.invoke().resolve().await
}
}
impl<V> AttributeValue for Suspend<V>
where
V: AttributeValue + 'static,
V::State: 'static,
{
type State = Rc<RefCell<Option<V::State>>>;
type AsyncOutput = V;
type Cloneable = ();
type CloneableOwned = ();
fn html_len(&self) -> usize {
0
}
fn to_html(self, _key: &str, _buf: &mut String) {
#[cfg(feature = "tracing")]
tracing::error!(
"Suspended attributes cannot be used outside Suspense."
);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
let key = key.to_owned();
let el = el.to_owned();
let state = Rc::new(RefCell::new(None));
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&state);
async move {
*state.borrow_mut() =
Some(self.inner.await.hydrate::<FROM_SERVER>(&key, &el));
self.subscriber.forward();
}
});
state
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
let key = key.to_owned();
let el = el.to_owned();
let state = Rc::new(RefCell::new(None));
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&state);
async move {
*state.borrow_mut() = Some(self.inner.await.build(&el, &key));
self.subscriber.forward();
}
});
state
}
fn rebuild(self, key: &str, state: &mut Self::State) {
let key = key.to_owned();
reactive_graph::spawn_local_scoped({
let state = Rc::clone(state);
async move {
let value = self.inner.await;
let mut state = state.borrow_mut();
if let Some(state) = state.as_mut() {
value.rebuild(&key, state);
}
self.subscriber.forward();
}
});
}
fn into_cloneable(self) -> Self::Cloneable {
#[cfg(feature = "tracing")]
tracing::error!("Suspended attributes cannot be spread");
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
#[cfg(feature = "tracing")]
tracing::error!("Suspended attributes cannot be spread");
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self.inner.await
}
}
/// A reactive function that can be shared across multiple locations and across threads.
pub type SharedReactiveFunction<T> = Arc<Mutex<dyn FnMut() -> T + Send>>;
/// A reactive view function.
pub trait ReactiveFunction: Send + 'static {
/// The return type of the function.
type Output;
/// Call the function.
fn invoke(&mut self) -> Self::Output;
/// Converts the function into a cloneable, shared type.
fn into_shared(self) -> Arc<Mutex<dyn FnMut() -> Self::Output + Send>>;
}
impl<T: 'static> ReactiveFunction for Arc<Mutex<dyn FnMut() -> T + Send>> {
type Output = T;
fn invoke(&mut self) -> Self::Output {
let mut fun = self.lock().expect("lock poisoned");
fun()
}
fn into_shared(self) -> Arc<Mutex<dyn FnMut() -> Self::Output + Send>> {
self
}
}
impl<T: Send + Sync + 'static> ReactiveFunction
for Arc<dyn Fn() -> T + Send + Sync>
{
type Output = T;
fn invoke(&mut self) -> Self::Output {
self()
}
fn into_shared(self) -> Arc<Mutex<dyn FnMut() -> Self::Output + Send>> {
Arc::new(Mutex::new(move || self()))
}
}
impl<F, T> ReactiveFunction for F
where
F: FnMut() -> T + Send + 'static,
{
type Output = T;
fn invoke(&mut self) -> Self::Output {
self()
}
fn into_shared(self) -> Arc<Mutex<dyn FnMut() -> Self::Output + Send>> {
Arc::new(Mutex::new(self))
}
}
macro_rules! reactive_impl {
($name:ident, <$($gen:ident),*>, $v:ty, $dry_resolve:literal, $( $where_clause:tt )*) =>
{
#[allow(deprecated)]
impl<$($gen),*> Render for $name<$($gen),*>
where
$v: Render + Clone + Send + Sync + 'static,
<$v as Render>::State: 'static,
$($where_clause)*
{
type State = RenderEffectState<<$v as Render>::State>;
#[track_caller]
fn build(self) -> Self::State {
(move || self.get()).build()
}
#[track_caller]
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();
}
}
#[allow(deprecated)]
impl<$($gen),*> AddAnyAttr for $name<$($gen),*>
where
$v: RenderHtml + Clone + Send + Sync + 'static,
<$v as Render>::State: 'static,
$($where_clause)*
{
type Output<SomeNewAttr: Attribute> = Self;
fn add_any_attr<NewAttr: Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr> {
todo!()
}
}
#[allow(deprecated)]
impl<$($gen),*> RenderHtml for $name<$($gen),*>
where
$v: RenderHtml + Clone + Send + Sync + 'static,
<$v as Render>::State: 'static,
$($where_clause)*
{
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
if $dry_resolve {
_ = self.get();
}
}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn html_len(&self) -> usize {
<$v>::MIN_LENGTH
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
let value = self.get();
value.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,
{
let value = self.get();
value.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 {
(move || self.get())
.hydrate::<FROM_SERVER>(cursor, position)
}
fn into_owned(self) -> Self::Owned {
self
}
}
#[allow(deprecated)]
impl<$($gen),*> AttributeValue for $name<$($gen),*>
where
$v: AttributeValue + Send + Sync + Clone + 'static,
<$v as AttributeValue>::State: 'static,
$($where_clause)*
{
type AsyncOutput = Self;
type State = RenderEffect<<$v as AttributeValue>::State>;
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
0
}
fn to_html(self, key: &str, buf: &mut String) {
let value = self.get();
value.to_html(key, buf);
}
fn to_template(_key: &str, _buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
key: &str,
el: &crate::renderer::types::Element,
) -> Self::State {
(move || self.get()).hydrate::<FROM_SERVER>(key, el)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
(move || self.get()).build(el, key)
}
fn rebuild(self, key: &str, state: &mut Self::State) {
(move || self.get()).rebuild(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
}
}
};
}
#[cfg(not(feature = "nightly"))]
mod stable {
use super::RenderEffectState;
use crate::{
html::attribute::{
any_attribute::AnyAttribute, Attribute, AttributeValue,
},
hydration::Cursor,
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml,
},
};
#[allow(deprecated)]
use reactive_graph::wrappers::read::MaybeSignal;
use reactive_graph::{
computed::{ArcMemo, Memo},
effect::RenderEffect,
owner::Storage,
signal::{ArcReadSignal, ArcRwSignal, ReadSignal, RwSignal},
traits::Get,
wrappers::read::{ArcSignal, Signal},
};
reactive_impl!(
RwSignal,
<V, S>,
V,
false,
RwSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
reactive_impl!(
ReadSignal,
<V, S>,
V,
false,
ReadSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
reactive_impl!(
Memo,
<V, S>,
V,
true,
Memo<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
reactive_impl!(
Signal,
<V, S>,
V,
true,
Signal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
reactive_impl!(
MaybeSignal,
<V, S>,
V,
true,
MaybeSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
reactive_impl!(ArcRwSignal, <V>, V, false, ArcRwSignal<V>: Get<Value = V>);
reactive_impl!(ArcReadSignal, <V>, V, false, ArcReadSignal<V>: Get<Value = V>);
reactive_impl!(ArcMemo, <V>, V, false, ArcMemo<V>: Get<Value = V>);
reactive_impl!(ArcSignal, <V>, V, true, ArcSignal<V>: Get<Value = V>);
}
#[cfg(feature = "reactive_stores")]
mod reactive_stores {
use super::RenderEffectState;
use crate::{
html::attribute::{
any_attribute::AnyAttribute, Attribute, AttributeValue,
},
hydration::Cursor,
ssr::StreamBuilder,
view::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml,
},
};
#[allow(deprecated)]
use reactive_graph::{effect::RenderEffect, owner::Storage, traits::Get};
use reactive_stores::{
ArcField, ArcStore, AtIndex, AtKeyed, DerefedField, Field,
KeyedSubfield, Store, StoreField, Subfield,
};
use std::ops::{Deref, DerefMut, Index, IndexMut};
reactive_impl!(
Subfield,
<Inner, Prev, V>,
V,
false,
Subfield<Inner, Prev, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
);
reactive_impl!(
AtKeyed,
<Inner, Prev, K, V>,
V,
false,
AtKeyed<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
reactive_impl!(
KeyedSubfield,
<Inner, Prev, K, V>,
V,
false,
KeyedSubfield<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
reactive_impl!(
DerefedField,
<S>,
<S::Value as Deref>::Target,
false,
S: Clone + StoreField + Send + Sync + 'static,
<S as StoreField>::Value: Deref + DerefMut
);
reactive_impl!(
AtIndex,
<Inner, Prev>,
<Prev as Index<usize>>::Output,
false,
AtIndex<Inner, Prev>: Get<Value = Prev::Output>,
Prev: Send + Sync + IndexMut<usize> + 'static,
Inner: Send + Sync + Clone + 'static,
);
reactive_impl!(
Store,
<V, S>,
V,
false,
Store<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
reactive_impl!(
Field,
<V, S>,
V,
false,
Field<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
reactive_impl!(ArcStore, <V>, V, false, ArcStore<V>: Get<Value = V>);
reactive_impl!(ArcField, <V>, V, false, ArcField<V>: Get<Value = V>);
}
/*
#[cfg(test)]
mod tests {
use crate::{
html::element::{button, main, HtmlElement},
renderer::mock_dom::MockDom,
view::Render,
};
use leptos_reactive::{create_runtime, RwSignal, SignalGet, SignalSet};
#[test]
fn create_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> =
button((), move || count.get().to_string());
let el = app.build();
assert_eq!(el.el.to_debug_html(), "<button>0</button>");
count.set(1);
assert_eq!(el.el.to_debug_html(), "<button>1</button>");
rt.dispose();
}
#[test]
fn update_dynamic_element_among_siblings() {
let rt = create_runtime();
let count = RwSignal::new(0);
let app: HtmlElement<_, _, _, MockDom> = main(
(),
button(
(),
("Hello, my ", move || count.get().to_string(), " friends."),
),
);
let el = app.build();
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 0 friends.</button></main>"
);
count.set(42);
assert_eq!(
el.el.to_debug_html(),
"<main><button>Hello, my 42 friends.</button></main>"
);
rt.dispose();
}
}
*/
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/style.rs | tachys/src/reactive_graph/style.rs | use super::{ReactiveFunction, SharedReactiveFunction};
use crate::{
html::style::{IntoStyle, IntoStyleValue},
renderer::Rndr,
};
use reactive_graph::effect::RenderEffect;
use std::sync::Arc;
impl<F, S> IntoStyleValue for F
where
F: ReactiveFunction<Output = S>,
S: IntoStyleValue + 'static,
{
type AsyncOutput = Self;
type State = (Arc<str>, RenderEffect<S::State>);
type Cloneable = SharedReactiveFunction<S>;
type CloneableOwned = SharedReactiveFunction<S>;
fn to_html(self, name: &str, style: &mut String) {
let mut f = self;
let value = f.invoke();
value.to_html(name, style);
}
fn build(
mut self,
style: &crate::renderer::dom::CssStyleDeclaration,
name: &str,
) -> Self::State {
let name: Arc<str> = Rndr::intern(name).into();
let style = style.to_owned();
(
Arc::clone(&name),
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&style, &name, &mut state);
state
} else {
value.build(&style, &name)
}
}),
)
}
fn rebuild(
mut self,
style: &crate::renderer::dom::CssStyleDeclaration,
name: &str,
state: &mut Self::State,
) {
let (prev_name, prev_effect) = state;
let mut prev_value = prev_effect.take_value();
if name != prev_name.as_ref() {
Rndr::remove_css_property(style, prev_name.as_ref());
prev_value = None;
}
let name: Arc<str> = name.into();
let style = style.to_owned();
*state = (
Arc::clone(&name),
RenderEffect::new_with_value(
move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&style, &name, &mut state);
state
} else {
value.build(&style, &name)
}
},
prev_value,
),
);
}
fn hydrate(
mut self,
style: &crate::renderer::dom::CssStyleDeclaration,
name: &str,
) -> Self::State {
let name: Arc<str> = Rndr::intern(name).into();
let style = style.to_owned();
(
Arc::clone(&name),
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&style, &name, &mut state);
state
} else {
value.hydrate(&style, &name)
}
}),
)
}
fn into_cloneable(self) -> Self::Cloneable {
self.into_shared()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into_shared()
}
fn dry_resolve(&mut self) {
self.invoke();
}
async fn resolve(self) -> Self::AsyncOutput {
self
}
}
impl<F, C> IntoStyle for F
where
F: ReactiveFunction<Output = C>,
C: IntoStyle + 'static,
C::State: 'static,
{
type AsyncOutput = C::AsyncOutput;
type State = RenderEffect<C::State>;
type Cloneable = SharedReactiveFunction<C>;
type CloneableOwned = SharedReactiveFunction<C>;
fn to_html(mut self, style: &mut String) {
let value = self.invoke();
value.to_html(style);
}
fn hydrate<const FROM_SERVER: bool>(
mut self,
el: &crate::renderer::types::Element,
) -> Self::State {
// TODO FROM_SERVER vs template
let el = el.clone();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&el)
}
})
}
fn build(mut self, el: &crate::renderer::types::Element) -> Self::State {
let el = el.clone();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build(&el)
}
})
}
fn rebuild(mut self, state: &mut Self::State) {
let prev_value = state.take_value();
*state = RenderEffect::new_with_value(
move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
unreachable!()
}
},
prev_value,
);
}
fn into_cloneable(self) -> Self::Cloneable {
self.into_shared()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into_shared()
}
fn dry_resolve(&mut self) {
self.invoke();
}
async fn resolve(mut self) -> Self::AsyncOutput {
self.invoke().resolve().await
}
fn reset(state: &mut Self::State) {
*state = RenderEffect::new_with_value(
move |prev| {
if let Some(mut state) = prev {
C::reset(&mut state);
state
} else {
unreachable!()
}
},
state.take_value(),
);
}
}
macro_rules! style_reactive {
($name:ident, <$($gen:ident),*>, $v:ty, $( $where_clause:tt )*) =>
{
#[allow(deprecated)]
impl<$($gen),*> IntoStyle for $name<$($gen),*>
where
$v: IntoStyle + Clone + Send + Sync + 'static,
<$v as IntoStyle>::State: 'static,
$($where_clause)*
{
type AsyncOutput = Self;
type State = RenderEffect<<$v as IntoStyle>::State>;
type Cloneable = Self;
type CloneableOwned = Self;
fn to_html(self, style: &mut String) {
let value = self.get();
value.to_html(style);
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
(move || self.get()).hydrate::<FROM_SERVER>(el)
}
fn build(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
(move || self.get()).build(el)
}
fn rebuild(self, state: &mut Self::State) {
(move || self.get()).rebuild(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
}
fn reset(state: &mut Self::State) {
*state = RenderEffect::new_with_value(
move |prev| {
if let Some(mut state) = prev {
<$v>::reset(&mut state);
state
} else {
unreachable!()
}
},
state.take_value(),
);
}
}
#[allow(deprecated)]
impl<$($gen),*> IntoStyleValue for $name<$($gen),*>
where
$v: IntoStyleValue + Send + Sync + Clone + 'static,
$($where_clause)*
{
type AsyncOutput = Self;
type State = (Arc<str>, RenderEffect<<$v as IntoStyleValue>::State>);
type Cloneable = $name<$($gen),*>;
type CloneableOwned = $name<$($gen),*>;
fn to_html(self, name: &str, style: &mut String) {
IntoStyleValue::to_html(move || self.get(), name, style)
}
fn build(
self,
style: &crate::renderer::dom::CssStyleDeclaration,
name: &str,
) -> Self::State {
IntoStyleValue::build(move || self.get(), style, name)
}
fn rebuild(
self,
style: &crate::renderer::dom::CssStyleDeclaration,
name: &str,
state: &mut Self::State,
) {
IntoStyleValue::rebuild(
move || self.get(),
style,
name,
state,
)
}
fn hydrate(
self,
style: &crate::renderer::dom::CssStyleDeclaration,
name: &str,
) -> Self::State {
IntoStyleValue::hydrate(move || self.get(), style, name)
}
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
}
}
};
}
#[cfg(not(feature = "nightly"))]
mod stable {
use super::RenderEffect;
use crate::html::style::{IntoStyle, IntoStyleValue};
#[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;
style_reactive!(
RwSignal,
<V, S>,
V,
RwSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
style_reactive!(
ReadSignal,
<V, S>,
V,
ReadSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
style_reactive!(
Memo,
<V, S>,
V,
Memo<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
style_reactive!(
Signal,
<V, S>,
V,
Signal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
style_reactive!(
MaybeSignal,
<V, S>,
V,
MaybeSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
style_reactive!(ArcRwSignal, <V>, V, ArcRwSignal<V>: Get<Value = V>);
style_reactive!(ArcReadSignal, <V>, V, ArcReadSignal<V>: Get<Value = V>);
style_reactive!(ArcMemo, <V>, V, ArcMemo<V>: Get<Value = V>);
style_reactive!(ArcSignal, <V>, V, ArcSignal<V>: Get<Value = V>);
}
#[cfg(feature = "reactive_stores")]
mod reactive_stores {
use super::RenderEffect;
use crate::html::style::{IntoStyle, IntoStyleValue};
#[allow(deprecated)]
use reactive_graph::{owner::Storage, traits::Get};
use reactive_stores::{
ArcField, ArcStore, AtIndex, AtKeyed, DerefedField, Field,
KeyedSubfield, Store, StoreField, Subfield,
};
use std::{
ops::{Deref, DerefMut, Index, IndexMut},
sync::Arc,
};
style_reactive!(
Subfield,
<Inner, Prev, V>,
V,
Subfield<Inner, Prev, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
);
style_reactive!(
AtKeyed,
<Inner, Prev, K, V>,
V,
AtKeyed<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
style_reactive!(
KeyedSubfield,
<Inner, Prev, K, V>,
V,
KeyedSubfield<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
style_reactive!(
DerefedField,
<S>,
<S::Value as Deref>::Target,
S: Clone + StoreField + Send + Sync + 'static,
<S as StoreField>::Value: Deref + DerefMut
);
style_reactive!(
AtIndex,
<Inner, Prev>,
<Prev as Index<usize>>::Output,
AtIndex<Inner, Prev>: Get<Value = Prev::Output>,
Prev: Send + Sync + IndexMut<usize> + 'static,
Inner: Send + Sync + Clone + 'static,
);
style_reactive!(
Store,
<V, S>,
V,
Store<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
style_reactive!(
Field,
<V, S>,
V,
Field<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
style_reactive!(ArcStore, <V>, V, ArcStore<V>: Get<Value = V>);
style_reactive!(ArcField, <V>, V, ArcField<V>: Get<Value = V>);
}
/*
impl<Fut> IntoStyle for Suspend<Fut>
where
Fut: Clone + Future + Send + 'static,
Fut::Output: IntoStyle,
{
type AsyncOutput = Fut::Output;
type State = Rc<RefCell<Option<<Fut::Output as IntoStyle>::State>>>;
type Cloneable = Self;
type CloneableOwned = Self;
fn to_html(self, style: &mut String) {
if let Some(inner) = self.inner.now_or_never() {
inner.to_html(style);
} else {
panic!("You cannot use Suspend on an attribute outside Suspense");
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
let el = el.to_owned();
let state = Rc::new(RefCell::new(None));
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&state);
async move {
*state.borrow_mut() =
Some(self.inner.await.hydrate::<FROM_SERVER>(&el));
self.subscriber.forward();
}
});
state
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
let el = el.to_owned();
let state = Rc::new(RefCell::new(None));
reactive_graph::spawn_local_scoped({
let state = Rc::clone(&state);
async move {
*state.borrow_mut() = Some(self.inner.await.build(&el));
self.subscriber.forward();
}
});
state
}
fn rebuild(self, state: &mut Self::State) {
reactive_graph::spawn_local_scoped({
let state = Rc::clone(state);
async move {
let value = self.inner.await;
let mut state = state.borrow_mut();
if let Some(state) = state.as_mut() {
value.rebuild(state);
}
self.subscriber.forward();
}
});
}
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.inner.await
}
}
*/
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/inner_html.rs | tachys/src/reactive_graph/inner_html.rs | use super::{ReactiveFunction, SharedReactiveFunction};
use crate::html::element::InnerHtmlValue;
use reactive_graph::effect::RenderEffect;
impl<F, V> InnerHtmlValue for F
where
F: ReactiveFunction<Output = V>,
V: InnerHtmlValue + 'static,
V::State: 'static,
{
type AsyncOutput = V::AsyncOutput;
type State = RenderEffect<V::State>;
type Cloneable = SharedReactiveFunction<V>;
type CloneableOwned = SharedReactiveFunction<V>;
fn html_len(&self) -> usize {
0
}
fn to_html(mut self, buf: &mut String) {
let value = self.invoke();
value.to_html(buf);
}
fn to_template(_buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
mut self,
el: &crate::renderer::types::Element,
) -> Self::State {
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.hydrate::<FROM_SERVER>(&el)
}
})
}
fn build(mut self, el: &crate::renderer::types::Element) -> Self::State {
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
value.build(&el)
}
})
}
fn rebuild(mut self, state: &mut Self::State) {
let prev_value = state.take_value();
*state = RenderEffect::new_with_value(
move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state);
state
} else {
unreachable!()
}
},
prev_value,
);
}
fn into_cloneable(self) -> Self::Cloneable {
self.into_shared()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into_shared()
}
fn dry_resolve(&mut self) {
self.invoke();
}
async fn resolve(mut self) -> Self::AsyncOutput {
self.invoke().resolve().await
}
}
macro_rules! inner_html_reactive {
($name:ident, <$($gen:ident),*>, $v:ty, $( $where_clause:tt )*) =>
{
#[allow(deprecated)]
impl<$($gen),*> InnerHtmlValue for $name<$($gen),*>
where
$v: InnerHtmlValue + Clone + Send + Sync + 'static,
<$v as InnerHtmlValue>::State: 'static,
$($where_clause)*
{
type AsyncOutput = Self;
type State = RenderEffect<<$v as InnerHtmlValue>::State>;
type Cloneable = Self;
type CloneableOwned = Self;
fn html_len(&self) -> usize {
0
}
fn to_html(self, buf: &mut String) {
let value = self.get();
value.to_html(buf);
}
fn to_template(_buf: &mut String) {}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
(move || self.get()).hydrate::<FROM_SERVER>(el)
}
fn build(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
(move || self.get()).build(el)
}
fn rebuild(self, state: &mut Self::State) {
(move || self.get()).rebuild(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
}
}
};
}
#[cfg(not(feature = "nightly"))]
mod stable {
use crate::html::element::InnerHtmlValue;
#[allow(deprecated)]
use reactive_graph::wrappers::read::MaybeSignal;
use reactive_graph::{
computed::{ArcMemo, Memo},
effect::RenderEffect,
owner::Storage,
signal::{ArcReadSignal, ArcRwSignal, ReadSignal, RwSignal},
traits::Get,
wrappers::read::{ArcSignal, Signal},
};
inner_html_reactive!(
RwSignal,
<V, S>,
V,
RwSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
inner_html_reactive!(
ReadSignal,
<V, S>,
V,
ReadSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
inner_html_reactive!(
Memo,
<V, S>,
V,
Memo<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
inner_html_reactive!(
Signal,
<V, S>,
V,
Signal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
inner_html_reactive!(
MaybeSignal,
<V, S>,
V,
MaybeSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
inner_html_reactive!(ArcRwSignal, <V>, V, ArcRwSignal<V>: Get<Value = V>);
inner_html_reactive!(ArcReadSignal, <V>, V, ArcReadSignal<V>: Get<Value = V>);
inner_html_reactive!(ArcMemo, <V>, V, ArcMemo<V>: Get<Value = V>);
inner_html_reactive!(ArcSignal, <V>, V, ArcSignal<V>: Get<Value = V>);
}
#[cfg(feature = "reactive_stores")]
mod reactive_stores {
use crate::html::element::InnerHtmlValue;
#[allow(deprecated)]
use reactive_graph::{effect::RenderEffect, owner::Storage, traits::Get};
use reactive_stores::{
ArcField, ArcStore, AtIndex, AtKeyed, DerefedField, Field,
KeyedSubfield, Store, StoreField, Subfield,
};
use std::ops::{Deref, DerefMut, Index, IndexMut};
inner_html_reactive!(
Subfield,
<Inner, Prev, V>,
V,
Subfield<Inner, Prev, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
);
inner_html_reactive!(
AtKeyed,
<Inner, Prev, K, V>,
V,
AtKeyed<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
inner_html_reactive!(
KeyedSubfield,
<Inner, Prev, K, V>,
V,
KeyedSubfield<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
inner_html_reactive!(
DerefedField,
<S>,
<S::Value as Deref>::Target,
S: Clone + StoreField + Send + Sync + 'static,
<S as StoreField>::Value: Deref + DerefMut
);
inner_html_reactive!(
AtIndex,
<Inner, Prev>,
<Prev as Index<usize>>::Output,
AtIndex<Inner, Prev>: Get<Value = Prev::Output>,
Prev: Send + Sync + IndexMut<usize> + 'static,
Inner: Send + Sync + Clone + 'static,
);
inner_html_reactive!(
Store,
<V, S>,
V,
Store<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
inner_html_reactive!(
Field,
<V, S>,
V,
Field<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
inner_html_reactive!(ArcStore, <V>, V, ArcStore<V>: Get<Value = V>);
inner_html_reactive!(ArcField, <V>, V, ArcField<V>: Get<Value = V>);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/reactive_graph/property.rs | tachys/src/reactive_graph/property.rs | use super::{ReactiveFunction, SharedReactiveFunction};
use crate::{html::property::IntoProperty, renderer::Rndr};
use reactive_graph::effect::RenderEffect;
// These do update during hydration because properties don't exist in the DOM
impl<F, V> IntoProperty for F
where
F: ReactiveFunction<Output = V>,
V: IntoProperty + 'static,
V::State: 'static,
{
type State = RenderEffect<V::State>;
type Cloneable = SharedReactiveFunction<V>;
type CloneableOwned = SharedReactiveFunction<V>;
fn hydrate<const FROM_SERVER: bool>(
mut self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
let key = Rndr::intern(key);
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state, &key);
state
} else {
value.hydrate::<FROM_SERVER>(&el, &key)
}
})
}
fn build(
mut self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
let key = Rndr::intern(key);
let key = key.to_owned();
let el = el.to_owned();
RenderEffect::new(move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state, &key);
state
} else {
value.build(&el, &key)
}
})
}
fn rebuild(mut self, state: &mut Self::State, key: &str) {
let prev_value = state.take_value();
let key = key.to_owned();
*state = RenderEffect::new_with_value(
move |prev| {
let value = self.invoke();
if let Some(mut state) = prev {
value.rebuild(&mut state, &key);
state
} else {
unreachable!()
}
},
prev_value,
);
}
fn into_cloneable(self) -> Self::Cloneable {
self.into_shared()
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self.into_shared()
}
}
macro_rules! property_reactive {
($name:ident, <$($gen:ident),*>, $v:ty, $( $where_clause:tt )*) =>
{
#[allow(deprecated)]
impl<$($gen),*> IntoProperty for $name<$($gen),*>
where
$v: IntoProperty + Clone + Send + Sync + 'static,
<$v as IntoProperty>::State: 'static,
$($where_clause)*
{
type State = RenderEffect<<$v as IntoProperty>::State>;
type Cloneable = Self;
type CloneableOwned = Self;
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
(move || self.get()).hydrate::<FROM_SERVER>(el, key)
}
fn build(
self,
el: &crate::renderer::types::Element,
key: &str,
) -> Self::State {
(move || self.get()).build(el, key)
}
fn rebuild(self, state: &mut Self::State, key: &str) {
(move || self.get()).rebuild(state, key)
}
fn into_cloneable(self) -> Self::Cloneable {
self
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
self
}
}
};
}
#[cfg(not(feature = "nightly"))]
mod stable {
use crate::html::property::IntoProperty;
#[allow(deprecated)]
use reactive_graph::wrappers::read::MaybeSignal;
use reactive_graph::{
computed::{ArcMemo, Memo},
effect::RenderEffect,
owner::Storage,
signal::{ArcReadSignal, ArcRwSignal, ReadSignal, RwSignal},
traits::Get,
wrappers::read::{ArcSignal, Signal},
};
property_reactive!(
RwSignal,
<V, S>,
V,
RwSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
property_reactive!(
ReadSignal,
<V, S>,
V,
ReadSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
property_reactive!(
Memo,
<V, S>,
V,
Memo<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
property_reactive!(
Signal,
<V, S>,
V,
Signal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
property_reactive!(
MaybeSignal,
<V, S>,
V,
MaybeSignal<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
property_reactive!(ArcRwSignal, <V>, V, ArcRwSignal<V>: Get<Value = V>);
property_reactive!(ArcReadSignal, <V>, V, ArcReadSignal<V>: Get<Value = V>);
property_reactive!(ArcMemo, <V>, V, ArcMemo<V>: Get<Value = V>);
property_reactive!(ArcSignal, <V>, V, ArcSignal<V>: Get<Value = V>);
}
#[cfg(feature = "reactive_stores")]
mod reactive_stores {
use crate::html::property::IntoProperty;
#[allow(deprecated)]
use reactive_graph::{effect::RenderEffect, owner::Storage, traits::Get};
use reactive_stores::{
ArcField, ArcStore, AtIndex, AtKeyed, DerefedField, Field,
KeyedSubfield, Store, StoreField, Subfield,
};
use std::ops::{Deref, DerefMut, Index, IndexMut};
property_reactive!(
Subfield,
<Inner, Prev, V>,
V,
Subfield<Inner, Prev, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
);
property_reactive!(
AtKeyed,
<Inner, Prev, K, V>,
V,
AtKeyed<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
property_reactive!(
KeyedSubfield,
<Inner, Prev, K, V>,
V,
KeyedSubfield<Inner, Prev, K, V>: Get<Value = V>,
Prev: Send + Sync + 'static,
Inner: Send + Sync + Clone + 'static,
K: Send + Sync + std::fmt::Debug + Clone + 'static,
for<'a> &'a V: IntoIterator,
);
property_reactive!(
DerefedField,
<S>,
<S::Value as Deref>::Target,
S: Clone + StoreField + Send + Sync + 'static,
<S as StoreField>::Value: Deref + DerefMut
);
property_reactive!(
AtIndex,
<Inner, Prev>,
<Prev as Index<usize>>::Output,
AtIndex<Inner, Prev>: Get<Value = Prev::Output>,
Prev: Send + Sync + IndexMut<usize> + 'static,
Inner: Send + Sync + Clone + 'static,
);
property_reactive!(
Store,
<V, S>,
V,
Store<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
property_reactive!(
Field,
<V, S>,
V,
Field<V, S>: Get<Value = V>,
S: Storage<V> + Storage<Option<V>>,
S: Send + Sync + 'static,
);
property_reactive!(ArcStore, <V>, V, ArcStore<V>: Get<Value = V>);
property_reactive!(ArcField, <V>, V, ArcField<V>: Get<Value = V>);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/add_attr.rs | tachys/src/view/add_attr.rs | use super::RenderHtml;
use crate::html::attribute::Attribute;
/// Allows adding a new attribute to some type, before it is rendered.
/// This takes place at compile time as part of the builder syntax for creating a statically typed
/// view tree.
///
/// Normally, this is used to add an attribute to an HTML element. But it is required to be
/// implemented for all types that implement [`RenderHtml`], so that attributes can be spread onto
/// other structures like the return type of a component.
pub trait AddAnyAttr {
/// The new type once the attribute has been added.
type Output<SomeNewAttr: Attribute>: RenderHtml;
/// Adds an attribute to the view.
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml;
}
/// Declares that spreading attributes onto a particular type has no effect.
#[macro_export]
macro_rules! no_attrs {
($ty_name:ty) => {
impl<'a> $crate::view::add_attr::AddAnyAttr for $ty_name {
type Output<SomeNewAttr: $crate::html::attribute::Attribute> =
$ty_name;
fn add_any_attr<NewAttr: $crate::html::attribute::Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr> {
self
}
}
};
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/error_boundary.rs | tachys/src/view/error_boundary.rs | use super::{add_attr::AddAnyAttr, Position, PositionState, RenderHtml};
use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
ssr::StreamBuilder,
view::{iterators::OptionState, Mountable, Render},
};
use either_of::Either;
use std::sync::Arc;
use throw_error::{Error as AnyError, ErrorHook};
impl<T, E> Render for Result<T, E>
where
T: Render,
E: Into<AnyError> + 'static,
{
type State = ResultState<T>;
fn build(self) -> Self::State {
let hook = throw_error::get_error_hook();
let (state, error) = match self {
Ok(view) => (Either::Left(view.build()), None),
Err(e) => (
Either::Right(Render::build(())),
Some(throw_error::throw(e.into())),
),
};
ResultState { state, error, hook }
}
fn rebuild(self, state: &mut Self::State) {
let _guard = state.hook.clone().map(throw_error::set_error_hook);
match (&mut state.state, self) {
// both errors: throw the new error and replace
(Either::Right(_), Err(new)) => {
if let Some(old_error) = state.error.take() {
throw_error::clear(&old_error);
}
state.error = Some(throw_error::throw(new.into()));
}
// both Ok: need to rebuild child
(Either::Left(old), Ok(new)) => {
T::rebuild(new, old);
}
// Ok => Err: unmount, replace with marker, and throw
(Either::Left(old), Err(err)) => {
let mut new_state = Render::build(());
old.insert_before_this(&mut new_state);
old.unmount();
state.state = Either::Right(new_state);
state.error = Some(throw_error::throw(err));
}
// Err => Ok: clear error and build
(Either::Right(old), Ok(new)) => {
if let Some(err) = state.error.take() {
throw_error::clear(&err);
}
let mut new_state = new.build();
old.insert_before_this(&mut new_state);
old.unmount();
state.state = Either::Left(new_state);
}
}
}
}
/// View state for a `Result<_, _>` view.
pub struct ResultState<T>
where
T: Render,
{
/// The view state.
state: OptionState<T>,
error: Option<throw_error::ErrorId>,
hook: Option<Arc<dyn ErrorHook>>,
}
impl<T> Drop for ResultState<T>
where
T: Render,
{
fn drop(&mut self) {
// when the state is cleared, unregister this error; this item is being dropped and its
// error should no longer be shown
if let Some(e) = self.error.take() {
throw_error::clear(&e);
}
}
}
impl<T> Mountable for ResultState<T>
where
T: Render,
{
fn unmount(&mut self) {
self.state.unmount();
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
self.state.mount(parent, marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.state.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.state.elements()
}
}
impl<T, E> AddAnyAttr for Result<T, E>
where
T: AddAnyAttr,
E: Into<AnyError> + Send + 'static,
{
type Output<SomeNewAttr: Attribute> =
Result<<T as AddAnyAttr>::Output<SomeNewAttr>, E>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
self.map(|inner| inner.add_any_attr(attr))
}
}
impl<T, E> RenderHtml for Result<T, E>
where
T: RenderHtml,
E: Into<AnyError> + Send + 'static,
{
type AsyncOutput = Result<T::AsyncOutput, E>;
type Owned = Result<T::Owned, E>;
const MIN_LENGTH: usize = T::MIN_LENGTH;
fn dry_resolve(&mut self) {
if let Ok(inner) = self.as_mut() {
inner.dry_resolve()
}
}
async fn resolve(self) -> Self::AsyncOutput {
match self {
Ok(view) => Ok(view.resolve().await),
Err(e) => Err(e),
}
}
fn html_len(&self) -> usize {
match self {
Ok(i) => i.html_len() + 3,
Err(_) => 0,
}
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut super::Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
match self {
Ok(inner) => {
inner.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
}
Err(e) => {
buf.push_str("<!>");
throw_error::throw(e);
}
}
}
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,
{
match self {
Ok(inner) => inner.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
),
Err(e) => {
buf.push_sync("<!>");
throw_error::throw(e);
}
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let hook = throw_error::get_error_hook();
let (state, error) = match self {
Ok(view) => (
Either::Left(view.hydrate::<FROM_SERVER>(cursor, position)),
None,
),
Err(e) => {
let state =
RenderHtml::hydrate::<FROM_SERVER>((), cursor, position);
(Either::Right(state), Some(throw_error::throw(e.into())))
}
};
ResultState { state, error, hook }
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let hook = throw_error::get_error_hook();
let (state, error) = match self {
Ok(view) => (
Either::Left(view.hydrate_async(cursor, position).await),
None,
),
Err(e) => {
let state =
RenderHtml::hydrate_async((), cursor, position).await;
(Either::Right(state), Some(throw_error::throw(e.into())))
}
};
ResultState { state, error, hook }
}
fn into_owned(self) -> Self::Owned {
match self {
Ok(view) => Ok(view.into_owned()),
Err(e) => Err(e),
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/fragment.rs | tachys/src/view/fragment.rs | use super::{
any_view::{AnyView, IntoAny},
iterators::StaticVec,
};
use crate::html::element::HtmlElement;
/// A typed-erased collection of different views.
pub struct Fragment {
/// The nodes contained in the fragment.
pub nodes: StaticVec<AnyView>,
}
/// Converts some view into a type-erased collection of views.
pub trait IntoFragment {
/// Converts some view into a type-erased collection of views.
fn into_fragment(self) -> Fragment;
}
impl FromIterator<AnyView> for Fragment {
fn from_iter<T: IntoIterator<Item = AnyView>>(iter: T) -> Self {
Fragment::new(iter.into_iter().collect())
}
}
impl From<AnyView> for Fragment {
fn from(view: AnyView) -> Self {
Fragment::new(vec![view])
}
}
impl From<Fragment> for AnyView {
fn from(value: Fragment) -> Self {
value.nodes.into_any()
}
}
impl Fragment {
/// Creates a new [`Fragment`].
#[inline(always)]
pub fn new(nodes: Vec<AnyView>) -> Self {
Self {
nodes: nodes.into(),
}
}
}
impl<E, At, Ch> IntoFragment for HtmlElement<E, At, Ch>
where
HtmlElement<E, At, Ch>: IntoAny,
{
fn into_fragment(self) -> Fragment {
Fragment::new(vec![self.into_any()])
}
}
impl IntoFragment for AnyView {
fn into_fragment(self) -> Fragment {
Fragment::new(vec![self])
}
}
impl<T> IntoFragment for Vec<T>
where
T: IntoAny,
{
fn into_fragment(self) -> Fragment {
Fragment::new(self.into_iter().map(IntoAny::into_any).collect())
}
}
impl<T> IntoFragment for StaticVec<T>
where
T: IntoAny,
{
fn into_fragment(self) -> Fragment {
Fragment::new(self.into_iter().map(IntoAny::into_any).collect())
}
}
impl<const N: usize, T> IntoFragment for [T; N]
where
T: IntoAny,
{
fn into_fragment(self) -> Fragment {
Fragment::new(self.into_iter().map(IntoAny::into_any).collect())
}
}
macro_rules! tuples {
($($ty:ident),*) => {
impl<$($ty),*> IntoFragment for ($($ty,)*)
where
$($ty: IntoAny),*,
{
fn into_fragment(self) -> Fragment {
#[allow(non_snake_case)]
let ($($ty,)*) = self;
Fragment::new(vec![$($ty.into_any(),)*])
}
}
}
}
tuples!(A);
tuples!(A, B);
tuples!(A, B, C);
tuples!(A, B, C, D);
tuples!(A, B, C, D, E);
tuples!(A, B, C, D, E, F);
tuples!(A, B, C, D, E, F, G);
tuples!(A, B, C, D, E, F, G, H);
tuples!(A, B, C, D, E, F, G, H, I);
tuples!(A, B, C, D, E, F, G, H, I, J);
tuples!(A, B, C, D, E, F, G, H, I, J, K);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W);
tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X);
tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/any_view.rs | tachys/src/view/any_view.rs | #![allow(clippy::type_complexity)]
#[cfg(feature = "ssr")]
use super::MarkBranch;
use super::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml,
};
use crate::{
erased::{Erased, ErasedLocal},
html::attribute::{
any_attribute::{AnyAttribute, AnyAttributeState, IntoAnyAttribute},
Attribute,
},
hydration::Cursor,
renderer::Rndr,
ssr::StreamBuilder,
};
use futures::future::{join, join_all};
use std::{any::TypeId, fmt::Debug};
#[cfg(any(feature = "ssr", feature = "hydrate"))]
use std::{future::Future, pin::Pin};
/// A type-erased view. This can be used if control flow requires that multiple different types of
/// view must be received, and it is either impossible or too cumbersome to use the `EitherOf___`
/// enums.
///
/// It can also be used to create recursive components, which otherwise cannot return themselves
/// due to the static typing of the view tree.
///
/// Generally speaking, using `AnyView` restricts the amount of information available to the
/// compiler and should be limited to situations in which it is necessary to preserve the maximum
/// amount of type information possible.
pub struct AnyView {
type_id: TypeId,
value: Erased,
build: fn(Erased) -> AnyViewState,
rebuild: fn(Erased, &mut AnyViewState),
// The fields below are cfg-gated so they will not be included in WASM bundles if not needed.
// Ordinarily, the compiler can simply omit this dead code because the methods are not called.
// With this type-erased wrapper, however, the compiler is not *always* able to correctly
// eliminate that code.
#[cfg(feature = "ssr")]
html_len: usize,
#[cfg(feature = "ssr")]
to_html:
fn(Erased, &mut String, &mut Position, bool, bool, Vec<AnyAttribute>),
#[cfg(feature = "ssr")]
to_html_async: fn(
Erased,
&mut StreamBuilder,
&mut Position,
bool,
bool,
Vec<AnyAttribute>,
),
#[cfg(feature = "ssr")]
to_html_async_ooo: fn(
Erased,
&mut StreamBuilder,
&mut Position,
bool,
bool,
Vec<AnyAttribute>,
),
#[cfg(feature = "ssr")]
#[allow(clippy::type_complexity)]
resolve: fn(Erased) -> Pin<Box<dyn Future<Output = AnyView> + Send>>,
#[cfg(feature = "ssr")]
dry_resolve: fn(&mut Erased),
#[cfg(feature = "hydrate")]
#[allow(clippy::type_complexity)]
hydrate_from_server: fn(Erased, &Cursor, &PositionState) -> AnyViewState,
#[cfg(feature = "hydrate")]
#[allow(clippy::type_complexity)]
hydrate_async: fn(
Erased,
&Cursor,
&PositionState,
) -> Pin<Box<dyn Future<Output = AnyViewState>>>,
}
impl AnyView {
#[doc(hidden)]
pub fn as_type_id(&self) -> TypeId {
self.type_id
}
}
impl Debug for AnyView {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnyView")
.field("type_id", &self.type_id)
.finish_non_exhaustive()
}
}
/// Retained view state for [`AnyView`].
pub struct AnyViewState {
type_id: TypeId,
state: ErasedLocal,
unmount: fn(&mut ErasedLocal),
mount: fn(
&mut ErasedLocal,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
),
insert_before_this: fn(&ErasedLocal, child: &mut dyn Mountable) -> bool,
elements: fn(&ErasedLocal) -> Vec<crate::renderer::types::Element>,
placeholder: Option<crate::renderer::types::Placeholder>,
}
impl Debug for AnyViewState {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AnyViewState")
.field("type_id", &self.type_id)
.field("state", &"")
.field("unmount", &self.unmount)
.field("mount", &self.mount)
.field("insert_before_this", &self.insert_before_this)
.finish()
}
}
/// Allows converting some view into [`AnyView`].
pub trait IntoAny {
/// Converts the view into a type-erased [`AnyView`].
fn into_any(self) -> AnyView;
}
/// A more general version of [`IntoAny`] that allows into [`AnyView`],
/// but also erasing other types that don't implement [`RenderHtml`] like routing.
pub trait IntoMaybeErased {
/// The type of the output.
type Output: IntoMaybeErased;
/// Converts the view into a type-erased view if in erased mode.
fn into_maybe_erased(self) -> Self::Output;
}
impl<T> IntoMaybeErased for T
where
T: RenderHtml,
{
#[cfg(not(erase_components))]
type Output = Self;
#[cfg(erase_components)]
type Output = AnyView;
fn into_maybe_erased(self) -> Self::Output {
#[cfg(not(erase_components))]
{
self
}
#[cfg(erase_components)]
{
self.into_owned().into_any()
}
}
}
fn mount_any<T>(
state: &mut ErasedLocal,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) where
T: Render,
T::State: 'static,
{
state.get_mut::<T::State>().mount(parent, marker)
}
fn unmount_any<T>(state: &mut ErasedLocal)
where
T: Render,
T::State: 'static,
{
state.get_mut::<T::State>().unmount();
}
fn insert_before_this<T>(state: &ErasedLocal, child: &mut dyn Mountable) -> bool
where
T: Render,
T::State: 'static,
{
state.get_ref::<T::State>().insert_before_this(child)
}
fn elements<T>(state: &ErasedLocal) -> Vec<crate::renderer::types::Element>
where
T: Render,
T::State: 'static,
{
state.get_ref::<T::State>().elements()
}
impl<T> IntoAny for T
where
T: Send,
T: RenderHtml,
{
fn into_any(self) -> AnyView {
#[cfg(feature = "ssr")]
fn dry_resolve<T: RenderHtml + 'static>(value: &mut Erased) {
value.get_mut::<T>().dry_resolve();
}
#[cfg(feature = "ssr")]
fn resolve<T: RenderHtml + 'static>(
value: Erased,
) -> Pin<Box<dyn Future<Output = AnyView> + Send>> {
use futures::FutureExt;
async move { value.into_inner::<T>().resolve().await.into_any() }
.boxed()
}
#[cfg(feature = "ssr")]
fn to_html<T: RenderHtml + 'static>(
value: Erased,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
value.into_inner::<T>().to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if !T::EXISTS {
buf.push_str("<!--<() />-->");
}
}
#[cfg(feature = "ssr")]
fn to_html_async<T: RenderHtml + 'static>(
value: Erased,
buf: &mut StreamBuilder,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
value.into_inner::<T>().to_html_async_with_buf::<false>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if !T::EXISTS {
buf.push_sync("<!--<() />-->");
}
}
#[cfg(feature = "ssr")]
fn to_html_async_ooo<T: RenderHtml + 'static>(
value: Erased,
buf: &mut StreamBuilder,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
value.into_inner::<T>().to_html_async_with_buf::<true>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if !T::EXISTS {
buf.push_sync("<!--<() />-->");
}
}
fn build<T: RenderHtml + 'static>(value: Erased) -> AnyViewState {
let state = ErasedLocal::new(value.into_inner::<T>().build());
let placeholder = (!T::EXISTS).then(Rndr::create_placeholder);
AnyViewState {
type_id: TypeId::of::<T>(),
state,
mount: mount_any::<T>,
unmount: unmount_any::<T>,
insert_before_this: insert_before_this::<T>,
elements: elements::<T>,
placeholder,
}
}
#[cfg(feature = "hydrate")]
fn hydrate_from_server<T: RenderHtml + 'static>(
value: Erased,
cursor: &Cursor,
position: &PositionState,
) -> AnyViewState {
let state = ErasedLocal::new(
value.into_inner::<T>().hydrate::<true>(cursor, position),
);
let placeholder =
(!T::EXISTS).then(|| cursor.next_placeholder(position));
AnyViewState {
type_id: TypeId::of::<T>(),
state,
mount: mount_any::<T>,
unmount: unmount_any::<T>,
insert_before_this: insert_before_this::<T>,
elements: elements::<T>,
placeholder,
}
}
#[cfg(feature = "hydrate")]
fn hydrate_async<T: RenderHtml + 'static>(
value: Erased,
cursor: &Cursor,
position: &PositionState,
) -> Pin<Box<dyn Future<Output = AnyViewState>>> {
let cursor = cursor.clone();
let position = position.clone();
Box::pin(async move {
let state = ErasedLocal::new(
value
.into_inner::<T>()
.hydrate_async(&cursor, &position)
.await,
);
let placeholder =
(!T::EXISTS).then(|| cursor.next_placeholder(&position));
AnyViewState {
type_id: TypeId::of::<T>(),
state,
mount: mount_any::<T>,
unmount: unmount_any::<T>,
insert_before_this: insert_before_this::<T>,
elements: elements::<T>,
placeholder,
}
})
}
fn rebuild<T: RenderHtml + 'static>(
value: Erased,
state: &mut AnyViewState,
) {
let state = state.state.get_mut::<<T as Render>::State>();
value.into_inner::<T>().rebuild(state);
}
let value = self.into_owned();
AnyView {
type_id: TypeId::of::<T::Owned>(),
build: build::<T::Owned>,
rebuild: rebuild::<T::Owned>,
#[cfg(feature = "ssr")]
resolve: resolve::<T::Owned>,
#[cfg(feature = "ssr")]
dry_resolve: dry_resolve::<T::Owned>,
#[cfg(feature = "ssr")]
html_len: value.html_len(),
#[cfg(feature = "ssr")]
to_html: to_html::<T::Owned>,
#[cfg(feature = "ssr")]
to_html_async: to_html_async::<T::Owned>,
#[cfg(feature = "ssr")]
to_html_async_ooo: to_html_async_ooo::<T::Owned>,
#[cfg(feature = "hydrate")]
hydrate_from_server: hydrate_from_server::<T::Owned>,
#[cfg(feature = "hydrate")]
hydrate_async: hydrate_async::<T::Owned>,
value: Erased::new(value),
}
}
}
impl Render for AnyView {
type State = AnyViewState;
fn build(self) -> Self::State {
(self.build)(self.value)
}
fn rebuild(self, state: &mut Self::State) {
if self.type_id == state.type_id {
(self.rebuild)(self.value, state)
} else {
let mut new = self.build();
if let Some(placeholder) = &mut state.placeholder {
placeholder.insert_before_this(&mut new);
placeholder.unmount();
} else {
state.insert_before_this(&mut new);
}
state.unmount();
*state = new;
}
}
}
impl AddAnyAttr for AnyView {
type Output<SomeNewAttr: Attribute> = AnyViewWithAttrs;
#[allow(unused_variables)]
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
AnyViewWithAttrs {
view: self,
attrs: vec![attr.into_cloneable_owned().into_any_attr()],
}
}
}
impl RenderHtml for AnyView {
type AsyncOutput = Self;
type Owned = Self;
fn dry_resolve(&mut self) {
#[cfg(feature = "ssr")]
{
(self.dry_resolve)(&mut self.value)
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyView to HTML without the `ssr` feature \
enabled."
);
}
async fn resolve(self) -> Self::AsyncOutput {
#[cfg(feature = "ssr")]
{
(self.resolve)(self.value).await
}
#[cfg(not(feature = "ssr"))]
panic!(
"You are rendering AnyView to HTML without the `ssr` feature \
enabled."
);
}
const MIN_LENGTH: usize = 0;
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
#[cfg(feature = "ssr")]
{
let type_id = if mark_branches && escape {
format!("{:?}", self.type_id)
} else {
Default::default()
};
if mark_branches && escape {
buf.open_branch(&type_id);
}
(self.to_html)(
self.value,
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if mark_branches && escape {
buf.close_branch(&type_id);
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
}
#[cfg(not(feature = "ssr"))]
{
_ = mark_branches;
_ = buf;
_ = position;
_ = escape;
_ = extra_attrs;
panic!(
"You are rendering AnyView to HTML without the `ssr` feature \
enabled."
);
}
}
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(feature = "ssr")]
if OUT_OF_ORDER {
let type_id = if mark_branches && escape {
format!("{:?}", self.type_id)
} else {
Default::default()
};
if mark_branches && escape {
buf.open_branch(&type_id);
}
(self.to_html_async_ooo)(
self.value,
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if mark_branches && escape {
buf.close_branch(&type_id);
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
} else {
let type_id = if mark_branches && escape {
format!("{:?}", self.type_id)
} else {
Default::default()
};
if mark_branches && escape {
buf.open_branch(&type_id);
}
(self.to_html_async)(
self.value,
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if mark_branches && escape {
buf.close_branch(&type_id);
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
}
#[cfg(not(feature = "ssr"))]
{
_ = buf;
_ = position;
_ = escape;
_ = mark_branches;
_ = extra_attrs;
panic!(
"You are rendering AnyView to HTML without the `ssr` feature \
enabled."
);
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
#[cfg(feature = "hydrate")]
{
if FROM_SERVER {
(self.hydrate_from_server)(self.value, cursor, position)
} else {
panic!(
"hydrating AnyView from inside a ViewTemplate is not \
supported."
);
}
}
#[cfg(not(feature = "hydrate"))]
{
_ = cursor;
_ = position;
panic!(
"You are trying to hydrate AnyView without the `hydrate` \
feature enabled."
);
}
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
#[cfg(feature = "hydrate")]
{
let state =
(self.hydrate_async)(self.value, cursor, position).await;
state
}
#[cfg(not(feature = "hydrate"))]
{
_ = cursor;
_ = position;
panic!(
"You are trying to hydrate AnyView without the `hydrate` \
feature enabled."
);
}
}
fn html_len(&self) -> usize {
#[cfg(feature = "ssr")]
{
self.html_len
}
#[cfg(not(feature = "ssr"))]
{
0
}
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl Mountable for AnyViewState {
fn unmount(&mut self) {
(self.unmount)(&mut self.state);
if let Some(placeholder) = &mut self.placeholder {
placeholder.unmount();
}
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
(self.mount)(&mut self.state, parent, marker);
if let Some(placeholder) = &mut self.placeholder {
placeholder.mount(parent, marker);
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
let before_view = (self.insert_before_this)(&self.state, child);
if before_view {
return true;
}
if let Some(placeholder) = &self.placeholder {
placeholder.insert_before_this(child)
} else {
false
}
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
(self.elements)(&self.state)
}
}
/// wip
pub struct AnyViewWithAttrs {
view: AnyView,
attrs: Vec<AnyAttribute>,
}
impl Render for AnyViewWithAttrs {
type State = AnyViewWithAttrsState;
fn build(self) -> Self::State {
let view = self.view.build();
let elements = view.elements();
let mut attrs = Vec::with_capacity(elements.len() * self.attrs.len());
for attr in self.attrs {
for el in &elements {
attrs.push(attr.clone().build(el))
}
}
AnyViewWithAttrsState { view, attrs }
}
fn rebuild(self, state: &mut Self::State) {
self.view.rebuild(&mut state.view);
// at this point, we have rebuilt the inner view
// now we need to update attributes that were spread onto this
// this approach is not ideal, but it avoids two edge cases:
// 1) merging attributes from two unrelated views (https://github.com/leptos-rs/leptos/issues/4268)
// 2) failing to re-create attributes from the same view (https://github.com/leptos-rs/leptos/issues/4512)
for element in state.elements() {
// first, remove the previous set of attributes
self.attrs
.clone()
.rebuild(&mut (element.clone(), Vec::new()));
// then, add the new set of attributes
self.attrs.clone().build(&element);
}
}
}
impl RenderHtml for AnyViewWithAttrs {
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
self.view.dry_resolve();
for attr in &mut self.attrs {
attr.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
let resolve_view = self.view.resolve();
let resolve_attrs =
join_all(self.attrs.into_iter().map(|attr| attr.resolve()));
let (view, attrs) = join(resolve_view, resolve_attrs).await;
Self { view, attrs }
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
mut extra_attrs: Vec<AnyAttribute>,
) {
// `extra_attrs` will be empty here in most cases, but it will have
// attributes in it already if this is, itself, receiving additional attrs
extra_attrs.extend(self.attrs);
self.view.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,
mut extra_attrs: Vec<AnyAttribute>,
) where
Self: Sized,
{
extra_attrs.extend(self.attrs);
self.view.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 {
let view = self.view.hydrate::<FROM_SERVER>(cursor, position);
let elements = view.elements();
let mut attrs = Vec::with_capacity(elements.len() * self.attrs.len());
for attr in self.attrs {
for el in &elements {
attrs.push(attr.clone().hydrate::<FROM_SERVER>(el));
}
}
AnyViewWithAttrsState { view, attrs }
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let view = self.view.hydrate_async(cursor, position).await;
let elements = view.elements();
let mut attrs = Vec::with_capacity(elements.len() * self.attrs.len());
for attr in self.attrs {
for el in &elements {
attrs.push(attr.clone().hydrate::<true>(el));
}
}
AnyViewWithAttrsState { view, attrs }
}
fn html_len(&self) -> usize {
self.view.html_len()
+ self.attrs.iter().map(|attr| attr.html_len()).sum::<usize>()
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl AddAnyAttr for AnyViewWithAttrs {
type Output<SomeNewAttr: Attribute> = AnyViewWithAttrs;
fn add_any_attr<NewAttr: Attribute>(
mut self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
self.attrs.push(attr.into_cloneable_owned().into_any_attr());
self
}
}
/// State for any view with attributes spread onto it.
pub struct AnyViewWithAttrsState {
view: AnyViewState,
#[allow(dead_code)] // keeps attribute states alive until dropped
attrs: Vec<AnyAttributeState>,
}
impl Mountable for AnyViewWithAttrsState {
fn unmount(&mut self) {
self.view.unmount();
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
self.view.mount(parent, marker)
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.view.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.view.elements()
}
}
/*
#[cfg(test)]
mod tests {
use super::IntoAny;
use crate::{
html::element::{p, span},
renderer::mock_dom::MockDom,
view::{any_view::AnyView, RenderHtml},
};
#[test]
fn should_handle_html_creation() {
let x = 1;
let mut buf = String::new();
let view: AnyView<MockDom> = if x == 0 {
p((), "foo").into_any()
} else {
span((), "bar").into_any()
};
view.to_html(&mut buf, &Default::default());
assert_eq!(buf, "<span>bar</span><!>");
}
}
*/
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/template.rs | tachys/src/view/template.rs | use super::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml, ToTemplate,
};
use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
renderer::Rndr,
};
/// A view wrapper that uses a `<template>` node to optimize DOM node creation.
///
/// Rather than creating all of the DOM nodes each time it is built, this template will create a
/// single `<template>` node once, then use `.cloneNode(true)` to clone that entire tree, and
/// hydrate it to add event listeners and interactivity for this instance.
pub struct ViewTemplate<V> {
view: V,
}
impl<V> ViewTemplate<V>
where
V: Render + ToTemplate + 'static,
{
/// Creates a new view template.
pub fn new(view: V) -> Self {
Self { view }
}
fn to_template() -> crate::renderer::types::TemplateElement {
Rndr::get_template::<V>()
}
}
impl<V> Render for ViewTemplate<V>
where
V: Render + RenderHtml + ToTemplate + 'static,
V::State: Mountable,
{
type State = V::State;
// TODO try_build/try_rebuild()
fn build(self) -> Self::State {
let tpl = Self::to_template();
let contents = Rndr::clone_template(&tpl);
self.view
.hydrate::<false>(&Cursor::new(contents), &Default::default())
}
fn rebuild(self, state: &mut Self::State) {
self.view.rebuild(state)
}
}
impl<V> AddAnyAttr for ViewTemplate<V>
where
V: RenderHtml + ToTemplate + 'static,
V::State: Mountable,
{
type Output<SomeNewAttr: Attribute> = ViewTemplate<V>;
fn add_any_attr<NewAttr: Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr> {
panic!("AddAnyAttr not supported on ViewTemplate");
}
}
impl<V> RenderHtml for ViewTemplate<V>
where
V: RenderHtml + ToTemplate + 'static,
V::State: Mountable,
{
type AsyncOutput = V::AsyncOutput;
type Owned = V::Owned;
const MIN_LENGTH: usize = V::MIN_LENGTH;
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
self.view.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
self.view.hydrate::<FROM_SERVER>(cursor, position)
}
fn dry_resolve(&mut self) {
self.view.dry_resolve();
}
async fn resolve(self) -> Self::AsyncOutput {
self.view.resolve().await
}
fn into_owned(self) -> Self::Owned {
self.view.into_owned()
}
}
impl<V> ToTemplate for ViewTemplate<V>
where
V: RenderHtml + ToTemplate + 'static,
V::State: Mountable,
{
const TEMPLATE: &'static str = V::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
V::to_template(buf, class, style, inner_html, position);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/primitives.rs | tachys/src/view/primitives.rs | use super::{Mountable, Position, PositionState, Render, RenderHtml};
use crate::{
html::attribute::any_attribute::AnyAttribute,
hydration::Cursor,
no_attrs,
renderer::{CastFrom, Rndr},
view::ToTemplate,
};
use std::{
fmt::Write,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8,
NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64,
NonZeroU8, NonZeroUsize,
},
};
// any changes here should also be made in src/reactive_graph/guards.rs
macro_rules! render_primitive {
($($child_type:ty),* $(,)?) => {
$(
paste::paste! {
pub struct [<$child_type:camel State>](crate::renderer::types::Text, $child_type);
impl Mountable for [<$child_type:camel State>] {
fn unmount(&mut self) {
self.0.unmount()
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
Rndr::insert_node(parent, self.0.as_ref(), marker);
}
fn insert_before_this(&self,
child: &mut dyn Mountable,
) -> bool {
self.0.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![]
}
}
impl Render for $child_type {
type State = [<$child_type:camel State>];
fn build(self) -> Self::State {
let node = Rndr::create_text_node(&self.to_string());
[<$child_type:camel State>](node, self)
}
fn rebuild(self, state: &mut Self::State) {
let [<$child_type:camel State>](node, this) = state;
if &self != this {
Rndr::set_text(node, &self.to_string());
*this = self;
}
}
}
no_attrs!($child_type);
impl RenderHtml for $child_type
{
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = 0;
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>) {
// add a comment node to separate from previous sibling, if any
if matches!(position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
_ = write!(buf, "{}", self);
*position = Position::NextChildAfterText;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
if position.get() == Position::FirstChild {
cursor.child();
} else {
cursor.sibling();
}
// separating placeholder marker comes before text node
if matches!(position.get(), Position::NextChildAfterText) {
cursor.sibling();
}
let node = cursor.current();
let node = crate::renderer::types::Text::cast_from(node.clone())
.unwrap_or_else(|| crate::hydration::failed_to_cast_text_node(node));
if !FROM_SERVER {
Rndr::set_text(&node, &self.to_string());
}
position.set(Position::NextChildAfterText);
[<$child_type:camel State>](node, self)
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl<'a> ToTemplate for $child_type {
const TEMPLATE: &'static str = " <!>";
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
position: &mut Position,
) {
if matches!(*position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push(' ');
*position = Position::NextChildAfterText;
}
}
}
)*
};
}
render_primitive![
usize,
u8,
u16,
u32,
u64,
u128,
isize,
i8,
i16,
i32,
i64,
i128,
f32,
f64,
char,
bool,
IpAddr,
SocketAddr,
SocketAddrV4,
SocketAddrV6,
Ipv4Addr,
Ipv6Addr,
NonZeroI8,
NonZeroU8,
NonZeroI16,
NonZeroU16,
NonZeroI32,
NonZeroU32,
NonZeroI64,
NonZeroU64,
NonZeroI128,
NonZeroU128,
NonZeroIsize,
NonZeroUsize,
];
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/either.rs | tachys/src/view/either.rs | use super::{
add_attr::AddAnyAttr, MarkBranch, Mountable, Position, PositionState,
Render, RenderHtml,
};
use crate::{
html::attribute::{
any_attribute::AnyAttribute, Attribute, NamedAttributeKey,
NextAttribute,
},
hydration::Cursor,
ssr::StreamBuilder,
};
use either_of::*;
use futures::future::join;
impl<A, B> Render for Either<A, B>
where
A: Render,
B: Render,
{
type State = Either<A::State, B::State>;
fn build(self) -> Self::State {
match self {
Either::Left(left) => Either::Left(left.build()),
Either::Right(right) => Either::Right(right.build()),
}
}
fn rebuild(self, state: &mut Self::State) {
match (self, &mut *state) {
(Either::Left(new), Either::Left(old)) => {
new.rebuild(old);
}
(Either::Right(new), Either::Right(old)) => {
new.rebuild(old);
}
(Either::Right(new), Either::Left(old)) => {
let mut new_state = new.build();
old.insert_before_this(&mut new_state);
old.unmount();
*state = Either::Right(new_state);
}
(Either::Left(new), Either::Right(old)) => {
let mut new_state = new.build();
old.insert_before_this(&mut new_state);
old.unmount();
*state = Either::Left(new_state);
}
}
}
}
impl<A, B> Mountable for Either<A, B>
where
A: Mountable,
B: Mountable,
{
fn unmount(&mut self) {
match self {
Either::Left(left) => left.unmount(),
Either::Right(right) => right.unmount(),
}
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
match self {
Either::Left(left) => left.mount(parent, marker),
Either::Right(right) => right.mount(parent, marker),
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
match &self {
Either::Left(left) => left.insert_before_this(child),
Either::Right(right) => right.insert_before_this(child),
}
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
match &self {
Either::Left(left) => left.elements(),
Either::Right(right) => right.elements(),
}
}
}
impl<A, B> AddAnyAttr for Either<A, B>
where
A: RenderHtml,
B: RenderHtml,
{
type Output<SomeNewAttr: Attribute> = Either<
<A as AddAnyAttr>::Output<SomeNewAttr>,
<B as AddAnyAttr>::Output<SomeNewAttr>,
>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
match self {
Either::Left(i) => Either::Left(i.add_any_attr(attr)),
Either::Right(i) => Either::Right(i.add_any_attr(attr)),
}
}
}
const fn max_usize(vals: &[usize]) -> usize {
let mut max = 0;
let len = vals.len();
let mut i = 0;
while i < len {
if vals[i] > max {
max = vals[i];
}
i += 1;
}
max
}
#[cfg(not(erase_components))]
impl<A, B> NextAttribute for Either<A, B>
where
B: NextAttribute,
A: NextAttribute,
{
type Output<NewAttr: Attribute> = Either<
<A as NextAttribute>::Output<NewAttr>,
<B as NextAttribute>::Output<NewAttr>,
>;
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
match self {
Either::Left(left) => Either::Left(left.add_any_attr(new_attr)),
Either::Right(right) => Either::Right(right.add_any_attr(new_attr)),
}
}
}
#[cfg(erase_components)]
impl<A, B> NextAttribute for Either<A, B>
where
B: crate::html::attribute::any_attribute::IntoAnyAttribute,
A: crate::html::attribute::any_attribute::IntoAnyAttribute,
{
type Output<NewAttr: Attribute> = Vec<AnyAttribute>;
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
use crate::html::attribute::any_attribute::IntoAnyAttribute;
vec![
match self {
Either::Left(left) => left.into_any_attr(),
Either::Right(right) => right.into_any_attr(),
},
new_attr.into_any_attr(),
]
}
}
impl<A, B> Attribute for Either<A, B>
where
B: Attribute,
A: Attribute,
{
const MIN_LENGTH: usize = max_usize(&[A::MIN_LENGTH, B::MIN_LENGTH]);
type AsyncOutput = Either<A::AsyncOutput, B::AsyncOutput>;
type State = Either<A::State, B::State>;
type Cloneable = Either<A::Cloneable, B::Cloneable>;
type CloneableOwned = Either<A::CloneableOwned, B::CloneableOwned>;
fn html_len(&self) -> usize {
match self {
Either::Left(left) => left.html_len(),
Either::Right(right) => right.html_len(),
}
}
fn to_html(
self,
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
) {
match self {
Either::Left(left) => left.to_html(buf, class, style, inner_html),
Either::Right(right) => {
right.to_html(buf, class, style, inner_html)
}
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State {
match self {
Either::Left(left) => Either::Left(left.hydrate::<FROM_SERVER>(el)),
Either::Right(right) => {
Either::Right(right.hydrate::<FROM_SERVER>(el))
}
}
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
match self {
Either::Left(left) => Either::Left(left.build(el)),
Either::Right(right) => Either::Right(right.build(el)),
}
}
fn rebuild(self, state: &mut Self::State) {
match self {
Either::Left(left) => {
if let Some(state) = state.as_left_mut() {
left.rebuild(state)
}
}
Either::Right(right) => {
if let Some(state) = state.as_right_mut() {
right.rebuild(state)
}
}
}
}
fn into_cloneable(self) -> Self::Cloneable {
match self {
Either::Left(left) => Either::Left(left.into_cloneable()),
Either::Right(right) => Either::Right(right.into_cloneable()),
}
}
fn into_cloneable_owned(self) -> Self::CloneableOwned {
match self {
Either::Left(left) => Either::Left(left.into_cloneable_owned()),
Either::Right(right) => Either::Right(right.into_cloneable_owned()),
}
}
fn dry_resolve(&mut self) {
match self {
Either::Left(left) => left.dry_resolve(),
Either::Right(right) => right.dry_resolve(),
}
}
async fn resolve(self) -> Self::AsyncOutput {
match self {
Either::Left(left) => Either::Left(left.resolve().await),
Either::Right(right) => Either::Right(right.resolve().await),
}
}
fn keys(&self) -> Vec<NamedAttributeKey> {
match self {
Either::Left(left) => left.keys(),
Either::Right(right) => right.keys(),
}
}
}
impl<A, B> RenderHtml for Either<A, B>
where
A: RenderHtml,
B: RenderHtml,
{
type AsyncOutput = Either<A::AsyncOutput, B::AsyncOutput>;
type Owned = Either<A::Owned, B::Owned>;
fn dry_resolve(&mut self) {
match self {
Either::Left(left) => left.dry_resolve(),
Either::Right(right) => right.dry_resolve(),
}
}
async fn resolve(self) -> Self::AsyncOutput {
match self {
Either::Left(left) => Either::Left(left.resolve().await),
Either::Right(right) => Either::Right(right.resolve().await),
}
}
const MIN_LENGTH: usize = max_usize(&[A::MIN_LENGTH, B::MIN_LENGTH]);
#[inline(always)]
fn html_len(&self) -> usize {
match self {
Either::Left(i) => i.html_len(),
Either::Right(i) => i.html_len(),
}
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
match self {
Either::Left(left) => {
if mark_branches && escape {
buf.open_branch("0");
}
left.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if mark_branches && escape {
buf.close_branch("0");
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
}
Either::Right(right) => {
if mark_branches && escape {
buf.open_branch("1");
}
right.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if mark_branches && escape {
buf.close_branch("1");
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
}
}
}
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,
{
match self {
Either::Left(left) => {
if mark_branches && escape {
buf.open_branch("0");
}
left.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if mark_branches && escape {
buf.close_branch("0");
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
}
Either::Right(right) => {
if mark_branches && escape {
buf.open_branch("1");
}
right.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
if mark_branches && escape {
buf.close_branch("1");
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
}
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
match self {
Either::Left(left) => {
Either::Left(left.hydrate::<FROM_SERVER>(cursor, position))
}
Either::Right(right) => {
Either::Right(right.hydrate::<FROM_SERVER>(cursor, position))
}
}
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
match self {
Either::Left(left) => {
Either::Left(left.hydrate_async(cursor, position).await)
}
Either::Right(right) => {
Either::Right(right.hydrate_async(cursor, position).await)
}
}
}
fn into_owned(self) -> Self::Owned {
match self {
Either::Left(left) => Either::Left(left.into_owned()),
Either::Right(right) => Either::Right(right.into_owned()),
}
}
}
/// Stores each value in the view state, overwriting it only if `Some(_)` is provided.
pub struct EitherKeepAlive<A, B> {
/// The first possibility.
pub a: Option<A>,
/// The second possibility.
pub b: Option<B>,
/// If `true`, then `b` will be shown.
pub show_b: bool,
}
/// Retained view state for [`EitherKeepAlive`].
pub struct EitherKeepAliveState<A, B> {
a: Option<A>,
b: Option<B>,
showing_b: bool,
}
impl<A, B> Render for EitherKeepAlive<A, B>
where
A: Render,
B: Render,
{
type State = EitherKeepAliveState<A::State, B::State>;
fn build(self) -> Self::State {
let showing_b = self.show_b;
let a = self.a.map(Render::build);
let b = self.b.map(Render::build);
EitherKeepAliveState { a, b, showing_b }
}
fn rebuild(self, state: &mut Self::State) {
// set or update A -- `None` just means "no change"
match (self.a, &mut state.a) {
(Some(new), Some(old)) => new.rebuild(old),
(Some(new), None) => state.a = Some(new.build()),
_ => {}
}
// set or update B
match (self.b, &mut state.b) {
(Some(new), Some(old)) => new.rebuild(old),
(Some(new), None) => state.b = Some(new.build()),
_ => {}
}
match (self.show_b, state.showing_b) {
// transition from A to B
(true, false) => match (&mut state.a, &mut state.b) {
(Some(a), Some(b)) => {
a.insert_before_this(b);
a.unmount();
}
_ => unreachable!(),
},
// transition from B to A
(false, true) => match (&mut state.a, &mut state.b) {
(Some(a), Some(b)) => {
b.insert_before_this(a);
b.unmount();
}
_ => unreachable!(),
},
_ => {}
}
state.showing_b = self.show_b;
}
}
impl<A, B> AddAnyAttr for EitherKeepAlive<A, B>
where
A: RenderHtml,
B: RenderHtml,
{
type Output<SomeNewAttr: Attribute> = EitherKeepAlive<
<A as AddAnyAttr>::Output<SomeNewAttr::Cloneable>,
<B as AddAnyAttr>::Output<SomeNewAttr::Cloneable>,
>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let EitherKeepAlive { a, b, show_b } = self;
let attr = attr.into_cloneable();
EitherKeepAlive {
a: a.map(|a| a.add_any_attr(attr.clone())),
b: b.map(|b| b.add_any_attr(attr.clone())),
show_b,
}
}
}
impl<A, B> RenderHtml for EitherKeepAlive<A, B>
where
A: RenderHtml,
B: RenderHtml,
{
type AsyncOutput = EitherKeepAlive<A::AsyncOutput, B::AsyncOutput>;
type Owned = EitherKeepAlive<A::Owned, B::Owned>;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
if let Some(inner) = &mut self.a {
inner.dry_resolve();
}
if let Some(inner) = &mut self.b {
inner.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
let EitherKeepAlive { a, b, show_b } = self;
let (a, b) = join(
async move {
match a {
Some(a) => Some(a.resolve().await),
None => None,
}
},
async move {
match b {
Some(b) => Some(b.resolve().await),
None => None,
}
},
)
.await;
EitherKeepAlive { a, b, show_b }
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
if self.show_b {
self.b
.expect("rendering B to HTML without filling it")
.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
} else {
self.a
.expect("rendering A to HTML without filling it")
.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,
{
if self.show_b {
self.b
.expect("rendering B to HTML without filling it")
.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
);
} else {
self.a
.expect("rendering A to HTML without filling it")
.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 {
let showing_b = self.show_b;
let a = self.a.map(|a| {
if showing_b {
a.build()
} else {
a.hydrate::<FROM_SERVER>(cursor, position)
}
});
let b = self.b.map(|b| {
if showing_b {
b.hydrate::<FROM_SERVER>(cursor, position)
} else {
b.build()
}
});
EitherKeepAliveState { showing_b, a, b }
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let showing_b = self.show_b;
let a = if let Some(a) = self.a {
Some(if showing_b {
a.build()
} else {
a.hydrate_async(cursor, position).await
})
} else {
None
};
let b = if let Some(b) = self.b {
Some(if showing_b {
b.hydrate_async(cursor, position).await
} else {
b.build()
})
} else {
None
};
EitherKeepAliveState { showing_b, a, b }
}
fn into_owned(self) -> Self::Owned {
EitherKeepAlive {
a: self.a.map(|a| a.into_owned()),
b: self.b.map(|b| b.into_owned()),
show_b: self.show_b,
}
}
}
impl<A, B> Mountable for EitherKeepAliveState<A, B>
where
A: Mountable,
B: Mountable,
{
fn unmount(&mut self) {
if self.showing_b {
self.b.as_mut().expect("B was not present").unmount();
} else {
self.a.as_mut().expect("A was not present").unmount();
}
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
if self.showing_b {
self.b
.as_mut()
.expect("B was not present")
.mount(parent, marker);
} else {
self.a
.as_mut()
.expect("A was not present")
.mount(parent, marker);
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
if self.showing_b {
self.b
.as_ref()
.expect("B was not present")
.insert_before_this(child)
} else {
self.a
.as_ref()
.expect("A was not present")
.insert_before_this(child)
}
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
if self.showing_b {
self.b
.as_ref()
.map(|inner| inner.elements())
.unwrap_or_default()
} else {
self.a
.as_ref()
.map(|inner| inner.elements())
.unwrap_or_default()
}
}
}
macro_rules! tuples {
($num:literal => $($ty:ident),*) => {
paste::paste! {
#[doc = concat!("Retained view state for ", stringify!([<EitherOf $num>]), ".")]
pub struct [<EitherOf $num State>]<$($ty,)*>
where
$($ty: Render,)*
{
/// Which child view state is being displayed.
pub state: [<EitherOf $num>]<$($ty::State,)*>,
}
impl<$($ty,)*> Mountable for [<EitherOf $num State>]<$($ty,)*>
where
$($ty: Render,)*
{
fn unmount(&mut self) {
match &mut self.state {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.unmount()),)*
};
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
match &mut self.state {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.mount(parent, marker)),)*
};
}
fn insert_before_this(&self,
child: &mut dyn Mountable,
) -> bool {
match &self.state {
$([<EitherOf $num>]::$ty(this) =>this.insert_before_this(child),)*
}
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
match &self.state {
$([<EitherOf $num>]::$ty(this) => this.elements(),)*
}
}
}
impl<$($ty,)*> Render for [<EitherOf $num>]<$($ty,)*>
where
$($ty: Render,)*
{
type State = [<EitherOf $num State>]<$($ty,)*>;
fn build(self) -> Self::State {
let state = match self {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.build()),)*
};
Self::State { state }
}
fn rebuild(self, state: &mut Self::State) {
let new_state = match (self, &mut state.state) {
// rebuild same state and return early
$(([<EitherOf $num>]::$ty(new), [<EitherOf $num>]::$ty(old)) => { return new.rebuild(old); },)*
// or mount new state
$(([<EitherOf $num>]::$ty(new), _) => {
let mut new = new.build();
state.insert_before_this(&mut new);
[<EitherOf $num>]::$ty(new)
},)*
};
// and then unmount old state
match &mut state.state {
$([<EitherOf $num>]::$ty(this) => this.unmount(),)*
};
// and store the new state
state.state = new_state;
}
}
impl<$($ty,)*> AddAnyAttr for [<EitherOf $num>]<$($ty,)*>
where
$($ty: RenderHtml,)*
{
type Output<SomeNewAttr: Attribute> = [<EitherOf $num>]<
$(<$ty as AddAnyAttr>::Output<SomeNewAttr>,)*
>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
match self {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.add_any_attr(attr)),)*
}
}
}
impl<$($ty,)*> RenderHtml for [<EitherOf $num>]<$($ty,)*>
where
$($ty: RenderHtml,)*
{
type AsyncOutput = [<EitherOf $num>]<$($ty::AsyncOutput,)*>;
type Owned = [<EitherOf $num>]<$($ty::Owned,)*>;
const MIN_LENGTH: usize = max_usize(&[$($ty ::MIN_LENGTH,)*]);
fn dry_resolve(&mut self) {
match self {
$([<EitherOf $num>]::$ty(this) => {
this.dry_resolve();
})*
}
}
async fn resolve(self) -> Self::AsyncOutput {
match self {
$([<EitherOf $num>]::$ty(this) => [<EitherOf $num>]::$ty(this.resolve().await),)*
}
}
#[inline(always)]
fn html_len(&self) -> usize {
match self {
$([<EitherOf $num>]::$ty(i) => i.html_len(),)*
}
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>
) {
match self {
$([<EitherOf $num>]::$ty(this) => {
if mark_branches && escape {
buf.open_branch(stringify!($ty));
}
this.to_html_with_buf(buf, position, escape, mark_branches, extra_attrs);
if mark_branches && escape {
buf.close_branch(stringify!($ty));
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
})*
}
}
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,
{
match self {
$([<EitherOf $num>]::$ty(this) => {
if mark_branches && escape {
buf.open_branch(stringify!($ty));
}
this.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position, escape, mark_branches, extra_attrs);
if mark_branches && escape {
buf.close_branch(stringify!($ty));
if *position == Position::NextChildAfterText {
*position = Position::NextChild;
}
}
})*
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let state = match self {
$([<EitherOf $num>]::$ty(this) => {
[<EitherOf $num>]::$ty(this.hydrate::<FROM_SERVER>(cursor, position))
})*
};
Self::State { state }
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let state = match self {
$([<EitherOf $num>]::$ty(this) => {
[<EitherOf $num>]::$ty(this.hydrate_async(cursor, position).await)
})*
};
Self::State { state }
}
fn into_owned(self) -> Self::Owned {
match self {
$([<EitherOf $num>]::$ty(this) => {
[<EitherOf $num>]::$ty(this.into_owned())
})*
}
}
}
}
}
}
tuples!(3 => A, B, C);
tuples!(4 => A, B, C, D);
tuples!(5 => A, B, C, D, E);
tuples!(6 => A, B, C, D, E, F);
tuples!(7 => A, B, C, D, E, F, G);
tuples!(8 => A, B, C, D, E, F, G, H);
tuples!(9 => A, B, C, D, E, F, G, H, I);
tuples!(10 => A, B, C, D, E, F, G, H, I, J);
tuples!(11 => A, B, C, D, E, F, G, H, I, J, K);
tuples!(12 => A, B, C, D, E, F, G, H, I, J, K, L);
tuples!(13 => A, B, C, D, E, F, G, H, I, J, K, L, M);
tuples!(14 => A, B, C, D, E, F, G, H, I, J, K, L, M, N);
tuples!(15 => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
tuples!(16 => A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/keyed.rs | tachys/src/view/keyed.rs | use super::{
add_attr::AddAnyAttr, MarkBranch, Mountable, Position, PositionState,
Render, RenderHtml,
};
use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
renderer::{CastFrom, Rndr},
ssr::StreamBuilder,
};
use drain_filter_polyfill::VecExt as VecDrainFilterExt;
use indexmap::IndexSet;
use rustc_hash::FxHasher;
use std::hash::{BuildHasherDefault, Hash};
type FxIndexSet<T> = IndexSet<T, BuildHasherDefault<FxHasher>>;
/// Creates a keyed list of views.
pub fn keyed<T, I, K, KF, VF, VFS, V>(
items: I,
key_fn: KF,
view_fn: VF,
) -> Keyed<T, I, K, KF, VF, VFS, V>
where
I: IntoIterator<Item = T>,
K: Eq + Hash + SerializableKey + 'static,
KF: Fn(&T) -> K,
V: Render,
VF: Fn(usize, T) -> (VFS, V),
VFS: Fn(usize),
{
Keyed {
#[cfg(not(feature = "ssr"))]
items: Some(items),
#[cfg(feature = "ssr")]
items: None,
#[cfg(feature = "ssr")]
ssr_items: items
.into_iter()
.enumerate()
.map(|(i, t)| {
let key = if cfg!(feature = "islands") {
let key = (key_fn)(&t);
key.ser_key()
} else {
String::new()
};
let (_, view) = (view_fn)(i, t);
(key, view)
})
.collect::<Vec<_>>(),
key_fn,
view_fn,
}
}
/// A keyed list of views.
pub struct Keyed<T, I, K, KF, VF, VFS, V>
where
I: IntoIterator<Item = T>,
K: Eq + Hash + 'static,
KF: Fn(&T) -> K,
VF: Fn(usize, T) -> (VFS, V),
VFS: Fn(usize),
{
items: Option<I>,
#[cfg(feature = "ssr")]
ssr_items: Vec<(String, V)>,
key_fn: KF,
view_fn: VF,
}
/// By default, keys used in for keyed iteration do not need to be serializable.
///
/// However, for some scenarios (like the “islands routing” mode that mixes server-side
/// rendering with client-side navigation) it is useful to have serializable keys.
///
/// When the `islands` feature is not enabled, this trait is implemented by all types.
///
/// When the `islands` features is enabled, this is automatically implemented for all types
/// that implement [`Serialize`](serde::Serialize), and can be manually implemented otherwise.
pub trait SerializableKey {
/// Serializes the key to a unique string.
///
/// The string can have any value, as long as it is idempotent (i.e., serializing the same key
/// multiple times will give the same value).
fn ser_key(&self) -> String;
}
#[cfg(not(feature = "islands"))]
impl<T> SerializableKey for T {
fn ser_key(&self) -> String {
panic!(
"SerializableKey called without the `islands` feature enabled. \
Something has gone wrong."
);
}
}
#[cfg(feature = "islands")]
impl<T: serde::Serialize> SerializableKey for T {
fn ser_key(&self) -> String {
serde_json::to_string(self).expect("failed to serialize key")
}
}
/// Retained view state for a keyed list.
pub struct KeyedState<K, VFS, V>
where
K: Eq + Hash + 'static,
VFS: Fn(usize),
V: Render,
{
parent: Option<crate::renderer::types::Element>,
marker: crate::renderer::types::Placeholder,
hashed_items: IndexSet<K, BuildHasherDefault<FxHasher>>,
rendered_items: Vec<Option<(VFS, V::State)>>,
}
impl<T, I, K, KF, VF, VFS, V> Render for Keyed<T, I, K, KF, VF, VFS, V>
where
I: IntoIterator<Item = T>,
K: Eq + Hash + SerializableKey + 'static,
KF: Fn(&T) -> K,
V: Render,
VF: Fn(usize, T) -> (VFS, V),
VFS: Fn(usize),
{
type State = KeyedState<K, VFS, V>;
fn build(self) -> Self::State {
let items = self.items.into_iter().flatten();
let (capacity, _) = items.size_hint();
let mut hashed_items =
FxIndexSet::with_capacity_and_hasher(capacity, Default::default());
let mut rendered_items = Vec::with_capacity(capacity);
for (index, item) in items.enumerate() {
hashed_items.insert((self.key_fn)(&item));
let (set_index, view) = (self.view_fn)(index, item);
rendered_items.push(Some((set_index, view.build())));
}
KeyedState {
parent: None,
marker: Rndr::create_placeholder(),
hashed_items,
rendered_items,
}
}
fn rebuild(self, state: &mut Self::State) {
let KeyedState {
parent,
marker,
hashed_items,
ref mut rendered_items,
} = state;
let new_items = self.items.into_iter().flatten();
let (capacity, _) = new_items.size_hint();
let mut new_hashed_items =
FxIndexSet::with_capacity_and_hasher(capacity, Default::default());
let mut items = Vec::new();
for item in new_items {
new_hashed_items.insert((self.key_fn)(&item));
items.push(Some(item));
}
let cmds = diff(hashed_items, &new_hashed_items);
apply_diff(
parent.as_ref(),
marker,
cmds,
rendered_items,
&self.view_fn,
items,
);
*hashed_items = new_hashed_items;
}
}
impl<T, I, K, KF, VF, VFS, V> AddAnyAttr for Keyed<T, I, K, KF, VF, VFS, V>
where
I: IntoIterator<Item = T> + Send + 'static,
K: Eq + Hash + SerializableKey + 'static,
KF: Fn(&T) -> K + Send + 'static,
V: RenderHtml,
V: 'static,
VF: Fn(usize, T) -> (VFS, V) + Send + 'static,
VFS: Fn(usize) + 'static,
T: 'static,
{
type Output<SomeNewAttr: Attribute> = Keyed<
T,
I,
K,
KF,
Box<
dyn Fn(
usize,
T,
) -> (
VFS,
<V as AddAnyAttr>::Output<SomeNewAttr::CloneableOwned>,
) + Send,
>,
VFS,
V::Output<SomeNewAttr::CloneableOwned>,
>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let Keyed {
items,
#[cfg(feature = "ssr")]
ssr_items,
key_fn,
view_fn,
} = self;
let attr = attr.into_cloneable_owned();
Keyed {
items,
key_fn,
#[cfg(feature = "ssr")]
ssr_items: ssr_items
.into_iter()
.map(|(k, v)| (k, v.add_any_attr(attr.clone())))
.collect(),
view_fn: Box::new(move |index, item| {
let (index, view) = view_fn(index, item);
(index, view.add_any_attr(attr.clone()))
}),
}
}
}
impl<T, I, K, KF, VF, VFS, V> RenderHtml for Keyed<T, I, K, KF, VF, VFS, V>
where
I: IntoIterator<Item = T> + Send + 'static,
K: Eq + Hash + SerializableKey + 'static,
KF: Fn(&T) -> K + Send + 'static,
V: RenderHtml + 'static,
VF: Fn(usize, T) -> (VFS, V) + Send + 'static,
VFS: Fn(usize) + 'static,
T: 'static,
{
type AsyncOutput = Vec<V::AsyncOutput>; // TODO
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
#[cfg(feature = "ssr")]
for view in &mut self.ssr_items {
view.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
#[cfg(feature = "ssr")]
{
futures::future::join_all(
self.ssr_items.into_iter().map(|(_, view)| view.resolve()),
)
.await
.into_iter()
.collect::<Vec<_>>()
}
#[cfg(not(feature = "ssr"))]
{
futures::future::join_all(
self.items.into_iter().flatten().enumerate().map(
|(index, item)| {
let (_, view) = (self.view_fn)(index, item);
view.resolve()
},
),
)
.await
.into_iter()
.collect::<Vec<_>>()
}
}
#[allow(unused)]
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
if mark_branches && escape {
buf.open_branch("for");
}
#[cfg(feature = "ssr")]
for item in self.ssr_items {
if mark_branches && escape {
buf.open_branch("item");
}
item.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
if mark_branches && escape {
buf.close_branch("item");
}
*position = Position::NextChild;
}
if mark_branches && escape {
buf.close_branch("for");
}
buf.push_str("<!>");
}
#[allow(unused)]
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>,
) {
if mark_branches && escape {
buf.open_branch("for");
}
#[cfg(feature = "ssr")]
for (key, item) in self.ssr_items {
let branch_name = mark_branches.then(|| format!("item-{key}"));
if mark_branches && escape {
buf.open_branch(branch_name.as_ref().unwrap());
}
item.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
if mark_branches && escape {
buf.close_branch(branch_name.as_ref().unwrap());
}
*position = Position::NextChild;
}
if mark_branches && escape {
buf.close_branch("for");
}
buf.push_sync("<!>");
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
// get parent and position
let current = cursor.current();
let parent = if position.get() == Position::FirstChild {
current
} else {
Rndr::get_parent(¤t)
.expect("first child of keyed list has no parent")
};
let parent = crate::renderer::types::Element::cast_from(parent)
.expect("parent of keyed list should be an element");
// build list
let items = self.items.into_iter().flatten();
let (capacity, _) = items.size_hint();
let mut hashed_items =
FxIndexSet::with_capacity_and_hasher(capacity, Default::default());
let mut rendered_items = Vec::with_capacity(capacity);
for (index, item) in items.enumerate() {
hashed_items.insert((self.key_fn)(&item));
let (set_index, view) = (self.view_fn)(index, item);
let item = view.hydrate::<FROM_SERVER>(cursor, position);
rendered_items.push(Some((set_index, item)));
}
let marker = cursor.next_placeholder(position);
position.set(Position::NextChild);
KeyedState {
parent: Some(parent),
marker,
hashed_items,
rendered_items,
}
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
// get parent and position
let current = cursor.current();
let parent = if position.get() == Position::FirstChild {
current
} else {
Rndr::get_parent(¤t)
.expect("first child of keyed list has no parent")
};
let parent = crate::renderer::types::Element::cast_from(parent)
.expect("parent of keyed list should be an element");
// build list
let items = self.items.into_iter().flatten();
let (capacity, _) = items.size_hint();
let mut hashed_items =
FxIndexSet::with_capacity_and_hasher(capacity, Default::default());
let mut rendered_items = Vec::with_capacity(capacity);
for (index, item) in items.enumerate() {
hashed_items.insert((self.key_fn)(&item));
let (set_index, view) = (self.view_fn)(index, item);
let item = view.hydrate_async(cursor, position).await;
rendered_items.push(Some((set_index, item)));
}
let marker = cursor.next_placeholder(position);
position.set(Position::NextChild);
KeyedState {
parent: Some(parent),
marker,
hashed_items,
rendered_items,
}
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl<K, VFS, V> Mountable for KeyedState<K, VFS, V>
where
K: Eq + Hash + 'static,
VFS: Fn(usize),
V: Render,
{
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
self.parent = Some(parent.clone());
for (_, item) in self.rendered_items.iter_mut().flatten() {
item.mount(parent, marker);
}
self.marker.mount(parent, marker);
}
fn unmount(&mut self) {
for (_, item) in self.rendered_items.iter_mut().flatten() {
item.unmount();
}
self.marker.unmount();
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.rendered_items
.first()
.map(|item| {
if let Some((_, item)) = item {
item.insert_before_this(child)
} else {
false
}
})
.unwrap_or_else(|| self.marker.insert_before_this(child))
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.rendered_items
.iter()
.flatten()
.flat_map(|item| item.1.elements())
.collect()
}
}
trait VecExt<T> {
fn get_next_closest_mounted_sibling(
&self,
start_at: usize,
) -> Option<&Option<T>>;
}
impl<T> VecExt<T> for Vec<Option<T>> {
fn get_next_closest_mounted_sibling(
&self,
start_at: usize,
) -> Option<&Option<T>> {
self[start_at..].iter().find(|s| s.is_some())
}
}
/// Calculates the operations needed to get from `from` to `to`.
fn diff<K: Eq + Hash>(from: &FxIndexSet<K>, to: &FxIndexSet<K>) -> Diff {
if from.is_empty() && to.is_empty() {
return Diff::default();
} else if to.is_empty() {
return Diff {
clear: true,
..Default::default()
};
} else if from.is_empty() {
return Diff {
added: to
.iter()
.enumerate()
.map(|(at, _)| DiffOpAdd {
at,
mode: DiffOpAddMode::Append,
})
.collect(),
..Default::default()
};
}
let mut removed = vec![];
let mut moved = vec![];
let mut added = vec![];
let max_len = std::cmp::max(from.len(), to.len());
for index in 0..max_len {
let from_item = from.get_index(index);
let to_item = to.get_index(index);
// if they're the same, do nothing
if from_item != to_item {
// if it's only in old, not new, remove it
if from_item.is_some() && !to.contains(from_item.unwrap()) {
let op = DiffOpRemove { at: index };
removed.push(op);
}
// if it's only in new, not old, add it
if to_item.is_some() && !from.contains(to_item.unwrap()) {
let op = DiffOpAdd {
at: index,
mode: DiffOpAddMode::Normal,
};
added.push(op);
}
// if it's in both old and new, it can either
// 1) be moved (and need to move in the DOM)
// 2) be moved (but not need to move in the DOM)
// * this would happen if, for example, 2 items
// have been added before it, and it has moved by 2
if let Some(from_item) = from_item {
if let Some(to_item) = to.get_full(from_item) {
let moves_forward_by = (to_item.0 as i32) - (index as i32);
let move_in_dom = moves_forward_by
!= (added.len() as i32) - (removed.len() as i32);
let op = DiffOpMove {
from: index,
len: 1,
to: to_item.0,
move_in_dom,
};
moved.push(op);
}
}
}
}
moved = group_adjacent_moves(moved);
Diff {
removed,
items_to_move: moved.iter().map(|m| m.len).sum(),
moved,
added,
clear: false,
}
}
/// Group adjacent items that are being moved as a group.
/// For example from `[2, 3, 5, 6]` to `[1, 2, 3, 4, 5, 6]` should result
/// in a move for `2,3` and `5,6` rather than 4 individual moves.
fn group_adjacent_moves(moved: Vec<DiffOpMove>) -> Vec<DiffOpMove> {
let mut prev: Option<DiffOpMove> = None;
let mut new_moved = Vec::with_capacity(moved.len());
for m in moved {
match prev {
Some(mut p) => {
if (m.from == p.from + p.len) && (m.to == p.to + p.len) {
p.len += 1;
prev = Some(p);
} else {
new_moved.push(prev.take().unwrap());
prev = Some(m);
}
}
None => prev = Some(m),
}
}
if let Some(prev) = prev {
new_moved.push(prev)
}
new_moved
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Diff {
removed: Vec<DiffOpRemove>,
moved: Vec<DiffOpMove>,
items_to_move: usize,
added: Vec<DiffOpAdd>,
clear: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct DiffOpMove {
/// The index this range is starting relative to `from`.
from: usize,
/// The number of elements included in this range.
len: usize,
/// The starting index this range will be moved to relative to `to`.
to: usize,
/// Marks this move to be applied to the DOM, or just to the underlying
/// storage
move_in_dom: bool,
}
impl Default for DiffOpMove {
fn default() -> Self {
Self {
from: 0,
to: 0,
len: 1,
move_in_dom: true,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct DiffOpAdd {
at: usize,
mode: DiffOpAddMode,
}
#[derive(Debug, PartialEq, Eq)]
struct DiffOpRemove {
at: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
enum DiffOpAddMode {
#[default]
Normal,
Append,
}
fn apply_diff<T, VFS, V>(
parent: Option<&crate::renderer::types::Element>,
marker: &crate::renderer::types::Placeholder,
diff: Diff,
children: &mut Vec<Option<(VFS, V::State)>>,
view_fn: impl Fn(usize, T) -> (VFS, V),
mut items: Vec<Option<T>>,
) where
VFS: Fn(usize),
V: Render,
{
// The order of cmds needs to be:
// 1. Clear
// 2. Removals
// 3. Move out
// 4. Resize
// 5. Move in
// 6. Additions
// 7. Removes holes
if diff.clear {
for (_, mut child) in children.drain(0..).flatten() {
child.unmount();
}
if diff.added.is_empty() {
return;
}
}
for DiffOpRemove { at } in &diff.removed {
let (_, mut item_to_remove) = children[*at].take().unwrap();
item_to_remove.unmount();
}
let (move_cmds, add_cmds) = unpack_moves(&diff);
let mut moved_children = move_cmds
.iter()
.map(|move_| children[move_.from].take())
.collect::<Vec<_>>();
children.resize_with(children.len() + diff.added.len(), || None);
for (i, DiffOpMove { to, .. }) in move_cmds
.iter()
.enumerate()
.filter(|(_, move_)| !move_.move_in_dom)
{
children[*to] = moved_children[i]
.take()
.inspect(|(set_index, _)| set_index(*to));
}
for (i, DiffOpMove { to, .. }) in move_cmds
.into_iter()
.enumerate()
.filter(|(_, move_)| move_.move_in_dom)
{
let (set_index, mut each_item) = moved_children[i].take().unwrap();
if let Some(parent) = parent {
if let Some(Some((_, state))) =
children.get_next_closest_mounted_sibling(to)
{
state.insert_before_this_or_marker(
parent,
&mut each_item,
Some(marker.as_ref()),
)
} else {
each_item.try_mount(parent, Some(marker.as_ref()));
}
}
set_index(to);
children[to] = Some((set_index, each_item));
}
for DiffOpAdd { at, mode } in add_cmds {
let item = items[at].take().unwrap();
let (set_index, item) = view_fn(at, item);
let mut item = item.build();
if let Some(parent) = parent {
match mode {
DiffOpAddMode::Normal => {
if let Some(Some((_, state))) =
children.get_next_closest_mounted_sibling(at)
{
state.insert_before_this_or_marker(
parent,
&mut item,
Some(marker.as_ref()),
)
} else {
item.try_mount(parent, Some(marker.as_ref()));
}
}
DiffOpAddMode::Append => {
item.try_mount(parent, Some(marker.as_ref()));
}
}
}
children[at] = Some((set_index, item));
}
#[allow(unstable_name_collisions)]
children.drain_filter(|c| c.is_none());
}
fn unpack_moves(diff: &Diff) -> (Vec<DiffOpMove>, Vec<DiffOpAdd>) {
let mut moves = Vec::with_capacity(diff.items_to_move);
let mut adds = Vec::with_capacity(diff.added.len());
let mut removes_iter = diff.removed.iter();
let mut adds_iter = diff.added.iter();
let mut moves_iter = diff.moved.iter();
let mut removes_next = removes_iter.next();
let mut adds_next = adds_iter.next();
let mut moves_next = moves_iter.next().copied();
for i in 0..diff.items_to_move + diff.added.len() + diff.removed.len() {
if let Some(DiffOpRemove { at, .. }) = removes_next {
if i == *at {
removes_next = removes_iter.next();
continue;
}
}
match (adds_next, &mut moves_next) {
(Some(add), Some(move_)) => {
if add.at == i {
adds.push(*add);
adds_next = adds_iter.next();
} else {
let mut single_move = *move_;
single_move.len = 1;
moves.push(single_move);
move_.len -= 1;
move_.from += 1;
move_.to += 1;
if move_.len == 0 {
moves_next = moves_iter.next().copied();
}
}
}
(Some(add), None) => {
adds.push(*add);
adds_next = adds_iter.next();
}
(None, Some(move_)) => {
let mut single_move = *move_;
single_move.len = 1;
moves.push(single_move);
move_.len -= 1;
move_.from += 1;
move_.to += 1;
if move_.len == 0 {
moves_next = moves_iter.next().copied();
}
}
(None, None) => break,
}
}
(moves, adds)
}
/*
#[cfg(test)]
mod tests {
use crate::{
html::element::{li, ul, HtmlElement, Li},
renderer::mock_dom::MockDom,
view::{keyed::keyed, Render},
};
fn item(key: usize) -> HtmlElement<Li, (), String, MockDom> {
li((), key.to_string())
}
#[test]
fn keyed_creates_list() {
let el = ul((), keyed(1..=3, |k| *k, item));
let el_state = el.build();
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li><li>3</li></ul>"
);
}
#[test]
fn adding_items_updates_list() {
let el = ul((), keyed(1..=3, |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed(1..=5, |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>"
);
}
#[test]
fn removing_items_updates_list() {
let el = ul((), keyed(1..=3, |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed(1..=2, |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li></ul>"
);
}
#[test]
fn swapping_items_updates_list() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([1, 4, 3, 2, 5], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>4</li><li>3</li><li>2</li><li>5</li></ul>"
);
}
#[test]
fn swapping_and_removing_orders_correctly() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([1, 4, 3, 5], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>4</li><li>3</li><li>5</li></ul>"
);
}
#[test]
fn arbitrarily_hard_adjustment() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([2, 4, 3], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>2</li><li>4</li><li>3</li></ul>"
);
}
#[test]
fn a_series_of_moves() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([2, 4, 3], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([1, 7, 5, 11, 13, 17], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([2, 6, 8, 7, 13], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([13, 4, 5, 3], |k| *k, item));
el.rebuild(&mut el_state);
let el = ul((), keyed([1, 2, 3, 4], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(
el_state.el.to_debug_html(),
"<ul><li>1</li><li>2</li><li>3</li><li>4</li></ul>"
);
}
#[test]
fn clearing_works() {
let el = ul((), keyed([1, 2, 3, 4, 5], |k| *k, item));
let mut el_state = el.build();
let el = ul((), keyed([], |k| *k, item));
el.rebuild(&mut el_state);
assert_eq!(el_state.el.to_debug_html(), "<ul></ul>");
}
}
*/
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/iterators.rs | tachys/src/view/iterators.rs | use super::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml,
};
use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
renderer::Rndr,
ssr::StreamBuilder,
};
use either_of::Either;
use itertools::Itertools;
/// Retained view state for an `Option`.
pub type OptionState<T> = Either<<T as Render>::State, <() as Render>::State>;
impl<T> Render for Option<T>
where
T: Render,
{
type State = OptionState<T>;
fn build(self) -> Self::State {
match self {
Some(value) => Either::Left(value),
None => Either::Right(()),
}
.build()
}
fn rebuild(self, state: &mut Self::State) {
match self {
Some(value) => Either::Left(value),
None => Either::Right(()),
}
.rebuild(state)
}
}
impl<T> AddAnyAttr for Option<T>
where
T: AddAnyAttr,
{
type Output<SomeNewAttr: Attribute> =
Option<<T as AddAnyAttr>::Output<SomeNewAttr>>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
self.map(|n| n.add_any_attr(attr))
}
}
impl<T> RenderHtml for Option<T>
where
T: RenderHtml,
{
type AsyncOutput = Option<T::AsyncOutput>;
type Owned = Option<T::Owned>;
const MIN_LENGTH: usize = T::MIN_LENGTH;
fn dry_resolve(&mut self) {
if let Some(inner) = self.as_mut() {
inner.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
match self {
None => None,
Some(value) => Some(value.resolve().await),
}
}
fn html_len(&self) -> usize {
match self {
Some(i) => i.html_len() + 3,
None => 3,
}
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
match self {
Some(value) => Either::Left(value),
None => Either::Right(()),
}
.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,
{
match self {
Some(value) => Either::Left(value),
None => Either::Right(()),
}
.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs,
)
}
#[track_caller]
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
match self {
Some(value) => Either::Left(value),
None => Either::Right(()),
}
.hydrate::<FROM_SERVER>(cursor, position)
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
match self {
Some(value) => Either::Left(value),
None => Either::Right(()),
}
.hydrate_async(cursor, position)
.await
}
fn into_owned(self) -> Self::Owned {
self.map(RenderHtml::into_owned)
}
}
impl<T> Render for Vec<T>
where
T: Render,
{
type State = VecState<T::State>;
fn build(self) -> Self::State {
let marker = Rndr::create_placeholder();
VecState {
states: self.into_iter().map(T::build).collect(),
marker,
}
}
fn rebuild(self, state: &mut Self::State) {
let VecState { states, marker } = state;
let old = states;
// this is an unkeyed diff
if old.is_empty() {
let mut new = self.build().states;
for item in new.iter_mut() {
Rndr::try_mount_before(item, marker.as_ref());
}
*old = new;
} else if self.is_empty() {
// TODO fast path for clearing
for item in old.iter_mut() {
item.unmount();
}
old.clear();
} else {
let mut adds = vec![];
let mut removes_at_end = 0;
for item in self.into_iter().zip_longest(old.iter_mut()) {
match item {
itertools::EitherOrBoth::Both(new, old) => {
T::rebuild(new, old)
}
itertools::EitherOrBoth::Left(new) => {
let mut new_state = new.build();
Rndr::try_mount_before(&mut new_state, marker.as_ref());
adds.push(new_state);
}
itertools::EitherOrBoth::Right(old) => {
removes_at_end += 1;
old.unmount()
}
}
}
old.truncate(old.len() - removes_at_end);
old.append(&mut adds);
}
}
}
/// Retained view state for a `Vec<_>`.
pub struct VecState<T>
where
T: Mountable,
{
states: Vec<T>,
// Vecs keep a placeholder because they have the potential to add additional items,
// after their own items but before the next neighbor. It is much easier to add an
// item before a known placeholder than to add it after the last known item, so we
// just leave a placeholder here unlike zero-or-one iterators (Option, Result, etc.)
marker: crate::renderer::types::Placeholder,
}
impl<T> Mountable for VecState<T>
where
T: Mountable,
{
fn unmount(&mut self) {
for state in self.states.iter_mut() {
state.unmount();
}
self.marker.unmount();
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
for state in self.states.iter_mut() {
state.mount(parent, marker);
}
self.marker.mount(parent, marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
for state in &self.states {
if state.insert_before_this(child) {
return true;
}
}
self.marker.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.states
.iter()
.flat_map(|item| item.elements())
.collect()
}
}
impl<T> AddAnyAttr for Vec<T>
where
T: AddAnyAttr,
{
type Output<SomeNewAttr: Attribute> =
Vec<<T as AddAnyAttr>::Output<SomeNewAttr::Cloneable>>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let attr = attr.into_cloneable();
self.into_iter()
.map(|n| n.add_any_attr(attr.clone()))
.collect()
}
}
impl<T> RenderHtml for Vec<T>
where
T: RenderHtml,
{
type AsyncOutput = Vec<T::AsyncOutput>;
type Owned = Vec<T::Owned>;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
for inner in self.iter_mut() {
inner.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
futures::future::join_all(self.into_iter().map(T::resolve))
.await
.into_iter()
.collect()
}
fn html_len(&self) -> usize {
self.iter().map(|n| n.html_len()).sum::<usize>() + 3
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
let mut children = self.into_iter();
if let Some(first) = children.next() {
first.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
}
for child in children {
child.to_html_with_buf(
buf,
position,
escape,
mark_branches,
// each child will have the extra attributes applied
extra_attrs.clone(),
);
}
if escape {
buf.push_str("<!>");
*position = Position::NextChild;
}
}
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,
{
let mut children = self.into_iter();
if let Some(first) = children.next() {
first.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
}
for child in children {
child.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
}
if escape {
buf.push_sync("<!>");
*position = Position::NextChild;
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let states = self
.into_iter()
.map(|child| child.hydrate::<FROM_SERVER>(cursor, position))
.collect();
let marker = cursor.next_placeholder(position);
position.set(Position::NextChild);
VecState { states, marker }
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let mut states = Vec::with_capacity(self.len());
for child in self {
states.push(child.hydrate_async(cursor, position).await);
}
let marker = cursor.next_placeholder(position);
position.set(Position::NextChild);
VecState { states, marker }
}
fn into_owned(self) -> Self::Owned {
self.into_iter()
.map(RenderHtml::into_owned)
.collect::<Vec<_>>()
}
}
/// A container used for ErasedMode. It's slightly better than a raw Vec<> because the rendering traits don't have to worry about the length of the Vec changing, therefore no marker traits etc.
pub struct StaticVec<T>(pub(crate) Vec<T>);
impl<T: Clone> Clone for StaticVec<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T> IntoIterator for StaticVec<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<T> StaticVec<T> {
/// Iterates over the items.
pub fn iter(&self) -> std::slice::Iter<'_, T> {
self.0.iter()
}
}
impl<T> From<Vec<T>> for StaticVec<T> {
fn from(vec: Vec<T>) -> Self {
Self(vec)
}
}
impl<T> From<StaticVec<T>> for Vec<T> {
fn from(static_vec: StaticVec<T>) -> Self {
static_vec.0
}
}
/// Retained view state for a `StaticVec<Vec<_>>`.
pub struct StaticVecState<T>
where
T: Mountable,
{
states: Vec<T>,
marker: crate::renderer::types::Placeholder,
}
impl<T> Mountable for StaticVecState<T>
where
T: Mountable,
{
fn unmount(&mut self) {
for state in self.states.iter_mut() {
state.unmount();
}
self.marker.unmount();
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
for state in self.states.iter_mut() {
state.mount(parent, marker);
}
self.marker.mount(parent, marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
for state in &self.states {
if state.insert_before_this(child) {
return true;
}
}
self.marker.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.states
.iter()
.flat_map(|item| item.elements())
.collect()
}
}
impl<T> Render for StaticVec<T>
where
T: Render,
{
type State = StaticVecState<T::State>;
fn build(self) -> Self::State {
let marker = Rndr::create_placeholder();
Self::State {
states: self.0.into_iter().map(T::build).collect(),
marker,
}
}
fn rebuild(self, state: &mut Self::State) {
let StaticVecState { states, marker } = state;
let old = states;
// reuses the Vec impl
if old.is_empty() {
let mut new = self.build().states;
for item in new.iter_mut() {
Rndr::mount_before(item, marker.as_ref());
}
*old = new;
} else if self.0.is_empty() {
// TODO fast path for clearing
for item in old.iter_mut() {
item.unmount();
}
old.clear();
} else {
let mut adds = vec![];
let mut removes_at_end = 0;
for item in self.0.into_iter().zip_longest(old.iter_mut()) {
match item {
itertools::EitherOrBoth::Both(new, old) => {
T::rebuild(new, old)
}
itertools::EitherOrBoth::Left(new) => {
let mut new_state = new.build();
Rndr::mount_before(&mut new_state, marker.as_ref());
adds.push(new_state);
}
itertools::EitherOrBoth::Right(old) => {
removes_at_end += 1;
old.unmount()
}
}
}
old.truncate(old.len() - removes_at_end);
old.append(&mut adds);
}
}
}
impl<T> AddAnyAttr for StaticVec<T>
where
T: AddAnyAttr,
{
type Output<SomeNewAttr: Attribute> =
StaticVec<<T as AddAnyAttr>::Output<SomeNewAttr::Cloneable>>;
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let attr = attr.into_cloneable();
self.0
.into_iter()
.map(|n| n.add_any_attr(attr.clone()))
.collect::<Vec<_>>()
.into()
}
}
impl<T> RenderHtml for StaticVec<T>
where
T: RenderHtml,
{
type AsyncOutput = StaticVec<T::AsyncOutput>;
type Owned = StaticVec<T::Owned>;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
for inner in self.0.iter_mut() {
inner.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
futures::future::join_all(self.0.into_iter().map(T::resolve))
.await
.into_iter()
.collect::<Vec<_>>()
.into()
}
fn html_len(&self) -> usize {
self.0.iter().map(RenderHtml::html_len).sum::<usize>() + 3
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
for child in self.0.into_iter() {
child.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
}
if escape {
buf.push_str("<!>");
*position = Position::NextChild;
}
}
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,
{
for child in self.0.into_iter() {
child.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
}
if escape {
buf.push_sync("<!>");
*position = Position::NextChild;
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let states = self
.0
.into_iter()
.map(|child| child.hydrate::<FROM_SERVER>(cursor, position))
.collect();
let marker = cursor.next_placeholder(position);
position.set(Position::NextChild);
Self::State { states, marker }
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let mut states = Vec::with_capacity(self.0.len());
for child in self.0 {
states.push(child.hydrate_async(cursor, position).await);
}
let marker = cursor.next_placeholder(position);
position.set(Position::NextChild);
Self::State { states, marker }
}
fn into_owned(self) -> Self::Owned {
self.0
.into_iter()
.map(RenderHtml::into_owned)
.collect::<Vec<_>>()
.into()
}
}
impl<T, const N: usize> Render for [T; N]
where
T: Render,
{
type State = ArrayState<T::State, N>;
fn build(self) -> Self::State {
Self::State {
states: self.map(T::build),
}
}
fn rebuild(self, state: &mut Self::State) {
let Self::State { states } = state;
let old = states;
// this is an unkeyed diff
self.into_iter()
.zip(old.iter_mut())
.for_each(|(new, old)| T::rebuild(new, old));
}
}
/// Retained view state for a `Vec<_>`.
pub struct ArrayState<T, const N: usize>
where
T: Mountable,
{
states: [T; N],
}
impl<T, const N: usize> Mountable for ArrayState<T, N>
where
T: Mountable,
{
fn unmount(&mut self) {
self.states.iter_mut().for_each(Mountable::unmount);
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
for state in self.states.iter_mut() {
state.mount(parent, marker);
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
for state in &self.states {
if state.insert_before_this(child) {
return true;
}
}
false
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.states
.iter()
.flat_map(|item| item.elements())
.collect()
}
}
impl<T, const N: usize> AddAnyAttr for [T; N]
where
T: AddAnyAttr,
{
type Output<SomeNewAttr: Attribute> =
[<T as AddAnyAttr>::Output<SomeNewAttr::Cloneable>; N];
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let attr = attr.into_cloneable();
self.map(|n| n.add_any_attr(attr.clone()))
}
}
impl<T, const N: usize> RenderHtml for [T; N]
where
T: RenderHtml,
{
type AsyncOutput = [T::AsyncOutput; N];
type Owned = [T::Owned; N];
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {
for inner in self.iter_mut() {
inner.dry_resolve();
}
}
async fn resolve(self) -> Self::AsyncOutput {
futures::future::join_all(self.into_iter().map(T::resolve))
.await
.into_iter()
.collect::<Vec<_>>()
.try_into()
.unwrap_or_else(|_| unreachable!())
}
fn html_len(&self) -> usize {
self.iter().map(RenderHtml::html_len).sum::<usize>()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
for child in self.into_iter() {
child.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
}
}
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,
{
for child in self.into_iter() {
child.to_html_async_with_buf::<OUT_OF_ORDER>(
buf,
position,
escape,
mark_branches,
extra_attrs.clone(),
);
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let states =
self.map(|child| child.hydrate::<FROM_SERVER>(cursor, position));
ArrayState { states }
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let mut states = Vec::with_capacity(self.len());
for child in self {
states.push(child.hydrate_async(cursor, position).await);
}
let Ok(states) = <[<T as Render>::State; N]>::try_from(states) else {
unreachable!()
};
ArrayState { states }
}
fn into_owned(self) -> Self::Owned {
self.into_iter()
.map(RenderHtml::into_owned)
.collect::<Vec<_>>()
.try_into()
.unwrap_or_else(|_| unreachable!())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/mod.rs | tachys/src/view/mod.rs | use self::add_attr::AddAnyAttr;
use crate::{
html::attribute::any_attribute::AnyAttribute, hydration::Cursor,
ssr::StreamBuilder,
};
use parking_lot::RwLock;
use std::{cell::RefCell, future::Future, rc::Rc, sync::Arc};
/// Add attributes to typed views.
pub mod add_attr;
/// A typed-erased view type.
pub mod any_view;
/// Allows choosing between one of several views.
pub mod either;
/// View rendering for `Result<_, _>` types.
pub mod error_boundary;
/// A type-erased view collection.
pub mod fragment;
/// View implementations for several iterable types.
pub mod iterators;
/// Keyed list iteration.
pub mod keyed;
mod primitives;
/// Optimized types for static strings known at compile time.
#[cfg(all(feature = "nightly", rustc_nightly))]
pub mod static_types;
/// View implementation for string types.
pub mod strings;
/// Optimizations for creating views via HTML `<template>` nodes.
pub mod template;
/// View implementations for tuples.
pub mod tuples;
/// The `Render` trait allows rendering something as part of the user interface.
pub trait Render: Sized {
/// The “view state” for this type, which can be retained between updates.
///
/// For example, for a text node, `State` might be the actual DOM text node
/// and the previous string, to allow for diffing between updates.
type State: Mountable;
/// Creates the view for the first time, without hydrating from existing HTML.
fn build(self) -> Self::State;
/// Updates the view with new data.
fn rebuild(self, state: &mut Self::State);
}
#[doc(hidden)]
pub trait MarkBranch {
fn open_branch(&mut self, branch_id: &str);
fn close_branch(&mut self, branch_id: &str);
}
impl MarkBranch for String {
fn open_branch(&mut self, branch_id: &str) {
self.push_str("<!--bo-");
self.push_str(branch_id);
self.push_str("-->");
}
fn close_branch(&mut self, branch_id: &str) {
self.push_str("<!--bc-");
self.push_str(branch_id);
self.push_str("-->");
}
}
impl MarkBranch for StreamBuilder {
fn open_branch(&mut self, branch_id: &str) {
self.sync_buf.push_str("<!--bo-");
self.sync_buf.push_str(branch_id);
self.sync_buf.push_str("-->");
}
fn close_branch(&mut self, branch_id: &str) {
self.sync_buf.push_str("<!--bc-");
self.sync_buf.push_str(branch_id);
self.sync_buf.push_str("-->");
}
}
/// The `RenderHtml` trait allows rendering something to HTML, and transforming
/// that HTML into an interactive interface.
///
/// This process is traditionally called “server rendering” and “hydration.” As a
/// metaphor, this means that the structure of the view is created on the server, then
/// “dehydrated” to HTML, sent across the network, and “rehydrated” with interactivity
/// in the browser.
///
/// However, the same process can be done entirely in the browser: for example, a view
/// can be transformed into some HTML that is used to create a `<template>` node, which
/// can be cloned many times and “hydrated,” which is more efficient than creating the
/// whole view piece by piece.
pub trait RenderHtml
where
Self: Render + AddAnyAttr + Send,
{
/// The type of the view after waiting for all asynchronous data to load.
type AsyncOutput: RenderHtml;
/// An equivalent value that is `'static`.
type Owned: RenderHtml + 'static;
/// The minimum length of HTML created when this view is rendered.
const MIN_LENGTH: usize;
/// Whether this should actually exist in the DOM, if it is the child of an element.
const EXISTS: bool = true;
/// “Runs” the view without other side effects. For primitive types, this is a no-op. For
/// reactive types, this can be used to gather data about reactivity or about asynchronous data
/// that needs to be loaded.
fn dry_resolve(&mut self);
/// Waits for any asynchronous sections of the view to load and returns the output.
fn resolve(self) -> impl Future<Output = Self::AsyncOutput> + Send;
/// An estimated length for this view, when rendered to HTML.
///
/// This is used for calculating the string buffer size when rendering HTML. It does not need
/// to be precise, but should be an appropriate estimate. The more accurate, the fewer
/// reallocations will be required and the faster server-side rendering will be.
fn html_len(&self) -> usize {
Self::MIN_LENGTH
}
/// Renders a view to an HTML string.
fn to_html(self) -> String
where
Self: Sized,
{
let mut buf = String::with_capacity(self.html_len());
self.to_html_with_buf(
&mut buf,
&mut Position::FirstChild,
true,
false,
vec![],
);
buf
}
/// Renders a view to HTML with branch markers. This can be used to support libraries that diff
/// HTML pages against one another, by marking sections of the view that branch to different
/// types with marker comments.
fn to_html_branching(self) -> String
where
Self: Sized,
{
let mut buf = String::with_capacity(self.html_len());
self.to_html_with_buf(
&mut buf,
&mut Position::FirstChild,
true,
true,
vec![],
);
buf
}
/// Renders a view to an in-order stream of HTML.
fn to_html_stream_in_order(self) -> StreamBuilder
where
Self: Sized,
{
let mut builder = StreamBuilder::with_capacity(self.html_len(), None);
self.to_html_async_with_buf::<false>(
&mut builder,
&mut Position::FirstChild,
true,
false,
vec![],
);
builder.finish()
}
/// Renders a view to an in-order stream of HTML with branch markers. This can be used to support libraries that diff
/// HTML pages against one another, by marking sections of the view that branch to different
/// types with marker comments.
fn to_html_stream_in_order_branching(self) -> StreamBuilder
where
Self: Sized,
{
let mut builder = StreamBuilder::with_capacity(self.html_len(), None);
self.to_html_async_with_buf::<false>(
&mut builder,
&mut Position::FirstChild,
true,
true,
vec![],
);
builder.finish()
}
/// Renders a view to an out-of-order stream of HTML.
fn to_html_stream_out_of_order(self) -> StreamBuilder
where
Self: Sized,
{
//let capacity = self.html_len();
let mut builder =
StreamBuilder::with_capacity(self.html_len(), Some(vec![0]));
self.to_html_async_with_buf::<true>(
&mut builder,
&mut Position::FirstChild,
true,
false,
vec![],
);
builder.finish()
}
/// Renders a view to an out-of-order stream of HTML with branch markers. This can be used to support libraries that diff
/// HTML pages against one another, by marking sections of the view that branch to different
/// types with marker comments.
fn to_html_stream_out_of_order_branching(self) -> StreamBuilder
where
Self: Sized,
{
let mut builder =
StreamBuilder::with_capacity(self.html_len(), Some(vec![0]));
self.to_html_async_with_buf::<true>(
&mut builder,
&mut Position::FirstChild,
true,
true,
vec![],
);
builder.finish()
}
/// Renders a view to HTML, writing it into the given buffer.
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
);
/// Renders a view into a buffer of (synchronous or asynchronous) HTML chunks.
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,
{
buf.with_buf(|buf| {
self.to_html_with_buf(
buf,
position,
escape,
mark_branches,
extra_attrs,
)
});
}
/// Makes a set of DOM nodes rendered from HTML interactive.
///
/// If `FROM_SERVER` is `true`, this HTML was rendered using [`RenderHtml::to_html`]
/// (e.g., during server-side rendering ).
///
/// If `FROM_SERVER` is `false`, the HTML was rendered using [`ToTemplate::to_template`]
/// (e.g., into a `<template>` element).
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State;
/// Asynchronously makes a set of DOM nodes rendered from HTML interactive.
///
/// Async hydration is useful for types that may need to wait before being hydrated:
/// for example, lazily-loaded routes need async hydration, because the client code
/// may be loading asynchronously, while the server HTML was already rendered.
fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> impl Future<Output = Self::State> {
async { self.hydrate::<true>(cursor, position) }
}
/// Hydrates using [`RenderHtml::hydrate`], beginning at the given element.
fn hydrate_from<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
) -> Self::State
where
Self: Sized,
{
self.hydrate_from_position::<FROM_SERVER>(el, Position::default())
}
/// Hydrates using [`RenderHtml::hydrate`], beginning at the given element and position.
fn hydrate_from_position<const FROM_SERVER: bool>(
self,
el: &crate::renderer::types::Element,
position: Position,
) -> Self::State
where
Self: Sized,
{
let cursor = Cursor::new(el.clone());
let position = PositionState::new(position);
self.hydrate::<FROM_SERVER>(&cursor, &position)
}
/// Convert into the equivalent value that is `'static`.
fn into_owned(self) -> Self::Owned;
}
/// Allows a type to be mounted to the DOM.
pub trait Mountable {
/// Detaches the view from the DOM.
fn unmount(&mut self);
/// Mounts a node to the interface.
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
);
/// Mounts a node to the interface. Returns `false` if it could not be mounted.
fn try_mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) -> bool {
self.mount(parent, marker);
true
}
/// Inserts another `Mountable` type before this one. Returns `false` if
/// this does not actually exist in the UI (for example, `()`).
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool;
/// Inserts another `Mountable` type before this one, or before the marker
/// if this one doesn't exist in the UI (for example, `()`).
fn insert_before_this_or_marker(
&self,
parent: &crate::renderer::types::Element,
child: &mut dyn Mountable,
marker: Option<&crate::renderer::types::Node>,
) {
if !self.insert_before_this(child) {
child.mount(parent, marker);
}
}
/// wip
fn elements(&self) -> Vec<crate::renderer::types::Element>;
}
/// Indicates where a node should be mounted to its parent.
pub enum MountKind {
/// Node should be mounted before this marker node.
Before(crate::renderer::types::Node),
/// Node should be appended to the parent’s children.
Append,
}
impl<T> Mountable for Option<T>
where
T: Mountable,
{
fn unmount(&mut self) {
if let Some(ref mut mounted) = self {
mounted.unmount()
}
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
if let Some(ref mut inner) = self {
inner.mount(parent, marker);
}
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.as_ref()
.map(|inner| inner.insert_before_this(child))
.unwrap_or(false)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.as_ref()
.map(|inner| inner.elements())
.unwrap_or_default()
}
}
impl<T> Mountable for Rc<RefCell<T>>
where
T: Mountable,
{
fn unmount(&mut self) {
self.borrow_mut().unmount()
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
self.borrow_mut().mount(parent, marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.borrow().insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
self.borrow().elements()
}
}
/// Allows data to be added to a static template.
pub trait ToTemplate {
/// The HTML content of the static template.
const TEMPLATE: &'static str = "";
/// The `class` attribute content known at compile time.
const CLASS: &'static str = "";
/// The `style` attribute content known at compile time.
const STYLE: &'static str = "";
/// The length of the template.
const LEN: usize = Self::TEMPLATE.len();
/// Renders a view type to a template. This does not take actual view data,
/// but can be used for constructing part of an HTML `<template>` that corresponds
/// to a view of a particular type.
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
);
/// Renders a view type to a template in attribute position.
fn to_template_attribute(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
Self::to_template(buf, class, style, inner_html, position);
}
}
/// Keeps track of what position the item currently being hydrated is in, relative to its siblings
/// and parents.
#[derive(Debug, Default, Clone)]
pub struct PositionState(Arc<RwLock<Position>>);
impl PositionState {
/// Creates a new position tracker.
pub fn new(position: Position) -> Self {
Self(Arc::new(RwLock::new(position)))
}
/// Sets the current position.
pub fn set(&self, position: Position) {
*self.0.write() = position;
}
/// Gets the current position.
pub fn get(&self) -> Position {
*self.0.read()
}
/// Creates a new [`PositionState`], which starts with the same [`Position`], but no longer
/// shares data with this `PositionState`.
pub fn deep_clone(&self) -> Self {
let current = self.get();
Self(Arc::new(RwLock::new(current)))
}
}
/// The position of this element, relative to others.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub enum Position {
/// This is the current node.
Current,
/// This is the first child of its parent.
#[default]
FirstChild,
/// This is the next child after another child.
NextChild,
/// This is the next child after a text node.
NextChildAfterText,
/// This is the only child of its parent.
OnlyChild,
/// This is the last child of its parent.
LastChild,
}
/// Declares that this type can be converted into some other type, which can be rendered.
pub trait IntoRender {
/// The renderable type into which this type can be converted.
type Output;
/// Consumes this value, transforming it into the renderable type.
fn into_render(self) -> Self::Output;
}
impl<T> IntoRender for T
where
T: Render,
{
type Output = Self;
fn into_render(self) -> Self::Output {
self
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/strings.rs | tachys/src/view/strings.rs | use super::{
Mountable, Position, PositionState, Render, RenderHtml, ToTemplate,
};
use crate::{
html::attribute::any_attribute::AnyAttribute,
hydration::Cursor,
no_attrs,
renderer::{CastFrom, Rndr},
};
use std::{borrow::Cow, rc::Rc, sync::Arc};
no_attrs!(&'a str);
no_attrs!(String);
no_attrs!(Arc<str>);
no_attrs!(Cow<'a, str>);
/// Retained view state for `&str`.
pub struct StrState<'a> {
pub(crate) node: crate::renderer::types::Text,
str: &'a str,
}
impl<'a> Render for &'a str {
type State = StrState<'a>;
fn build(self) -> Self::State {
let node = Rndr::create_text_node(self);
StrState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let StrState { node, str } = state;
if &self != str {
Rndr::set_text(node, self);
*str = self;
}
}
}
impl RenderHtml for &str {
type AsyncOutput = Self;
type Owned = String;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn html_len(&self) -> usize {
self.len()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
_mark_branches: bool,
_extra_attrs: Vec<AnyAttribute>,
) {
// add a comment node to separate from previous sibling, if any
if matches!(position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
if self.is_empty() && escape {
buf.push(' ');
} else if escape {
let escaped = html_escape::encode_text(self);
buf.push_str(&escaped);
} else {
buf.push_str(self);
}
*position = Position::NextChildAfterText;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
if position.get() == Position::FirstChild {
cursor.child();
} else {
cursor.sibling();
}
// separating placeholder marker comes before text node
if matches!(position.get(), Position::NextChildAfterText) {
cursor.sibling();
}
let node = cursor.current();
let node = crate::renderer::types::Text::cast_from(node.clone())
.unwrap_or_else(|| {
crate::hydration::failed_to_cast_text_node(node)
});
if !FROM_SERVER {
Rndr::set_text(&node, self);
}
position.set(Position::NextChildAfterText);
StrState { node, str: self }
}
fn into_owned(self) -> Self::Owned {
self.to_string()
}
}
impl ToTemplate for &str {
const TEMPLATE: &'static str = " <!>";
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
position: &mut Position,
) {
if matches!(*position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push(' ');
*position = Position::NextChildAfterText;
}
}
impl Mountable for StrState<'_> {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
Rndr::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.node.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![]
}
}
/// Retained view state for `String`.
pub struct StringState {
node: crate::renderer::types::Text,
str: String,
}
impl Render for String {
type State = StringState;
fn build(self) -> Self::State {
let node = Rndr::create_text_node(&self);
StringState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let StringState { node, str } = state;
if &self != str {
Rndr::set_text(node, &self);
*str = self;
}
}
}
impl RenderHtml for String {
const MIN_LENGTH: usize = 0;
type AsyncOutput = Self;
type Owned = Self;
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn html_len(&self) -> usize {
self.len()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
<&str as RenderHtml>::to_html_with_buf(
self.as_str(),
buf,
position,
escape,
mark_branches,
extra_attrs,
)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let StrState { node, .. } =
self.as_str().hydrate::<FROM_SERVER>(cursor, position);
StringState { node, str: self }
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl ToTemplate for String {
const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
<&str as ToTemplate>::to_template(
buf, class, style, inner_html, position,
)
}
}
impl Mountable for StringState {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
Rndr::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.node.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![]
}
}
/// Retained view state for `Rc<str>`.
pub struct RcStrState {
node: crate::renderer::types::Text,
str: Rc<str>,
}
impl Render for Rc<str> {
type State = RcStrState;
fn build(self) -> Self::State {
let node = Rndr::create_text_node(&self);
RcStrState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let RcStrState { node, str } = state;
if !Rc::ptr_eq(&self, str) {
Rndr::set_text(node, &self);
*str = self;
}
}
}
// can't Send an Rc<str> between threads, so can't implement async HTML rendering that might need
// to send it
/*
impl RenderHtml for Rc<str>
where
{
type AsyncOutput = Self;
const MIN_LENGTH: usize = 0;
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn html_len(&self) -> usize {
self.len()
}
fn to_html_with_buf(self, buf: &mut String, position: &mut Position, escape: bool, mark_branches: bool) {
<&str as RenderHtml>::to_html_with_buf(&self, buf, position)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let this: &str = self.as_ref();
let StrState { node, .. } =
this.hydrate::<FROM_SERVER>(cursor, position);
RcStrState { node, str: self }
}
}*/
impl ToTemplate for Rc<str> {
const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
<&str as ToTemplate>::to_template(
buf, class, style, inner_html, position,
)
}
}
impl Mountable for RcStrState {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
Rndr::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.node.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![]
}
}
/// Retained view state for `Arc<str>`.
pub struct ArcStrState {
node: crate::renderer::types::Text,
str: Arc<str>,
}
impl Render for Arc<str> {
type State = ArcStrState;
fn build(self) -> Self::State {
let node = Rndr::create_text_node(&self);
ArcStrState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let ArcStrState { node, str } = state;
if self != *str {
Rndr::set_text(node, &self);
*str = self;
}
}
}
impl RenderHtml for Arc<str> {
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn html_len(&self) -> usize {
self.len()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
<&str as RenderHtml>::to_html_with_buf(
&self,
buf,
position,
escape,
mark_branches,
extra_attrs,
)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let this: &str = self.as_ref();
let StrState { node, .. } =
this.hydrate::<FROM_SERVER>(cursor, position);
ArcStrState { node, str: self }
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl ToTemplate for Arc<str> {
const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
<&str as ToTemplate>::to_template(
buf, class, style, inner_html, position,
)
}
}
impl Mountable for ArcStrState {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
Rndr::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.node.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![]
}
}
/// Retained view state for `Cow<'_, str>`.
pub struct CowStrState<'a> {
node: crate::renderer::types::Text,
str: Cow<'a, str>,
}
impl<'a> Render for Cow<'a, str> {
type State = CowStrState<'a>;
fn build(self) -> Self::State {
let node = Rndr::create_text_node(&self);
CowStrState { node, str: self }
}
fn rebuild(self, state: &mut Self::State) {
let CowStrState { node, str } = state;
if self != *str {
Rndr::set_text(node, &self);
*str = self;
}
}
}
impl RenderHtml for Cow<'_, str> {
type AsyncOutput = Self;
type Owned = String;
const MIN_LENGTH: usize = 0;
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self::AsyncOutput {
self
}
fn html_len(&self) -> usize {
self.len()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>,
) {
<&str as RenderHtml>::to_html_with_buf(
&self,
buf,
position,
escape,
mark_branches,
extra_attrs,
)
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let this: &str = self.as_ref();
let StrState { node, .. } =
this.hydrate::<FROM_SERVER>(cursor, position);
CowStrState { node, str: self }
}
fn into_owned(self) -> <Self as RenderHtml>::Owned {
self.into_owned()
}
}
impl ToTemplate for Cow<'_, str> {
const TEMPLATE: &'static str = <&str as ToTemplate>::TEMPLATE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
<&str as ToTemplate>::to_template(
buf, class, style, inner_html, position,
)
}
}
impl Mountable for CowStrState<'_> {
fn unmount(&mut self) {
self.node.unmount()
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
Rndr::insert_node(parent, self.node.as_ref(), marker);
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.node.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![]
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/tuples.rs | tachys/src/view/tuples.rs | use super::{
Mountable, Position, PositionState, Render, RenderHtml, ToTemplate,
};
use crate::{
html::attribute::{any_attribute::AnyAttribute, Attribute},
hydration::Cursor,
renderer::Rndr,
view::{add_attr::AddAnyAttr, StreamBuilder},
};
use const_str_slice_concat::{
const_concat, const_concat_with_separator, str_from_buffer,
};
impl Render for () {
type State = crate::renderer::types::Placeholder;
fn build(self) -> Self::State {
Rndr::create_placeholder()
}
fn rebuild(self, _state: &mut Self::State) {}
}
impl RenderHtml for () {
type AsyncOutput = ();
type Owned = ();
const MIN_LENGTH: usize = 3;
const EXISTS: bool = false;
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
_mark_branches: bool,
_extra_attrs: Vec<AnyAttribute>,
) {
if escape {
buf.push_str("<!>");
*position = Position::NextChild;
}
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let marker = cursor.next_placeholder(position);
position.set(Position::NextChild);
marker
}
async fn resolve(self) -> Self::AsyncOutput {}
fn dry_resolve(&mut self) {}
fn into_owned(self) -> Self::Owned {}
}
impl AddAnyAttr for () {
type Output<SomeNewAttr: Attribute> = ();
fn add_any_attr<NewAttr: Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
}
}
impl Mountable for () {
fn unmount(&mut self) {}
fn mount(
&mut self,
_parent: &crate::renderer::types::Element,
_marker: Option<&crate::renderer::types::Node>,
) {
}
fn insert_before_this(&self, _child: &mut dyn Mountable) -> bool {
false
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![]
}
}
impl ToTemplate for () {
const TEMPLATE: &'static str = "<!>";
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
buf.push_str("<!>");
}
fn to_template_attribute(
_buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
}
}
impl<A: Render> Render for (A,) {
type State = A::State;
fn build(self) -> Self::State {
self.0.build()
}
fn rebuild(self, state: &mut Self::State) {
self.0.rebuild(state)
}
}
impl<A> RenderHtml for (A,)
where
A: RenderHtml,
{
type AsyncOutput = (A::AsyncOutput,);
type Owned = (A::Owned,);
const MIN_LENGTH: usize = A::MIN_LENGTH;
const EXISTS: bool = A::EXISTS;
fn html_len(&self) -> usize {
self.0.html_len()
}
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)
}
async fn hydrate_async(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
self.0.hydrate_async(cursor, position).await
}
async fn resolve(self) -> Self::AsyncOutput {
(self.0.resolve().await,)
}
fn dry_resolve(&mut self) {
self.0.dry_resolve();
}
fn into_owned(self) -> Self::Owned {
(self.0.into_owned(),)
}
}
impl<A: ToTemplate> ToTemplate for (A,) {
const TEMPLATE: &'static str = A::TEMPLATE;
const CLASS: &'static str = A::CLASS;
const STYLE: &'static str = A::STYLE;
fn to_template(
buf: &mut String,
class: &mut String,
style: &mut String,
inner_html: &mut String,
position: &mut Position,
) {
A::to_template(buf, class, style, inner_html, position)
}
}
impl<A> AddAnyAttr for (A,)
where
A: AddAnyAttr,
{
type Output<SomeNewAttr: Attribute> = (A::Output<SomeNewAttr>,);
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
(self.0.add_any_attr(attr),)
}
}
macro_rules! impl_view_for_tuples {
($first:ident, $($ty:ident),* $(,)?) => {
impl<$first, $($ty),*> Render for ($first, $($ty,)*)
where
$first: Render,
$($ty: Render),*,
{
type State = ($first::State, $($ty::State,)*);
fn build(self) -> Self::State {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.build(),
$($ty.build()),*
)
}
fn rebuild(self, state: &mut Self::State) {
paste::paste! {
let ([<$first:lower>], $([<$ty:lower>],)*) = self;
let ([<view_ $first:lower>], $([<view_ $ty:lower>],)*) = state;
[<$first:lower>].rebuild([<view_ $first:lower>]);
$([<$ty:lower>].rebuild([<view_ $ty:lower>]));*
}
}
}
impl<$first, $($ty),*> RenderHtml for ($first, $($ty,)*)
where
$first: RenderHtml,
$($ty: RenderHtml),*,
{
type AsyncOutput = ($first::AsyncOutput, $($ty::AsyncOutput,)*);
type Owned = ($first::Owned, $($ty::Owned,)*);
const EXISTS: bool = $first::EXISTS || $($ty::EXISTS || )* false;
const MIN_LENGTH: usize = $first::MIN_LENGTH $(+ $ty::MIN_LENGTH)*;
#[inline(always)]
fn html_len(&self) -> usize {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
$($ty.html_len() +)* $first.html_len()
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
mark_branches: bool,
extra_attrs: Vec<AnyAttribute>
) {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
$first.to_html_with_buf(buf, position, escape, mark_branches, extra_attrs.clone());
$($ty.to_html_with_buf(buf, position, escape, mark_branches, extra_attrs.clone()));*
}
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,
{
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
$first.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position, escape, mark_branches, extra_attrs.clone());
$($ty.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position, escape, mark_branches, extra_attrs.clone()));*
}
fn hydrate<const FROM_SERVER: bool>(self, cursor: &Cursor, position: &PositionState) -> Self::State {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
(
$first.hydrate::<FROM_SERVER>(cursor, position),
$($ty.hydrate::<FROM_SERVER>(cursor, position)),*
)
}
async fn hydrate_async(self, cursor: &Cursor, position: &PositionState) -> Self::State {
#[allow(non_snake_case)]
let ($first, $($ty,)* ) = self;
(
$first.hydrate_async(cursor, position).await,
$($ty.hydrate_async(cursor, position).await),*
)
}
async fn resolve(self) -> Self::AsyncOutput {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
futures::join!(
$first.resolve(),
$($ty.resolve()),*
)
}
fn dry_resolve(&mut self) {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
$first.dry_resolve();
$($ty.dry_resolve());*
}
fn into_owned(self) -> Self::Owned {
#[allow(non_snake_case)]
let ($first, $($ty,)*) = self;
(
$first.into_owned(),
$($ty.into_owned()),*
)
}
}
impl<$first, $($ty),*> ToTemplate for ($first, $($ty,)*)
where
$first: ToTemplate,
$($ty: ToTemplate),*
{
const TEMPLATE: &'static str = str_from_buffer(&const_concat(&[
$first::TEMPLATE, $($ty::TEMPLATE),*
]));
const CLASS: &'static str = str_from_buffer(&const_concat_with_separator(&[
$first::CLASS, $($ty::CLASS),*
], " "));
const STYLE: &'static str = str_from_buffer(&const_concat_with_separator(&[
$first::STYLE, $($ty::STYLE),*
], ";"));
fn to_template(buf: &mut String, class: &mut String, style: &mut String, inner_html: &mut String, position: &mut Position) {
$first ::to_template(buf, class, style, inner_html, position);
$($ty::to_template(buf, class, style, inner_html, position));*;
}
}
impl<$first, $($ty),*> Mountable for ($first, $($ty,)*) where
$first: Mountable,
$($ty: Mountable),*,
{
fn unmount(&mut self) {
#[allow(non_snake_case)] // better macro performance
let ($first, $($ty,)*) = self;
$first.unmount();
$($ty.unmount());*
}
fn mount(
&mut self,
parent: &crate::renderer::types::Element,
marker: Option<&crate::renderer::types::Node>,
) {
#[allow(non_snake_case)] // better macro performance
let ($first, $($ty,)*) = self;
$first.mount(parent, marker);
$($ty.mount(parent, marker));*
}
fn insert_before_this(&self,
child: &mut dyn Mountable,
) -> bool {
#[allow(non_snake_case)] // better macro performance
let ($first, $($ty,)*) = self;
$first.insert_before_this(child)
$(|| $ty.insert_before_this(child))*
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
#[allow(non_snake_case)] // better macro performance
let ($first, $($ty,)*) = self;
$first.elements().into_iter()
$(.chain($ty.elements()))*
.collect()
}
}
impl<$first, $($ty,)*> AddAnyAttr for ($first, $($ty,)*)
where
$first: AddAnyAttr,
$($ty: AddAnyAttr),*,
{
type Output<SomeNewAttr: Attribute> = ($first::Output<SomeNewAttr::Cloneable>, $($ty::Output<SomeNewAttr::Cloneable>,)*);
fn add_any_attr<NewAttr: Attribute>(
self,
attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
let shared = attr.into_cloneable();
#[allow(non_snake_case)] // better macro performance
let ($first, $($ty,)*) = self;
($first.add_any_attr(shared.clone()), $($ty.add_any_attr(shared.clone()),)*)
}
}
};
}
impl_view_for_tuples!(A, B);
impl_view_for_tuples!(A, B, C);
impl_view_for_tuples!(A, B, C, D);
impl_view_for_tuples!(A, B, C, D, E);
impl_view_for_tuples!(A, B, C, D, E, F);
impl_view_for_tuples!(A, B, C, D, E, F, G);
impl_view_for_tuples!(A, B, C, D, E, F, G, H);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
impl_view_for_tuples!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
impl_view_for_tuples!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/view/static_types.rs | tachys/src/view/static_types.rs | use super::{
add_attr::AddAnyAttr, Mountable, Position, PositionState, Render,
RenderHtml, ToTemplate,
};
use crate::{
html::attribute::{
any_attribute::AnyAttribute,
maybe_next_attr_erasure_macros::{
next_attr_combine, next_attr_output_type,
},
Attribute, AttributeKey, AttributeValue, NamedAttributeKey,
NextAttribute,
},
hydration::Cursor,
renderer::{CastFrom, Rndr},
};
use std::marker::PhantomData;
/// An attribute for which both the key and the value are known at compile time,
/// i.e., as `&'static str`s.
#[derive(Debug)]
pub struct StaticAttr<K: AttributeKey, const V: &'static str> {
ty: PhantomData<K>,
}
impl<K: AttributeKey, const V: &'static str> Clone for StaticAttr<K, V> {
fn clone(&self) -> Self {
Self { ty: PhantomData }
}
}
impl<K: AttributeKey, const V: &'static str> PartialEq for StaticAttr<K, V> {
fn eq(&self, _other: &Self) -> bool {
// by definition, two static attrs with same key and same const V are same
true
}
}
/// Creates an [`Attribute`] whose key and value are both known at compile time.
pub fn static_attr<K: AttributeKey, const V: &'static str>() -> StaticAttr<K, V>
{
StaticAttr { ty: PhantomData }
}
impl<K, const V: &'static str> ToTemplate for StaticAttr<K, V>
where
K: AttributeKey,
{
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
_position: &mut Position,
) {
buf.push(' ');
buf.push_str(K::KEY);
buf.push_str("=\"");
buf.push_str(V);
buf.push('"');
}
}
impl<K, const V: &'static str> Attribute for StaticAttr<K, V>
where
K: AttributeKey,
{
const MIN_LENGTH: usize = K::KEY.len() + 3 + V.len(); // K::KEY + ="..." + V
type AsyncOutput = Self;
type State = ();
type Cloneable = Self;
type CloneableOwned = Self;
#[inline(always)]
fn html_len(&self) -> usize {
K::KEY.len() + 3 + V.len()
}
fn to_html(
self,
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
) {
AttributeValue::to_html(V, K::KEY, buf)
}
fn hydrate<const FROM_SERVER: bool>(
self,
_el: &crate::renderer::types::Element,
) -> Self::State {
}
fn build(self, el: &crate::renderer::types::Element) -> Self::State {
Rndr::set_attribute(el, K::KEY, V);
}
fn rebuild(self, _state: &mut Self::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
}
fn keys(&self) -> Vec<NamedAttributeKey> {
vec![NamedAttributeKey::Attribute(K::KEY.into())]
}
}
impl<K, const V: &'static str> NextAttribute for StaticAttr<K, V>
where
K: AttributeKey,
{
next_attr_output_type!(Self, NewAttr);
fn add_any_attr<NewAttr: Attribute>(
self,
new_attr: NewAttr,
) -> Self::Output<NewAttr> {
next_attr_combine!(StaticAttr::<K, V> { ty: PhantomData }, new_attr)
}
}
/// A static string that is known at compile time and can be optimized by including its type in the
/// view tree.
#[derive(Debug, Clone, Copy)]
pub struct Static<const V: &'static str>;
impl<const V: &'static str> PartialEq for Static<V> {
fn eq(&self, _other: &Self) -> bool {
// by definition, two static values of same const V are same
true
}
}
impl<const V: &'static str> AsRef<str> for Static<V> {
fn as_ref(&self) -> &str {
V
}
}
impl<const V: &'static str> Render for Static<V>
where
crate::renderer::types::Text: Mountable,
{
type State = Option<crate::renderer::types::Text>;
fn build(self) -> Self::State {
// a view state has to be returned so it can be mounted
Some(Rndr::create_text_node(V))
}
// This type is specified as static, so no rebuilding is done.
fn rebuild(self, _state: &mut Self::State) {}
}
impl<const V: &'static str> RenderHtml for Static<V> {
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = V.len();
fn dry_resolve(&mut self) {}
// this won't actually compile because if a weird interaction because the const &'static str and
// the RPITIT, so we just refine it to a concrete future type; this will never change in any
// case
#[allow(refining_impl_trait)]
fn resolve(self) -> std::future::Ready<Self> {
std::future::ready(self)
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
escape: bool,
_mark_branches: bool,
_extra_attrs: Vec<AnyAttribute>,
) {
// add a comment node to separate from previous sibling, if any
if matches!(position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
if V.is_empty() && escape {
buf.push(' ');
} else if escape {
let escaped = html_escape::encode_text(V);
buf.push_str(&escaped);
} else {
buf.push_str(V);
}
*position = Position::NextChildAfterText;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
if position.get() == Position::FirstChild {
cursor.child();
} else {
cursor.sibling();
}
// separating placeholder marker comes before text node
if matches!(position.get(), Position::NextChildAfterText) {
cursor.sibling();
}
let node = cursor.current();
let node = crate::renderer::types::Text::cast_from(node.clone())
.unwrap_or_else(|| {
crate::hydration::failed_to_cast_text_node(node)
});
position.set(Position::NextChildAfterText);
Some(node)
}
fn into_owned(self) -> Self::Owned {
self
}
}
impl<const V: &'static str> AddAnyAttr for Static<V> {
type Output<NewAttr: Attribute> = Static<V>;
fn add_any_attr<NewAttr: Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
// inline helper function to assist the compiler with type inference
#[inline(always)]
const fn create_static<const S: &'static str, A: Attribute>(
) -> <Static<S> as AddAnyAttr>::Output<A> {
Static
}
// call the helper function with the current const value and new attribute type
create_static::<V, NewAttr>()
}
}
impl<const V: &'static str> ToTemplate for Static<V> {
const TEMPLATE: &'static str = V;
fn to_template(
buf: &mut String,
_class: &mut String,
_style: &mut String,
_inner_html: &mut String,
position: &mut Position,
) {
if matches!(*position, Position::NextChildAfterText) {
buf.push_str("<!>")
}
buf.push_str(V);
*position = Position::NextChildAfterText;
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/tachys/src/svg/mod.rs | tachys/src/svg/mod.rs | use crate::{
html::{
attribute::{any_attribute::AnyAttribute, Attribute},
element::{ElementType, ElementWithChildren, HtmlElement},
},
hydration::Cursor,
prelude::{AddAnyAttr, Mountable},
renderer::{
dom::{Element, Node},
CastFrom, Rndr,
},
view::{Position, PositionState, Render, RenderHtml},
};
use std::{borrow::Cow, fmt::Debug};
macro_rules! svg_elements {
($($tag:ident [$($attr:ty),*]),* $(,)?) => {
paste::paste! {
$(
/// An SVG element.
// `tag()` function
#[allow(non_snake_case)]
#[track_caller]
pub fn $tag() -> HtmlElement<[<$tag:camel>], (), ()>
where
{
HtmlElement {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
tag: [<$tag:camel>],
attributes: (),
children: (),
}
}
/// An SVG element.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct [<$tag:camel>];
impl<At, Ch> HtmlElement<[<$tag:camel>], At, Ch>
where
At: Attribute,
Ch: Render,
{
$(
pub fn $attr<V>(self, value: V) -> HtmlElement <
[<$tag:camel>],
<At as $crate::html::attribute::NextAttribute<Attr<$crate::html::attribute::[<$attr:camel>], V>>>::Output,
Ch
>
where
V: AttributeValue,
At: $crate::html::attribute::NextAttribute<Attr<$crate::html::attribute::[<$attr:camel>], V>>,
<At as $crate::html::attribute::NextAttribute<Attr<$crate::html::attribute::[<$attr:camel>], V>>>::Output: Attribute,
{
let HtmlElement { tag, children, attributes,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at
} = self;
HtmlElement {
tag,
children,
attributes: attributes.add_any_attr($crate::html::attribute::$attr(value)),
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at
}
}
)*
}
impl ElementType for [<$tag:camel>] {
type Output = web_sys::SvgElement;
const TAG: &'static str = stringify!($tag);
const SELF_CLOSING: bool = false;
const ESCAPE_CHILDREN: bool = true;
const NAMESPACE: Option<&'static str> = Some("http://www.w3.org/2000/svg");
#[inline(always)]
fn tag(&self) -> &str {
Self::TAG
}
}
impl ElementWithChildren for [<$tag:camel>] {}
)*
}
}
}
svg_elements![
a [],
animate [],
animateMotion [],
animateTransform [],
circle [],
clipPath [],
defs [],
desc [],
discard [],
ellipse [],
feBlend [],
feColorMatrix [],
feComponentTransfer [],
feComposite [],
feConvolveMatrix [],
feDiffuseLighting [],
feDisplacementMap [],
feDistantLight [],
feDropShadow [],
feFlood [],
feFuncA [],
feFuncB [],
feFuncG [],
feFuncR [],
feGaussianBlur [],
feImage [],
feMerge [],
feMergeNode [],
feMorphology [],
feOffset [],
fePointLight [],
feSpecularLighting [],
feSpotLight [],
feTile [],
feTurbulence [],
filter [],
foreignObject [],
g [],
hatch [],
hatchpath [],
image [],
line [],
linearGradient [],
marker [],
mask [],
metadata [],
mpath [],
path [],
pattern [],
polygon [],
polyline [],
radialGradient [],
rect [],
script [],
set [],
stop [],
style [],
svg [],
switch [],
symbol [],
text [],
textPath [],
title [],
tspan [],
view [],
];
/// An SVG element.
#[allow(non_snake_case)]
#[track_caller]
pub fn r#use() -> HtmlElement<Use, (), ()>
where {
HtmlElement {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: std::panic::Location::caller(),
tag: Use,
attributes: (),
children: (),
}
}
/// An SVG element.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Use;
impl ElementType for Use {
type Output = web_sys::SvgElement;
const TAG: &'static str = "use";
const SELF_CLOSING: bool = false;
const ESCAPE_CHILDREN: bool = true;
const NAMESPACE: Option<&'static str> = Some("http://www.w3.org/2000/svg");
#[inline(always)]
fn tag(&self) -> &str {
Self::TAG
}
}
impl ElementWithChildren for Use {}
/// An element that contains no interactivity, and whose contents can be known at compile time.
pub struct InertElement {
html: Cow<'static, str>,
}
impl InertElement {
/// Creates a new inert svg element.
pub fn new(html: impl Into<Cow<'static, str>>) -> Self {
Self { html: html.into() }
}
}
/// Retained view state for [`InertElement`].
pub struct InertElementState(Cow<'static, str>, Element);
impl Mountable for InertElementState {
fn unmount(&mut self) {
self.1.unmount();
}
fn mount(&mut self, parent: &Element, marker: Option<&Node>) {
self.1.mount(parent, marker)
}
fn insert_before_this(&self, child: &mut dyn Mountable) -> bool {
self.1.insert_before_this(child)
}
fn elements(&self) -> Vec<crate::renderer::types::Element> {
vec![self.1.clone()]
}
}
impl Render for InertElement {
type State = InertElementState;
fn build(self) -> Self::State {
let el = Rndr::create_svg_element_from_html(self.html.clone());
InertElementState(self.html, el)
}
fn rebuild(self, state: &mut Self::State) {
let InertElementState(prev, el) = state;
if &self.html != prev {
let mut new_el =
Rndr::create_svg_element_from_html(self.html.clone());
el.insert_before_this(&mut new_el);
el.unmount();
*el = new_el;
*prev = self.html;
}
}
}
impl AddAnyAttr for InertElement {
type Output<SomeNewAttr: Attribute> = Self;
fn add_any_attr<NewAttr: Attribute>(
self,
_attr: NewAttr,
) -> Self::Output<NewAttr>
where
Self::Output<NewAttr>: RenderHtml,
{
panic!(
"InertElement does not support adding attributes. It should only \
be used as a child, and not returned at the top level."
)
}
}
impl RenderHtml for InertElement {
type AsyncOutput = Self;
type Owned = Self;
const MIN_LENGTH: usize = 0;
fn html_len(&self) -> usize {
self.html.len()
}
fn dry_resolve(&mut self) {}
async fn resolve(self) -> Self {
self
}
fn to_html_with_buf(
self,
buf: &mut String,
position: &mut Position,
_escape: bool,
_mark_branches: bool,
_extra_attrs: Vec<AnyAttribute>,
) {
buf.push_str(&self.html);
*position = Position::NextChild;
}
fn hydrate<const FROM_SERVER: bool>(
self,
cursor: &Cursor,
position: &PositionState,
) -> Self::State {
let curr_position = position.get();
if curr_position == Position::FirstChild {
cursor.child();
} else if curr_position != Position::Current {
cursor.sibling();
}
let el = crate::renderer::types::Element::cast_from(cursor.current())
.unwrap();
position.set(Position::NextChild);
InertElementState(self.html, el)
}
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/router_macro/src/lib.rs | router_macro/src/lib.rs | //! A macro to make path definitions easier with [`leptos_router`].
//!
//! [`leptos_router`]: https://docs.rs/leptos_router/latest/leptos_router/components/fn.Route.html
#![deny(missing_docs)]
use proc_macro::{TokenStream, TokenTree};
use proc_macro2::Span;
use proc_macro_error2::{abort, proc_macro_error, set_dummy};
use quote::{format_ident, quote, ToTokens};
use syn::{
spanned::Spanned, FnArg, Ident, ImplItem, ItemImpl, Path, Type, TypePath,
};
const RFC3986_UNRESERVED: [char; 4] = ['-', '.', '_', '~'];
const RFC3986_PCHAR_OTHER: [char; 1] = ['@'];
/// Constructs a path for use in a [`Route`] definition.
///
/// Note that this is an optional convenience. Manually defining route segments
/// is equivalent.
///
/// # Examples
///
/// ```rust
/// use leptos_router::{
/// path, OptionalParamSegment, ParamSegment, StaticSegment,
/// WildcardSegment,
/// };
///
/// let path = path!("/foo/:bar/:baz?/*any");
/// let output = (
/// StaticSegment("foo"),
/// ParamSegment("bar"),
/// OptionalParamSegment("baz"),
/// WildcardSegment("any"),
/// );
///
/// assert_eq!(path, output);
/// ```
/// [`Route`]: https://docs.rs/leptos_router/latest/leptos_router/components/fn.Route.html
#[proc_macro_error2::proc_macro_error]
#[proc_macro]
pub fn path(tokens: TokenStream) -> TokenStream {
let mut parser = SegmentParser::new(tokens);
parser.parse_all();
let segments = Segments(parser.segments);
segments.into_token_stream().into()
}
#[derive(Debug, PartialEq)]
struct Segments(pub Vec<Segment>);
#[derive(Debug, PartialEq)]
enum Segment {
Static(String),
Param(String),
OptionalParam(String),
Wildcard(String),
}
struct SegmentParser {
input: proc_macro::token_stream::IntoIter,
segments: Vec<Segment>,
}
impl SegmentParser {
pub fn new(input: TokenStream) -> Self {
Self {
input: input.into_iter(),
segments: Vec::new(),
}
}
}
impl SegmentParser {
pub fn parse_all(&mut self) {
for input in self.input.by_ref() {
match input {
TokenTree::Literal(lit) => {
let lit = lit.to_string();
if lit.contains("//") {
abort!(
proc_macro2::Span::call_site(),
"Consecutive '/' is not allowed"
);
}
Self::parse_str(
&mut self.segments,
lit.trim_start_matches(['"', '/'])
.trim_end_matches(['"', '/']),
);
if lit.ends_with(r#"/""#) && lit != r#""/""# {
self.segments.push(Segment::Static("/".to_string()));
}
}
TokenTree::Group(_) => unimplemented!(),
TokenTree::Ident(_) => unimplemented!(),
TokenTree::Punct(_) => unimplemented!(),
}
}
}
pub fn parse_str(segments: &mut Vec<Segment>, current_str: &str) {
if ["", "*"].contains(¤t_str) {
return;
}
for segment in current_str.split('/') {
if let Some(segment) = segment.strip_prefix(':') {
if let Some(segment) = segment.strip_suffix('?') {
segments.push(Segment::OptionalParam(segment.to_string()));
} else {
segments.push(Segment::Param(segment.to_string()));
}
} else if let Some(segment) = segment.strip_prefix('*') {
segments.push(Segment::Wildcard(segment.to_string()));
} else {
segments.push(Segment::Static(segment.to_string()));
}
}
}
}
impl Segment {
fn is_valid(segment: &str) -> bool {
segment == "/"
|| segment.chars().all(|c| {
c.is_ascii_digit()
|| c.is_ascii_lowercase()
|| c.is_ascii_uppercase()
|| RFC3986_UNRESERVED.contains(&c)
|| RFC3986_PCHAR_OTHER.contains(&c)
})
}
fn ensure_valid(&self) {
match self {
Self::Wildcard(s) if !Self::is_valid(s) => {
abort!(Span::call_site(), "Invalid wildcard segment: {}", s)
}
Self::Static(s) if !Self::is_valid(s) => {
abort!(Span::call_site(), "Invalid static segment: {}", s)
}
Self::Param(s) if !Self::is_valid(s) => {
abort!(Span::call_site(), "Invalid param segment: {}", s)
}
_ => (),
}
}
}
impl Segments {
fn ensure_valid(&self) {
if let Some((_last, segments)) = self.0.split_last() {
if let Some(Segment::Wildcard(s)) =
segments.iter().find(|s| matches!(s, Segment::Wildcard(_)))
{
abort!(Span::call_site(), "Wildcard must be at end: {}", s)
}
}
}
}
impl ToTokens for Segment {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.ensure_valid();
match self {
Segment::Wildcard(s) => {
tokens.extend(quote! { leptos_router::WildcardSegment(#s) });
}
Segment::Static(s) => {
tokens.extend(quote! { leptos_router::StaticSegment(#s) });
}
Segment::Param(p) => {
tokens.extend(quote! { leptos_router::ParamSegment(#p) });
}
Segment::OptionalParam(p) => {
tokens
.extend(quote! { leptos_router::OptionalParamSegment(#p) });
}
}
}
}
impl ToTokens for Segments {
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.ensure_valid();
match self.0.as_slice() {
[] => tokens.extend(quote! { () }),
[segment] => tokens.extend(quote! { (#segment,) }),
segments => tokens.extend(quote! { (#(#segments),*) }),
}
}
}
/// When added to an [`impl LazyRoute`] implementation block, this will automatically
/// add a [`lazy`] annotation to the `view` method, which will cause the code for the view
/// to lazy-load concurrently with the `data` being loaded for the route.
///
/// ```rust
/// use leptos::prelude::*;
/// use leptos_router::{lazy_route, LazyRoute};
///
/// // the route definition
/// #[derive(Debug)]
/// struct BlogListingRoute {
/// titles: Resource<Vec<String>>
/// }
///
/// #[lazy_route]
/// impl LazyRoute for BlogListingRoute {
/// fn data() -> Self {
/// Self {
/// titles: Resource::new(|| (), |_| async {
/// vec![/* todo: load blog posts */]
/// })
/// }
/// }
///
/// // this function will be lazy-loaded, concurrently with data()
/// fn view(this: Self) -> AnyView {
/// let BlogListingRoute { titles } = this;
///
/// // ... now you can use the `posts` resource with Suspense, etc.,
/// // and return AnyView by calling .into_any() on a view
/// # ().into_any()
/// }
/// }
/// ```
///
/// [`impl LazyRoute`]: https://docs.rs/leptos_router/latest/leptos_router/trait.LazyRoute.html
/// [`lazy`]: https://docs.rs/leptos_macro/latest/leptos_macro/macro.lazy.html
#[proc_macro_attribute]
#[proc_macro_error]
pub fn lazy_route(
args: proc_macro::TokenStream,
s: TokenStream,
) -> TokenStream {
lazy_route_impl(args, s)
}
fn lazy_route_impl(
_args: proc_macro::TokenStream,
s: TokenStream,
) -> TokenStream {
set_dummy(s.clone().into());
let mut im = syn::parse::<ItemImpl>(s.clone()).unwrap_or_else(|e| {
abort!(e.span(), "`lazy_route` can only be used on an `impl` block")
});
if im.trait_.is_none() {
abort!(
im.span(),
"`lazy_route` can only be used on an `impl LazyRoute for ...` \
block"
)
}
let self_ty = im.self_ty.clone();
let ty_name_to_snake = match &*self_ty {
Type::Path(TypePath {
path: Path { segments, .. },
..
}) => segments.last().unwrap().ident.to_string(),
_ => abort!(self_ty.span(), "only path types are supported"),
};
let lazy_view_ident =
Ident::new(&format!("__{ty_name_to_snake}_View"), im.self_ty.span());
let preload_ident = format_ident!("__preload_{lazy_view_ident}");
im.items.push(
syn::parse::<ImplItem>(
quote! {
async fn preload() {
// TODO for 0.9 this is not precise
// we don't split routes for wasm32 ssr
// but we don't require a `hydrate`/`csr` feature on leptos_router
#[cfg(target_arch = "wasm32")]
#preload_ident().await;
}
}
.into(),
)
.unwrap_or_else(|e| {
abort!(e.span(), "could not parse preload item impl")
}),
);
let item = im.items.iter_mut().find_map(|item| match item {
ImplItem::Fn(inner) => {
if inner.sig.ident.to_string().as_str() == "view" {
Some(inner)
} else {
None
}
}
_ => None,
});
match item {
None => s,
Some(fun) => {
if let Some(a) = fun.sig.asyncness {
abort!(a.span(), "`view` method should not be async")
}
fun.sig.asyncness = Some(Default::default());
let first_arg = fun.sig.inputs.first().unwrap_or_else(|| {
abort!(fun.sig.span(), "must have an argument")
});
let FnArg::Typed(first_arg) = first_arg else {
abort!(
first_arg.span(),
"this must be a typed argument like `this: Self`"
)
};
let first_arg_pat = &*first_arg.pat;
let body = std::mem::replace(
&mut fun.block,
syn::parse(
quote! {
{
#lazy_view_ident(#first_arg_pat).await
}
}
.into(),
)
.unwrap(),
);
quote! {
#[allow(non_snake_case)]
#[::leptos::lazy]
fn #lazy_view_ident(#first_arg_pat: #self_ty) -> ::leptos::prelude::AnyView {
#body
}
#im
}.into()
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/router_macro/tests/path.rs | router_macro/tests/path.rs | use leptos_router::{
OptionalParamSegment, ParamSegment, StaticSegment, WildcardSegment,
};
use leptos_router_macro::path;
#[test]
fn parses_empty_string() {
let output = path!("");
assert!(output.eq(&()));
}
#[test]
fn parses_single_slash() {
let output = path!("/");
assert!(output.eq(&()));
}
#[test]
fn parses_single_asterisk() {
let output = path!("*");
assert!(output.eq(&()));
}
#[test]
fn parses_slash_asterisk() {
let output = path!("/*");
assert!(output.eq(&()));
}
#[test]
fn parses_asterisk_any() {
let output = path!("/foo/:bar/*any");
assert_eq!(
output,
(
StaticSegment("foo"),
ParamSegment("bar"),
WildcardSegment("any")
)
);
}
#[test]
fn parses_hyphen() {
let output = path!("/foo/bar-baz");
assert_eq!(output, (StaticSegment("foo"), StaticSegment("bar-baz")));
}
#[test]
fn parses_rfc3976_unreserved() {
let output = path!("/-._~");
assert_eq!(output, (StaticSegment("-._~"),));
}
#[test]
fn parses_rfc3976_pchar_other() {
let output = path!("/@");
assert_eq!(output, (StaticSegment("@"),));
}
#[test]
fn parses_no_slashes() {
let output = path!("home");
assert_eq!(output, (StaticSegment("home"),));
}
#[test]
fn parses_no_leading_slash() {
let output = path!("home");
assert_eq!(output, (StaticSegment("home"),));
}
#[test]
fn parses_trailing_slash() {
let output = path!("/home/");
assert_eq!(output, (StaticSegment("home"), StaticSegment("/")));
}
#[test]
fn parses_single_static() {
let output = path!("/home");
assert_eq!(output, (StaticSegment("home"),));
}
#[test]
fn parses_single_param() {
let output = path!("/:id");
assert_eq!(output, (ParamSegment("id"),));
}
#[test]
fn parses_optional_param() {
let output = path!("/:id?");
assert_eq!(output, (OptionalParamSegment("id"),));
}
#[test]
fn parses_static_and_param() {
let output = path!("/home/:id");
assert_eq!(output, (StaticSegment("home"), ParamSegment("id"),));
}
#[test]
fn parses_mixed_segment_types() {
let output = path!("/foo/:bar/*baz");
assert_eq!(
output,
(
StaticSegment("foo"),
ParamSegment("bar"),
WildcardSegment("baz")
)
);
}
#[test]
fn parses_trailing_slash_after_param() {
let output = path!("/foo/:bar/");
assert_eq!(
output,
(
StaticSegment("foo"),
ParamSegment("bar"),
StaticSegment("/")
)
);
}
#[test]
fn parses_consecutive_static() {
let output = path!("/foo/bar/baz");
assert_eq!(
output,
(
StaticSegment("foo"),
StaticSegment("bar"),
StaticSegment("baz")
)
);
}
#[test]
fn parses_consecutive_param() {
let output = path!("/:foo/:bar/:baz");
assert_eq!(
output,
(
ParamSegment("foo"),
ParamSegment("bar"),
ParamSegment("baz")
)
);
}
#[test]
fn parses_consecutive_optional_param() {
let output = path!("/:foo?/:bar?/:baz?");
assert_eq!(
output,
(
OptionalParamSegment("foo"),
OptionalParamSegment("bar"),
OptionalParamSegment("baz")
)
);
}
#[test]
fn parses_complex() {
let output = path!("/home/:id/foo/:bar/:baz?/*any");
assert_eq!(
output,
(
StaticSegment("home"),
ParamSegment("id"),
StaticSegment("foo"),
ParamSegment("bar"),
OptionalParamSegment("baz"),
WildcardSegment("any"),
)
);
}
// #[test]
// fn deny_consecutive_slashes() {
// let _ = path!("/////foo///bar/////baz/");
// }
//
// #[test]
// fn deny_invalid_segment() {
// let _ = path!("/foo/^/");
// }
//
// #[test]
// fn deny_non_trailing_wildcard_segment() {
// let _ = path!("/home/*any/end");
// }
//
// #[test]
// fn deny_invalid_wildcard() {
// let _ = path!("/home/any*");
// }
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/hydration_context/src/lib.rs | hydration_context/src/lib.rs | //! Isomorphic web applications that run on the server to render HTML, then add interactivity in
//! the client, need to accomplish two tasks:
//! 1. Send HTML from the server, so that the client can "hydrate" it in the browser by adding
//! event listeners and setting up other interactivity.
//! 2. Send data that was loaded on the server to the client, so that the client "hydrates" with
//! the same data with which the server rendered HTML.
//!
//! This crate helps with the second part of this process. It provides a [`SharedContext`] type
//! that allows you to store data on the server, and then extract the same data in the client.
#![deny(missing_docs)]
#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(feature = "browser")]
#[cfg_attr(docsrs, doc(cfg(feature = "browser")))]
mod csr;
#[cfg(feature = "browser")]
#[cfg_attr(docsrs, doc(cfg(feature = "browser")))]
mod hydrate;
mod ssr;
#[cfg(feature = "browser")]
pub use csr::*;
use futures::Stream;
#[cfg(feature = "browser")]
pub use hydrate::*;
use serde::{Deserialize, Serialize};
pub use ssr::*;
use std::{fmt::Debug, future::Future, pin::Pin};
use throw_error::{Error, ErrorId};
/// Type alias for a boxed [`Future`].
pub type PinnedFuture<T> = Pin<Box<dyn Future<Output = T> + Send + Sync>>;
/// Type alias for a boxed [`Future`] that is `!Send`.
pub type PinnedLocalFuture<T> = Pin<Box<dyn Future<Output = T>>>;
/// Type alias for a boxed [`Stream`].
pub type PinnedStream<T> = Pin<Box<dyn Stream<Item = T> + Send + Sync>>;
#[derive(
Clone, Debug, PartialEq, Eq, Hash, Default, Deserialize, Serialize,
)]
#[serde(transparent)]
/// A unique identifier for a piece of data that will be serialized
/// from the server to the client.
pub struct SerializedDataId(usize);
impl SerializedDataId {
/// Create a new instance of [`SerializedDataId`].
pub fn new(id: usize) -> Self {
SerializedDataId(id)
}
/// Consume into the inner usize identifier.
pub fn into_inner(self) -> usize {
self.0
}
}
impl From<SerializedDataId> for ErrorId {
fn from(value: SerializedDataId) -> Self {
value.0.into()
}
}
/// Information that will be shared between the server and the client.
pub trait SharedContext: Debug {
/// Whether the application is running in the browser.
fn is_browser(&self) -> bool;
/// Returns the next in a series of IDs that is unique to a particular request and response.
///
/// This should not be used as a global unique ID mechanism. It is specific to the process
/// of serializing and deserializing data from the server to the browser as part of an HTTP
/// response.
fn next_id(&self) -> SerializedDataId;
/// The given [`Future`] should resolve with some data that can be serialized
/// from the server to the client. This will be polled as part of the process of
/// building the HTTP response, *not* when it is first created.
///
/// In browser implementations, this should be a no-op.
fn write_async(&self, id: SerializedDataId, fut: PinnedFuture<String>);
/// Reads the current value of some data from the shared context, if it has been
/// sent from the server. This returns the serialized data as a `String` that should
/// be deserialized.
///
/// On the server and in client-side rendered implementations, this should
/// always return [`None`].
fn read_data(&self, id: &SerializedDataId) -> Option<String>;
/// Returns a [`Future`] that resolves with a `String` that should
/// be deserialized once the given piece of server data has resolved.
///
/// On the server and in client-side rendered implementations, this should
/// return a [`Future`] that is immediately ready with [`None`].
fn await_data(&self, id: &SerializedDataId) -> Option<String>;
/// Returns some [`Stream`] of HTML that contains JavaScript `<script>` tags defining
/// all values being serialized from the server to the client, with their serialized values
/// and any boilerplate needed to notify a running application that they exist; or `None`.
///
/// In browser implementations, this return `None`.
fn pending_data(&self) -> Option<PinnedStream<String>>;
/// Whether the page is currently being hydrated.
///
/// Should always be `false` on the server or when client-rendering, including after the
/// initial hydration in the client.
fn during_hydration(&self) -> bool;
/// Tells the shared context that the hydration process is complete.
fn hydration_complete(&self);
/// Returns `true` if you are currently in a part of the application tree that should be
/// hydrated.
///
/// For example, in an app with "islands," this should be `true` inside islands and
/// false elsewhere.
fn get_is_hydrating(&self) -> bool;
/// Sets whether you are currently in a part of the application tree that should be hydrated.
///
/// For example, in an app with "islands," this should be `true` inside islands and
/// false elsewhere.
fn set_is_hydrating(&self, is_hydrating: bool);
/// Returns all errors that have been registered, removing them from the list.
fn take_errors(&self) -> Vec<(SerializedDataId, ErrorId, Error)>;
/// Returns the set of errors that have been registered with a particular boundary.
fn errors(&self, boundary_id: &SerializedDataId) -> Vec<(ErrorId, Error)>;
/// "Seals" an error boundary, preventing further errors from being registered for it.
///
/// This can be used in streaming SSR scenarios in which the final state of the error boundary
/// can only be known after the initial state is hydrated.
fn seal_errors(&self, boundary_id: &SerializedDataId);
/// Registers an error with the context to be shared from server to client.
fn register_error(
&self,
error_boundary: SerializedDataId,
error_id: ErrorId,
error: Error,
);
/// Adds a `Future` to the set of “blocking resources” that should prevent the server’s
/// response stream from beginning until all are resolved. The `Future` returned by
/// blocking resources will not resolve until every `Future` added by this method
/// has resolved.
///
/// In browser implementations, this should be a no-op.
fn defer_stream(&self, wait_for: PinnedFuture<()>);
/// Returns a `Future` that will resolve when every `Future` added via
/// [`defer_stream`](Self::defer_stream) has resolved.
///
/// In browser implementations, this should be a no-op.
fn await_deferred(&self) -> Option<PinnedFuture<()>>;
/// Tells the client that this chunk is being sent from the server before all its data have
/// loaded, and it may be in a fallback state.
fn set_incomplete_chunk(&self, id: SerializedDataId);
/// Checks whether this chunk is being sent from the server before all its data have loaded.
fn get_incomplete_chunk(&self, id: &SerializedDataId) -> bool;
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/hydration_context/src/hydrate.rs | hydration_context/src/hydrate.rs | // #[wasm_bindgen(thread_local)] is deprecated in wasm-bindgen 0.2.96
// but the replacement is also only shipped in that version
// as a result, we'll just allow deprecated for now
#![allow(deprecated)]
use super::{SerializedDataId, SharedContext};
use crate::{PinnedFuture, PinnedStream};
use core::fmt::Debug;
use js_sys::Array;
use std::{
fmt::Display,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
LazyLock,
},
};
use throw_error::{Error, ErrorId};
use wasm_bindgen::{prelude::wasm_bindgen, JsCast};
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(thread_local)]
static __RESOLVED_RESOURCES: Array;
#[wasm_bindgen(thread_local)]
static __SERIALIZED_ERRORS: Array;
#[wasm_bindgen(thread_local)]
static __INCOMPLETE_CHUNKS: Array;
}
fn serialized_errors() -> Vec<(SerializedDataId, ErrorId, Error)> {
__SERIALIZED_ERRORS.with(|s| {
s.iter()
.flat_map(|value| {
value.dyn_ref::<Array>().map(|value| {
let error_boundary_id =
value.get(0).as_f64().unwrap() as usize;
let error_id = value.get(1).as_f64().unwrap() as usize;
let value = value
.get(2)
.as_string()
.expect("Expected a [number, string] tuple");
(
SerializedDataId(error_boundary_id),
ErrorId::from(error_id),
Error::from(SerializedError(value)),
)
})
})
.collect()
})
}
fn incomplete_chunks() -> Vec<SerializedDataId> {
__INCOMPLETE_CHUNKS.with(|i| {
i.iter()
.map(|value| {
let id = value.as_f64().unwrap() as usize;
SerializedDataId(id)
})
.collect()
})
}
/// An error that has been serialized across the network boundary.
#[derive(Debug, Clone)]
struct SerializedError(String);
impl Display for SerializedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
}
}
impl std::error::Error for SerializedError {}
#[derive(Default)]
/// The shared context that should be used in the browser while hydrating.
pub struct HydrateSharedContext {
id: AtomicUsize,
is_hydrating: AtomicBool,
during_hydration: AtomicBool,
errors: LazyLock<Vec<(SerializedDataId, ErrorId, Error)>>,
incomplete: LazyLock<Vec<SerializedDataId>>,
}
impl HydrateSharedContext {
/// Creates a new shared context for hydration in the browser.
pub fn new() -> Self {
Self {
id: AtomicUsize::new(0),
is_hydrating: AtomicBool::new(true),
during_hydration: AtomicBool::new(true),
errors: LazyLock::new(serialized_errors),
incomplete: LazyLock::new(incomplete_chunks),
}
}
/// Creates a new shared context for hydration in the browser.
///
/// This defaults to a mode in which the app is not hydrated, but allows you to opt into
/// hydration for certain portions using [`SharedContext::set_is_hydrating`].
pub fn new_islands() -> Self {
Self {
id: AtomicUsize::new(0),
is_hydrating: AtomicBool::new(false),
during_hydration: AtomicBool::new(true),
errors: LazyLock::new(serialized_errors),
incomplete: LazyLock::new(incomplete_chunks),
}
}
}
impl Debug for HydrateSharedContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HydrateSharedContext").finish()
}
}
impl SharedContext for HydrateSharedContext {
fn is_browser(&self) -> bool {
true
}
fn next_id(&self) -> SerializedDataId {
let id = self.id.fetch_add(1, Ordering::Relaxed);
SerializedDataId(id)
}
fn write_async(&self, _id: SerializedDataId, _fut: PinnedFuture<String>) {}
fn read_data(&self, id: &SerializedDataId) -> Option<String> {
__RESOLVED_RESOURCES.with(|r| r.get(id.0 as u32).as_string())
}
fn await_data(&self, _id: &SerializedDataId) -> Option<String> {
todo!()
}
fn pending_data(&self) -> Option<PinnedStream<String>> {
None
}
fn during_hydration(&self) -> bool {
self.during_hydration.load(Ordering::Relaxed)
}
fn hydration_complete(&self) {
self.during_hydration.store(false, Ordering::Relaxed)
}
fn get_is_hydrating(&self) -> bool {
self.is_hydrating.load(Ordering::Relaxed)
}
fn set_is_hydrating(&self, is_hydrating: bool) {
self.is_hydrating.store(is_hydrating, Ordering::Relaxed)
}
fn errors(&self, boundary_id: &SerializedDataId) -> Vec<(ErrorId, Error)> {
self.errors
.iter()
.filter_map(|(boundary, id, error)| {
if boundary == boundary_id {
Some((id.clone(), error.clone()))
} else {
None
}
})
.collect()
}
#[inline(always)]
fn register_error(
&self,
_error_boundary: SerializedDataId,
_error_id: ErrorId,
_error: Error,
) {
}
#[inline(always)]
fn seal_errors(&self, _boundary_id: &SerializedDataId) {}
fn take_errors(&self) -> Vec<(SerializedDataId, ErrorId, Error)> {
self.errors.clone()
}
#[inline(always)]
fn defer_stream(&self, _wait_for: PinnedFuture<()>) {}
#[inline(always)]
fn await_deferred(&self) -> Option<PinnedFuture<()>> {
None
}
#[inline(always)]
fn set_incomplete_chunk(&self, _id: SerializedDataId) {}
fn get_incomplete_chunk(&self, id: &SerializedDataId) -> bool {
self.incomplete.iter().any(|entry| entry == id)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/hydration_context/src/ssr.rs | hydration_context/src/ssr.rs | use super::{SerializedDataId, SharedContext};
use crate::{PinnedFuture, PinnedStream};
use futures::{
future::join_all,
stream::{self, once},
Stream, StreamExt,
};
use or_poisoned::OrPoisoned;
use std::{
collections::HashSet,
fmt::{Debug, Write},
mem,
pin::Pin,
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc, Mutex, RwLock,
},
task::{Context, Poll},
};
use throw_error::{Error, ErrorId};
type AsyncDataBuf = Arc<RwLock<Vec<(SerializedDataId, PinnedFuture<String>)>>>;
type ErrorBuf = Arc<RwLock<Vec<(SerializedDataId, ErrorId, Error)>>>;
type SealedErrors = Arc<RwLock<HashSet<SerializedDataId>>>;
#[derive(Default)]
/// The shared context that should be used on the server side.
pub struct SsrSharedContext {
id: AtomicUsize,
non_hydration_id: AtomicUsize,
is_hydrating: AtomicBool,
sync_buf: RwLock<Vec<ResolvedData>>,
async_buf: AsyncDataBuf,
errors: ErrorBuf,
sealed_error_boundaries: SealedErrors,
deferred: Mutex<Vec<PinnedFuture<()>>>,
incomplete: Arc<Mutex<Vec<SerializedDataId>>>,
}
impl SsrSharedContext {
/// Creates a new shared context for rendering HTML on the server.
pub fn new() -> Self {
Self {
is_hydrating: AtomicBool::new(true),
non_hydration_id: AtomicUsize::new(usize::MAX),
..Default::default()
}
}
/// Creates a new shared context for rendering HTML on the server in "islands" mode.
///
/// This defaults to a mode in which the app is not hydrated, but allows you to opt into
/// hydration for certain portions using [`SharedContext::set_is_hydrating`].
pub fn new_islands() -> Self {
Self {
is_hydrating: AtomicBool::new(false),
non_hydration_id: AtomicUsize::new(usize::MAX),
..Default::default()
}
}
/// Consume the data buffers, awaiting all async resources,
/// returning both sync and async buffers.
/// Useful to implement custom hydration contexts.
///
/// WARNING: this will clear the internal buffers, it should only be called once.
/// A second call would return an empty `vec![]`.
pub async fn consume_buffers(&self) -> Vec<(SerializedDataId, String)> {
let sync_data = mem::take(&mut *self.sync_buf.write().or_poisoned());
let async_data = mem::take(&mut *self.async_buf.write().or_poisoned());
let mut all_data = Vec::new();
for resolved in sync_data {
all_data.push((resolved.0, resolved.1));
}
for (id, fut) in async_data {
let data = fut.await;
all_data.push((id, data));
}
all_data
}
}
impl Debug for SsrSharedContext {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SsrSharedContext")
.field("id", &self.id)
.field("is_hydrating", &self.is_hydrating)
.field("sync_buf", &self.sync_buf)
.field("async_buf", &self.async_buf.read().or_poisoned().len())
.finish()
}
}
impl SharedContext for SsrSharedContext {
fn is_browser(&self) -> bool {
false
}
#[track_caller]
fn next_id(&self) -> SerializedDataId {
let id = if self.get_is_hydrating() {
self.id.fetch_add(1, Ordering::Relaxed)
} else {
self.non_hydration_id.fetch_sub(1, Ordering::Relaxed)
};
SerializedDataId(id)
}
fn write_async(&self, id: SerializedDataId, fut: PinnedFuture<String>) {
self.async_buf.write().or_poisoned().push((id, fut))
}
fn read_data(&self, _id: &SerializedDataId) -> Option<String> {
None
}
fn await_data(&self, _id: &SerializedDataId) -> Option<String> {
None
}
fn get_is_hydrating(&self) -> bool {
self.is_hydrating.load(Ordering::SeqCst)
}
fn set_is_hydrating(&self, is_hydrating: bool) {
self.is_hydrating.store(is_hydrating, Ordering::SeqCst)
}
fn errors(&self, boundary_id: &SerializedDataId) -> Vec<(ErrorId, Error)> {
self.errors
.read()
.or_poisoned()
.iter()
.filter_map(|(boundary, id, error)| {
if boundary == boundary_id {
Some((id.clone(), error.clone()))
} else {
None
}
})
.collect()
}
fn register_error(
&self,
error_boundary_id: SerializedDataId,
error_id: ErrorId,
error: Error,
) {
self.errors.write().or_poisoned().push((
error_boundary_id,
error_id,
error,
));
}
fn take_errors(&self) -> Vec<(SerializedDataId, ErrorId, Error)> {
mem::take(&mut *self.errors.write().or_poisoned())
}
fn seal_errors(&self, boundary_id: &SerializedDataId) {
self.sealed_error_boundaries
.write()
.or_poisoned()
.insert(boundary_id.clone());
}
fn pending_data(&self) -> Option<PinnedStream<String>> {
let sync_data = mem::take(&mut *self.sync_buf.write().or_poisoned());
let async_data = self.async_buf.read().or_poisoned();
// 1) initial, synchronous setup chunk
let mut initial_chunk = String::new();
// resolved synchronous resources and errors
initial_chunk.push_str("__RESOLVED_RESOURCES=[");
for resolved in sync_data {
resolved.write_to_buf(&mut initial_chunk);
initial_chunk.push(',');
}
initial_chunk.push_str("];");
initial_chunk.push_str("__SERIALIZED_ERRORS=[");
for error in mem::take(&mut *self.errors.write().or_poisoned()) {
_ = write!(
initial_chunk,
"[{}, {}, {:?}],",
error.0 .0,
error.1,
error.2.to_string()
);
}
initial_chunk.push_str("];");
// pending async resources
initial_chunk.push_str("__PENDING_RESOURCES=[");
for (id, _) in async_data.iter() {
_ = write!(&mut initial_chunk, "{},", id.0);
}
initial_chunk.push_str("];");
// resolvers
initial_chunk.push_str("__RESOURCE_RESOLVERS=[];");
let async_data = AsyncDataStream {
async_buf: Arc::clone(&self.async_buf),
errors: Arc::clone(&self.errors),
sealed_error_boundaries: Arc::clone(&self.sealed_error_boundaries),
};
let incomplete = Arc::clone(&self.incomplete);
let stream = stream::once(async move { initial_chunk })
.chain(async_data)
.chain(once(async move {
let mut script = String::new();
script.push_str("__INCOMPLETE_CHUNKS=[");
for chunk in mem::take(&mut *incomplete.lock().or_poisoned()) {
_ = write!(script, "{},", chunk.0);
}
script.push_str("];");
script
}));
Some(Box::pin(stream))
}
fn during_hydration(&self) -> bool {
false
}
fn hydration_complete(&self) {}
fn defer_stream(&self, wait_for: PinnedFuture<()>) {
self.deferred.lock().or_poisoned().push(wait_for);
}
fn await_deferred(&self) -> Option<PinnedFuture<()>> {
let deferred = mem::take(&mut *self.deferred.lock().or_poisoned());
if deferred.is_empty() {
None
} else {
Some(Box::pin(async move {
join_all(deferred).await;
}))
}
}
fn set_incomplete_chunk(&self, id: SerializedDataId) {
self.incomplete.lock().or_poisoned().push(id);
}
fn get_incomplete_chunk(&self, id: &SerializedDataId) -> bool {
self.incomplete
.lock()
.or_poisoned()
.iter()
.any(|entry| entry == id)
}
}
struct AsyncDataStream {
async_buf: AsyncDataBuf,
errors: ErrorBuf,
sealed_error_boundaries: SealedErrors,
}
impl Stream for AsyncDataStream {
type Item = String;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
let mut resolved = String::new();
let mut async_buf = self.async_buf.write().or_poisoned();
let data = mem::take(&mut *async_buf);
for (id, mut fut) in data {
match fut.as_mut().poll(cx) {
// if it's not ready, put it back into the queue
Poll::Pending => {
async_buf.push((id, fut));
}
Poll::Ready(data) => {
let data = data.replace('<', "\\u003c");
_ = write!(
resolved,
"__RESOLVED_RESOURCES[{}] = {:?};",
id.0, data
);
}
}
}
let sealed = self.sealed_error_boundaries.read().or_poisoned();
for error in mem::take(&mut *self.errors.write().or_poisoned()) {
if !sealed.contains(&error.0) {
_ = write!(
resolved,
"__SERIALIZED_ERRORS.push([{}, {}, {:?}]);",
error.0 .0,
error.1,
error.2.to_string()
);
}
}
if async_buf.is_empty() && resolved.is_empty() {
return Poll::Ready(None);
}
if resolved.is_empty() {
return Poll::Pending;
}
Poll::Ready(Some(resolved))
}
}
#[derive(Debug)]
struct ResolvedData(SerializedDataId, String);
impl ResolvedData {
pub fn write_to_buf(&self, buf: &mut String) {
let ResolvedData(id, ser) = self;
// escapes < to prevent it being interpreted as another opening HTML tag
let ser = ser.replace('<', "\\u003c");
write!(buf, "{}: {:?}", id.0, ser).unwrap();
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/hydration_context/src/csr.rs | hydration_context/src/csr.rs | use super::{SerializedDataId, SharedContext};
use crate::{PinnedFuture, PinnedStream};
#[derive(Debug, Default)]
/// The shared context that should be used in the browser while hydrating.
pub struct CsrSharedContext;
impl SharedContext for CsrSharedContext {
#[inline(always)]
fn is_browser(&self) -> bool {
true
}
#[inline(always)]
fn next_id(&self) -> SerializedDataId {
SerializedDataId(0)
}
#[inline(always)]
fn write_async(&self, _id: SerializedDataId, _fut: PinnedFuture<String>) {}
#[inline(always)]
fn read_data(&self, _id: &SerializedDataId) -> Option<String> {
None
}
#[inline(always)]
fn await_data(&self, _id: &SerializedDataId) -> Option<String> {
todo!()
}
#[inline(always)]
fn pending_data(&self) -> Option<PinnedStream<String>> {
None
}
#[inline(always)]
fn get_is_hydrating(&self) -> bool {
false
}
#[inline(always)]
fn set_is_hydrating(&self, _is_hydrating: bool) {}
#[inline(always)]
fn errors(
&self,
_boundary_id: &SerializedDataId,
) -> Vec<(throw_error::ErrorId, throw_error::Error)> {
Vec::new()
}
#[inline(always)]
fn take_errors(
&self,
) -> Vec<(SerializedDataId, throw_error::ErrorId, throw_error::Error)> {
Vec::new()
}
#[inline(always)]
fn register_error(
&self,
_error_boundary: SerializedDataId,
_error_id: throw_error::ErrorId,
_error: throw_error::Error,
) {
}
#[inline(always)]
fn seal_errors(&self, _boundary_id: &SerializedDataId) {}
#[inline(always)]
fn during_hydration(&self) -> bool {
false
}
#[inline(always)]
fn hydration_complete(&self) {}
#[inline(always)]
fn defer_stream(&self, _wait_for: PinnedFuture<()>) {}
#[inline(always)]
fn await_deferred(&self) -> Option<PinnedFuture<()>> {
None
}
#[inline(always)]
fn set_incomplete_chunk(&self, _id: SerializedDataId) {}
#[inline(always)]
fn get_incomplete_chunk(&self, _id: &SerializedDataId) -> bool {
false
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/reactive.rs | benchmarks/src/reactive.rs | use std::{cell::Cell, rc::Rc};
use test::Bencher;
#[bench]
fn leptos_deep_creation(b: &mut Bencher) {
use leptos::*;
let runtime = create_runtime();
b.iter(|| {
let signal = create_rw_signal(0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
let prev = memos.last().copied();
if let Some(prev) = prev {
memos.push(create_memo(move |_| prev.get() + 1));
} else {
memos.push(create_memo(move |_| signal.get() + 1));
}
}
});
runtime.dispose();
}
#[bench]
fn leptos_deep_update(b: &mut Bencher) {
use leptos::*;
let runtime = create_runtime();
b.iter(|| {
let signal = create_rw_signal(0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
memos.push(create_memo(move |_| prev.get() + 1));
} else {
memos.push(create_memo(move |_| signal.get() + 1));
}
}
signal.set(1);
assert_eq!(memos[999].get(), 1001);
});
runtime.dispose();
}
#[bench]
fn leptos_narrowing_down(b: &mut Bencher) {
use leptos::*;
let runtime = create_runtime();
b.iter(|| {
let sigs = (0..1000).map(|n| create_signal(n)).collect::<Vec<_>>();
let reads = sigs.iter().map(|(r, _)| *r).collect::<Vec<_>>();
let writes = sigs.iter().map(|(_, w)| *w).collect::<Vec<_>>();
let memo =
create_memo(move |_| reads.iter().map(|r| r.get()).sum::<i32>());
assert_eq!(memo(), 499500);
});
runtime.dispose();
}
#[bench]
fn leptos_fanning_out(b: &mut Bencher) {
use leptos::*;
let runtime = create_runtime();
b.iter(|| {
let sig = create_rw_signal(0);
let memos = (0..1000)
.map(|_| create_memo(move |_| sig.get()))
.collect::<Vec<_>>();
assert_eq!(memos.iter().map(|m| m.get()).sum::<i32>(), 0);
sig.set(1);
assert_eq!(memos.iter().map(|m| m.get()).sum::<i32>(), 1000);
});
runtime.dispose();
}
#[bench]
fn leptos_narrowing_update(b: &mut Bencher) {
use leptos::*;
let runtime = create_runtime();
b.iter(|| {
let acc = Rc::new(Cell::new(0));
let sigs = (0..1000).map(|n| create_signal(n)).collect::<Vec<_>>();
let reads = sigs.iter().map(|(r, _)| *r).collect::<Vec<_>>();
let writes = sigs.iter().map(|(_, w)| *w).collect::<Vec<_>>();
let memo =
create_memo(move |_| reads.iter().map(|r| r.get()).sum::<i32>());
assert_eq!(memo(), 499500);
create_isomorphic_effect({
let acc = Rc::clone(&acc);
move |_| {
acc.set(memo());
}
});
assert_eq!(acc.get(), 499500);
writes[1].update(|n| *n += 1);
writes[10].update(|n| *n += 1);
writes[100].update(|n| *n += 1);
assert_eq!(acc.get(), 499503);
assert_eq!(memo(), 499503);
});
runtime.dispose();
}
#[bench]
fn l0410_deep_creation(b: &mut Bencher) {
use l0410::*;
let runtime = create_runtime();
b.iter(|| {
create_scope(runtime, |cx| {
let signal = create_rw_signal(cx, 0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
memos.push(create_memo(cx, move |_| prev.get() + 1));
} else {
memos.push(create_memo(cx, move |_| signal.get() + 1));
}
}
})
.dispose()
});
runtime.dispose();
}
#[bench]
fn l0410_deep_update(b: &mut Bencher) {
use l0410::*;
let runtime = create_runtime();
b.iter(|| {
create_scope(runtime, |cx| {
let signal = create_rw_signal(cx, 0);
let mut memos = Vec::<Memo<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
memos.push(create_memo(cx, move |_| prev.get() + 1));
} else {
memos.push(create_memo(cx, move |_| signal.get() + 1));
}
}
signal.set(1);
assert_eq!(memos[999].get(), 1001);
})
.dispose()
});
runtime.dispose();
}
#[bench]
fn l0410_narrowing_down(b: &mut Bencher) {
use l0410::*;
let runtime = create_runtime();
b.iter(|| {
create_scope(runtime, |cx| {
let acc = Rc::new(Cell::new(0));
let sigs =
(0..1000).map(|n| create_signal(cx, n)).collect::<Vec<_>>();
let reads = sigs.iter().map(|(r, _)| *r).collect::<Vec<_>>();
let writes = sigs.iter().map(|(_, w)| *w).collect::<Vec<_>>();
let memo = create_memo(cx, move |_| {
reads.iter().map(|r| r.get()).sum::<i32>()
});
assert_eq!(memo(), 499500);
})
.dispose()
});
runtime.dispose();
}
#[bench]
fn l0410_fanning_out(b: &mut Bencher) {
use l0410::*;
let runtime = create_runtime();
b.iter(|| {
create_scope(runtime, |cx| {
let sig = create_rw_signal(cx, 0);
let memos = (0..1000)
.map(|_| create_memo(cx, move |_| sig.get()))
.collect::<Vec<_>>();
assert_eq!(memos.iter().map(|m| m.get()).sum::<i32>(), 0);
sig.set(1);
assert_eq!(memos.iter().map(|m| m.get()).sum::<i32>(), 1000);
})
.dispose()
});
runtime.dispose();
}
#[bench]
fn l0410_narrowing_update(b: &mut Bencher) {
use l0410::*;
let runtime = create_runtime();
b.iter(|| {
create_scope(runtime, |cx| {
let acc = Rc::new(Cell::new(0));
let sigs =
(0..1000).map(|n| create_signal(cx, n)).collect::<Vec<_>>();
let reads = sigs.iter().map(|(r, _)| *r).collect::<Vec<_>>();
let writes = sigs.iter().map(|(_, w)| *w).collect::<Vec<_>>();
let memo = create_memo(cx, move |_| {
reads.iter().map(|r| r.get()).sum::<i32>()
});
assert_eq!(memo.get(), 499500);
create_isomorphic_effect(cx, {
let acc = Rc::clone(&acc);
move |_| {
acc.set(memo.get());
}
});
assert_eq!(acc.get(), 499500);
writes[1].update(|n| *n += 1);
writes[10].update(|n| *n += 1);
writes[100].update(|n| *n += 1);
assert_eq!(acc.get(), 499503);
assert_eq!(memo.get(), 499503);
})
.dispose()
});
runtime.dispose();
}
#[bench]
fn l0410_scope_creation_and_disposal(b: &mut Bencher) {
use l0410::*;
let runtime = create_runtime();
b.iter(|| {
let acc = Rc::new(Cell::new(0));
let disposers = (0..1000)
.map(|_| {
create_scope(runtime, {
let acc = Rc::clone(&acc);
move |cx| {
let (r, w) = create_signal(cx, 0);
create_isomorphic_effect(cx, {
move |_| {
acc.set(r.get());
}
});
w.update(|n| *n += 1);
}
})
})
.collect::<Vec<_>>();
for disposer in disposers {
disposer.dispose();
}
});
runtime.dispose();
}
#[bench]
fn sycamore_narrowing_down(b: &mut Bencher) {
use sycamore::reactive::{
create_effect, create_memo, create_scope, create_signal,
};
b.iter(|| {
let d = create_scope(|cx| {
let acc = Rc::new(Cell::new(0));
let sigs = Rc::new(
(0..1000).map(|n| create_signal(cx, n)).collect::<Vec<_>>(),
);
let memo = create_memo(cx, {
let sigs = Rc::clone(&sigs);
move || sigs.iter().map(|r| *r.get()).sum::<i32>()
});
assert_eq!(*memo.get(), 499500);
});
unsafe { d.dispose() };
});
}
#[bench]
fn sycamore_fanning_out(b: &mut Bencher) {
use sycamore::reactive::{
create_effect, create_memo, create_scope, create_signal,
};
b.iter(|| {
let d = create_scope(|cx| {
let sig = create_signal(cx, 0);
let memos = (0..1000)
.map(|_| create_memo(cx, move || sig.get()))
.collect::<Vec<_>>();
assert_eq!(memos.iter().map(|m| *(*m.get())).sum::<i32>(), 0);
sig.set(1);
assert_eq!(memos.iter().map(|m| *(*m.get())).sum::<i32>(), 1000);
});
unsafe { d.dispose() };
});
}
#[bench]
fn sycamore_deep_creation(b: &mut Bencher) {
use sycamore::reactive::*;
b.iter(|| {
let d = create_scope(|cx| {
let signal = create_signal(cx, 0);
let mut memos = Vec::<&ReadSignal<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
memos.push(create_memo(cx, move || *prev.get() + 1));
} else {
memos.push(create_memo(cx, move || *signal.get() + 1));
}
}
});
unsafe { d.dispose() };
});
}
#[bench]
fn sycamore_deep_update(b: &mut Bencher) {
use sycamore::reactive::*;
b.iter(|| {
let d = create_scope(|cx| {
let signal = create_signal(cx, 0);
let mut memos = Vec::<&ReadSignal<usize>>::new();
for _ in 0..1000usize {
if let Some(prev) = memos.last().copied() {
memos.push(create_memo(cx, move || *prev.get() + 1));
} else {
memos.push(create_memo(cx, move || *signal.get() + 1));
}
}
signal.set(1);
assert_eq!(*memos[999].get(), 1001);
});
unsafe { d.dispose() };
});
}
#[bench]
fn sycamore_narrowing_update(b: &mut Bencher) {
use sycamore::reactive::{
create_effect, create_memo, create_scope, create_signal,
};
b.iter(|| {
let d = create_scope(|cx| {
let acc = Rc::new(Cell::new(0));
let sigs = Rc::new(
(0..1000).map(|n| create_signal(cx, n)).collect::<Vec<_>>(),
);
let memo = create_memo(cx, {
let sigs = Rc::clone(&sigs);
move || sigs.iter().map(|r| *r.get()).sum::<i32>()
});
assert_eq!(*memo.get(), 499500);
create_effect(cx, {
let acc = Rc::clone(&acc);
move || {
acc.set(*memo.get());
}
});
assert_eq!(acc.get(), 499500);
sigs[1].set(*sigs[1].get() + 1);
sigs[10].set(*sigs[10].get() + 1);
sigs[100].set(*sigs[100].get() + 1);
assert_eq!(acc.get(), 499503);
assert_eq!(*memo.get(), 499503);
});
unsafe { d.dispose() };
});
}
#[bench]
fn sycamore_scope_creation_and_disposal(b: &mut Bencher) {
use sycamore::reactive::{create_effect, create_scope, create_signal};
b.iter(|| {
let acc = Rc::new(Cell::new(0));
let disposers = (0..1000)
.map(|_| {
create_scope({
let acc = Rc::clone(&acc);
move |cx| {
let s = create_signal(cx, 0);
create_effect(cx, {
move || {
acc.set(*s.get());
}
});
s.set(*s.get() + 1);
}
})
})
.collect::<Vec<_>>();
for disposer in disposers {
unsafe {
disposer.dispose();
}
}
});
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/lib.rs | benchmarks/src/lib.rs | #![feature(test)]
extern crate test;
mod reactive;
mod ssr;
mod todomvc;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/ssr.rs | benchmarks/src/ssr.rs | use test::Bencher;
#[bench]
fn leptos_ssr_bench(b: &mut Bencher) {
use leptos::*;
let r = create_runtime();
b.iter(|| {
leptos::leptos_dom::HydrationCtx::reset_id();
#[component]
fn Counter(initial: i32) -> impl IntoView {
let (value, set_value) = create_signal(initial);
view! {
<div>
<button on:click=move |_| set_value.update(|value| *value -= 1)>"-1"</button>
<span>"Value: " {move || value().to_string()} "!"</span>
<button on:click=move |_| set_value.update(|value| *value += 1)>"+1"</button>
</div>
}
}
let rendered = view! {
<main>
<h1>"Welcome to our benchmark page."</h1>
<p>"Here's some introductory text."</p>
<Counter initial=1/>
<Counter initial=2/>
<Counter initial=3/>
</main>
}.into_view().render_to_string();
assert_eq!(
rendered,
"<main data-hk=\"0-0-0-1\"><h1 data-hk=\"0-0-0-2\">Welcome to our benchmark page.</h1><p data-hk=\"0-0-0-3\">Here's some introductory text.</p><div data-hk=\"0-0-0-5\"><button data-hk=\"0-0-0-6\">-1</button><span data-hk=\"0-0-0-7\">Value: <!>1<!--hk=0-0-0-8-->!</span><button data-hk=\"0-0-0-9\">+1</button></div><!--hk=0-0-0-4--><div data-hk=\"0-0-0-11\"><button data-hk=\"0-0-0-12\">-1</button><span data-hk=\"0-0-0-13\">Value: <!>2<!--hk=0-0-0-14-->!</span><button data-hk=\"0-0-0-15\">+1</button></div><!--hk=0-0-0-10--><div data-hk=\"0-0-0-17\"><button data-hk=\"0-0-0-18\">-1</button><span data-hk=\"0-0-0-19\">Value: <!>3<!--hk=0-0-0-20-->!</span><button data-hk=\"0-0-0-21\">+1</button></div><!--hk=0-0-0-16--></main>" );
});
r.dispose();
}
#[bench]
fn tachys_ssr_bench(b: &mut Bencher) {
use leptos::{create_runtime, create_signal, SignalGet, SignalUpdate};
use tachy_maccy::view;
use tachydom::view::{Render, RenderHtml};
use tachydom::html::element::ElementChild;
use tachydom::html::attribute::global::ClassAttribute;
use tachydom::html::attribute::global::GlobalAttributes;
use tachydom::html::attribute::global::OnAttribute;
use tachydom::renderer::dom::Dom;
let rt = create_runtime();
b.iter(|| {
fn counter(initial: i32) -> impl Render<Dom> + RenderHtml<Dom> {
let (value, set_value) = create_signal(initial);
view! {
<div>
<button on:click=move |_| set_value.update(|value| *value -= 1)>"-1"</button>
<span>"Value: " {move || value().to_string()} "!"</span>
<button on:click=move |_| set_value.update(|value| *value += 1)>"+1"</button>
</div>
}
}
let rendered = view! {
<main>
<h1>"Welcome to our benchmark page."</h1>
<p>"Here's some introductory text."</p>
{counter(1)}
{counter(2)}
{counter(3)}
</main>
}.to_html();
assert_eq!(
rendered,
"<main><h1>Welcome to our benchmark page.</h1><p>Here's some introductory text.</p><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><button>-1</button><span>Value: <!>3<!>!</span><button>+1</button></div></main>"
);
});
rt.dispose();
}
#[bench]
fn tera_ssr_bench(b: &mut Bencher) {
use serde::{Deserialize, Serialize};
use tera::*;
static TEMPLATE: &str = r#"<main>
<h1>Welcome to our benchmark page.</h1>
<p>Here's some introductory text.</p>
{% for counter in counters %}
<div>
<button>-1</button>
<span>Value: {{ counter.value }}!</span>
<button>+1</button>
</div>
{% endfor %}
</main>"#;
static LazyCell<TERA>: Tera = LazyLock::new(|| {
let mut tera = Tera::default();
tera.add_raw_templates(vec![("template.html", TEMPLATE)]).unwrap();
tera
});
#[derive(Serialize, Deserialize)]
struct Counter {
value: i32,
}
b.iter(|| {
let mut ctx = Context::new();
ctx.insert(
"counters",
&vec![
Counter { value: 0 },
Counter { value: 1 },
Counter { value: 2 },
],
);
let _ = TERA.render("template.html", &ctx).unwrap();
});
}
#[bench]
fn sycamore_ssr_bench(b: &mut Bencher) {
use sycamore::prelude::*;
use sycamore::*;
b.iter(|| {
_ = create_scope(|cx| {
#[derive(Prop)]
struct CounterProps {
initial: i32
}
#[component]
fn Counter<G: Html>(cx: Scope, props: CounterProps) -> View<G> {
let value = create_signal(cx, props.initial);
view! {
cx,
div {
button(on:click=|_| value.set(*value.get() - 1)) {
"-1"
}
span {
"Value: "
(value.get().to_string())
"!"
}
button(on:click=|_| value.set(*value.get() + 1)) {
"+1"
}
}
}
}
let rendered = render_to_string(|cx| view! {
cx,
main {
h1 {
"Welcome to our benchmark page."
}
p {
"Here's some introductory text."
}
Counter(initial = 1)
Counter(initial = 2)
Counter(initial = 3)
}
});
assert_eq!(
rendered,
"<main data-hk=\"0.0\"><h1 data-hk=\"0.1\">Welcome to our benchmark page.</h1><p data-hk=\"0.2\">Here's some introductory text.</p><!--#--><div data-hk=\"1.0\"><button data-hk=\"1.1\">-1</button><span data-hk=\"1.2\">Value: <!--#-->1<!--/-->!</span><button data-hk=\"1.3\">+1</button></div><!--/--><!----><!--#--><div data-hk=\"2.0\"><button data-hk=\"2.1\">-1</button><span data-hk=\"2.2\">Value: <!--#-->2<!--/-->!</span><button data-hk=\"2.3\">+1</button></div><!--/--><!----><!--#--><div data-hk=\"3.0\"><button data-hk=\"3.1\">-1</button><span data-hk=\"3.2\">Value: <!--#-->3<!--/-->!</span><button data-hk=\"3.3\">+1</button></div><!--/--></main>"
);
});
});
}
#[bench]
fn yew_ssr_bench(b: &mut Bencher) {
use yew::prelude::*;
use yew::ServerRenderer;
b.iter(|| {
#[derive(Properties, PartialEq, Eq, Debug)]
struct CounterProps {
initial: i32
}
#[function_component(Counter)]
fn counter(props: &CounterProps) -> Html {
let state = use_state(|| props.initial);
let incr_counter = {
let state = state.clone();
Callback::from(move |_| state.set(&*state + 1))
};
let decr_counter = {
let state = state.clone();
Callback::from(move |_| state.set(&*state - 1))
};
html! {
<div>
<h1>{"Welcome to our benchmark page."}</h1>
<p>{"Here's some introductory text."}</p>
<button onclick={decr_counter}> {"-1"} </button>
<p> {"Value: "} {*state} {"!"} </p>
<button onclick={incr_counter}> {"+1"} </button>
</div>
}
}
#[function_component]
fn App() -> Html {
html! {
<main>
<Counter initial=1/>
<Counter initial=2/>
<Counter initial=3/>
</main>
}
}
tokio_test::block_on(async {
let renderer = ServerRenderer::<App>::new();
let rendered = renderer.render().await;
assert_eq!(
rendered,
"<!--<[]>--><main><!--<[]>--><div><h1>Welcome to our benchmark page.</h1><p>Here's some introductory text.</p><button>-1</button><p>Value: 1!</p><button>+1</button></div><!--</[]>--><!--<[]>--><div><h1>Welcome to our benchmark page.</h1><p>Here's some introductory text.</p><button>-1</button><p>Value: 2!</p><button>+1</button></div><!--</[]>--><!--<[]>--><div><h1>Welcome to our benchmark page.</h1><p>Here's some introductory text.</p><button>-1</button><p>Value: 3!</p><button>+1</button></div><!--</[]>--></main><!--</[]>-->"
);
});
});
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/todomvc/leptos.rs | benchmarks/src/todomvc/leptos.rs | pub use leptos::*;
use miniserde::*;
use wasm_bindgen::JsCast;
use web_sys::HtmlInputElement;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Todos(pub Vec<Todo>);
const STORAGE_KEY: &str = "todos-leptos";
impl Todos {
pub fn new() -> Self {
Self(vec![])
}
pub fn new_with_1000() -> Self {
let todos = (0..1000)
.map(|id| Todo::new(id, format!("Todo #{id}")))
.collect();
Self(todos)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn add(&mut self, todo: Todo) {
self.0.push(todo);
}
pub fn remove(&mut self, id: usize) {
self.0.retain(|todo| todo.id != id);
}
pub fn remaining(&self) -> usize {
self.0.iter().filter(|todo| !(todo.completed)()).count()
}
pub fn completed(&self) -> usize {
self.0.iter().filter(|todo| (todo.completed)()).count()
}
pub fn toggle_all(&self) {
// if all are complete, mark them all active instead
if self.remaining() == 0 {
for todo in &self.0 {
if todo.completed.get() {
(todo.set_completed)(false);
}
}
}
// otherwise, mark them all complete
else {
for todo in &self.0 {
(todo.set_completed)(true);
}
}
}
fn clear_completed(&mut self) {
self.0.retain(|todo| !todo.completed.get());
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Todo {
pub id: usize,
pub title: ReadSignal<String>,
pub set_title: WriteSignal<String>,
pub completed: ReadSignal<bool>,
pub set_completed: WriteSignal<bool>,
}
impl Todo {
pub fn new(id: usize, title: String) -> Self {
Self::new_with_completed(id, title, false)
}
pub fn new_with_completed(
id: usize,
title: String,
completed: bool,
) -> Self {
let (title, set_title) = create_signal(title);
let (completed, set_completed) = create_signal(completed);
Self {
id,
title,
set_title,
completed,
set_completed,
}
}
pub fn toggle(&self) {
self.set_completed
.update(|completed| *completed = !*completed);
}
}
const ESCAPE_KEY: u32 = 27;
const ENTER_KEY: u32 = 13;
#[component]
pub fn TodoMVC(todos: Todos) -> impl IntoView {
let mut next_id = todos
.0
.iter()
.map(|todo| todo.id)
.max()
.map(|last| last + 1)
.unwrap_or(0);
let (todos, set_todos) = create_signal(todos);
provide_context(set_todos);
let (mode, set_mode) = create_signal(Mode::All);
let add_todo = move |ev: web_sys::KeyboardEvent| {
let target = event_target::<HtmlInputElement>(&ev);
ev.stop_propagation();
let key_code = ev.unchecked_ref::<web_sys::KeyboardEvent>().key_code();
if key_code == ENTER_KEY {
let title = event_target_value(&ev);
let title = title.trim();
if !title.is_empty() {
let new = Todo::new(next_id, title.to_string());
set_todos.update(|t| t.add(new));
next_id += 1;
target.set_value("");
}
}
};
let filtered_todos = create_memo::<Vec<Todo>>(move |_| {
todos.with(|todos| match mode.get() {
Mode::All => todos.0.to_vec(),
Mode::Active => todos
.0
.iter()
.filter(|todo| !todo.completed.get())
.cloned()
.collect(),
Mode::Completed => todos
.0
.iter()
.filter(|todo| todo.completed.get())
.cloned()
.collect(),
})
});
// effect to serialize to JSON
// this does reactive reads, so it will automatically serialize on any relevant change
create_effect(move |_| {
if let Ok(Some(storage)) = window().local_storage() {
let objs = todos
.get()
.0
.iter()
.map(TodoSerialized::from)
.collect::<Vec<_>>();
let json = json::to_string(&objs);
if storage.set_item(STORAGE_KEY, &json).is_err() {
log::error!("error while trying to set item in localStorage");
}
}
});
view! {
<main>
<section class="todoapp">
<header class="header">
<h1>"todos"</h1>
<input
class="new-todo"
placeholder="What needs to be done?"
autofocus=""
on:keydown=add_todo
/>
</header>
<section class="main" class:hidden=move || todos.with(|t| t.is_empty())>
<input
id="toggle-all"
class="toggle-all"
type="checkbox"
prop:checked=move || todos.with(|t| t.remaining() > 0)
on:input=move |_| set_todos.update(|t| t.toggle_all())
/>
<label for="toggle-all">"Mark all as complete"</label>
<ul class="todo-list">
<For
each=filtered_todos
key=|todo| todo.id
children=move |todo: Todo| {
view! { <Todo todo=todo.clone()/> }
}
/>
</ul>
</section>
<footer class="footer" class:hidden=move || todos.with(|t| t.is_empty())>
<span class="todo-count">
<strong>{move || todos.with(|t| t.remaining().to_string())}</strong>
{move || if todos.with(|t| t.remaining()) == 1 { " item" } else { " items" }}
" left"
</span>
<ul class="filters">
<li>
<a
href="#/"
class="selected"
class:selected=move || mode() == Mode::All
>
"All"
</a>
</li>
<li>
<a href="#/active" class:selected=move || mode() == Mode::Active>
"Active"
</a>
</li>
<li>
<a href="#/completed" class:selected=move || mode() == Mode::Completed>
"Completed"
</a>
</li>
</ul>
<button
class="clear-completed hidden"
class:hidden=move || todos.with(|t| t.completed() == 0)
on:click=move |_| set_todos.update(|t| t.clear_completed())
>
"Clear completed"
</button>
</footer>
</section>
<footer class="info">
<p>"Double-click to edit a todo"</p>
<p>"Created by " <a href="http://todomvc.com">"Greg Johnston"</a></p>
<p>"Part of " <a href="http://todomvc.com">"TodoMVC"</a></p>
</footer>
</main>
}.into_view()
}
#[component]
pub fn Todo(todo: Todo) -> impl IntoView {
let (editing, set_editing) = create_signal(false);
let set_todos = use_context::<WriteSignal<Todos>>().unwrap();
//let input = NodeRef::new();
let save = move |value: &str| {
let value = value.trim();
if value.is_empty() {
set_todos.update(|t| t.remove(todo.id));
} else {
(todo.set_title)(value.to_string());
}
set_editing(false);
};
view! {
<li class="todo" class:editing=editing class:completed=move || (todo.completed)()>
<div class="view">
<input class="toggle" type="checkbox" prop:checked=move || (todo.completed)()/>
<label on:dblclick=move |_| set_editing(true)>{move || todo.title.get()}</label>
<button
class="destroy"
on:click=move |_| set_todos.update(|t| t.remove(todo.id))
></button>
</div>
{move || {
editing()
.then(|| {
view! {
<input
class="edit"
class:hidden=move || !(editing)()
prop:value=move || todo.title.get()
on:focusout=move |ev| save(&event_target_value(&ev))
on:keyup=move |ev| {
let key_code = ev.unchecked_ref::<web_sys::KeyboardEvent>().key_code();
if key_code == ENTER_KEY {
save(&event_target_value(&ev));
} else if key_code == ESCAPE_KEY {
set_editing(false);
}
}
/>
}
})
}}
</li>
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Active,
Completed,
All,
}
impl Default for Mode {
fn default() -> Self {
Mode::All
}
}
pub fn route(hash: &str) -> Mode {
match hash {
"/active" => Mode::Active,
"/completed" => Mode::Completed,
_ => Mode::All,
}
}
#[derive(Serialize, Deserialize)]
pub struct TodoSerialized {
pub id: usize,
pub title: String,
pub completed: bool,
}
impl TodoSerialized {
pub fn into_todo(self, ) -> Todo {
Todo::new_with_completed(self.id, self.title, self.completed)
}
}
impl From<&Todo> for TodoSerialized {
fn from(todo: &Todo) -> Self {
Self {
id: todo.id,
title: todo.title.get(),
completed: (todo.completed)(),
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/todomvc/yew.rs | benchmarks/src/todomvc/yew.rs | use gloo::storage::{LocalStorage, Storage};
use strum::IntoEnumIterator;
use web_sys::HtmlInputElement as InputElement;
use yew::events::{FocusEvent, KeyboardEvent};
use yew::html::Scope;
use yew::{classes, html, Classes, Component, Context, Html, NodeRef, TargetCast};
const KEY: &str = "yew.todomvc.self";
pub enum Msg {
Add(String),
Edit((usize, String)),
Remove(usize),
SetFilter(Filter),
ToggleAll,
ToggleEdit(usize),
Toggle(usize),
ClearCompleted,
Focus,
}
pub struct App {
state: State,
focus_ref: NodeRef,
}
impl Component for App {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
let entries = vec![]; //LocalStorage::get(KEY).unwrap_or_else(|_| Vec::new());
let state = State {
entries,
filter: Filter::All,
edit_value: "".into(),
};
let focus_ref = NodeRef::default();
Self { state, focus_ref }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Add(description) => {
if !description.is_empty() {
let entry = Entry {
description: description.trim().to_string(),
completed: false,
editing: false,
};
self.state.entries.push(entry);
}
}
Msg::Edit((idx, edit_value)) => {
self.state.complete_edit(idx, edit_value.trim().to_string());
self.state.edit_value = "".to_string();
}
Msg::Remove(idx) => {
self.state.remove(idx);
}
Msg::SetFilter(filter) => {
self.state.filter = filter;
}
Msg::ToggleEdit(idx) => {
let entry = self
.state
.entries
.iter()
.filter(|e| self.state.filter.fits(e))
.nth(idx)
.unwrap();
self.state.edit_value = entry.description.clone();
self.state.clear_all_edit();
self.state.toggle_edit(idx);
}
Msg::ToggleAll => {
let status = !self.state.is_all_completed();
self.state.toggle_all(status);
}
Msg::Toggle(idx) => {
self.state.toggle(idx);
}
Msg::ClearCompleted => {
self.state.clear_completed();
}
Msg::Focus => {
if let Some(input) = self.focus_ref.cast::<InputElement>() {
input.focus().unwrap();
}
}
}
LocalStorage::set(KEY, &self.state.entries).expect("failed to set");
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let hidden_class = if self.state.entries.is_empty() {
"hidden"
} else {
""
};
html! {
<div class="todomvc-wrapper">
<section class="todoapp">
<header class="header">
<h1>{ "todos" }</h1>
{ self.view_input(ctx.link()) }
</header>
<section class={classes!("main", hidden_class)}>
<input
type="checkbox"
class="toggle-all"
id="toggle-all"
checked={self.state.is_all_completed()}
onclick={ctx.link().callback(|_| Msg::ToggleAll)}
/>
<label for="toggle-all" />
<ul class="todo-list">
{ for self.state.entries.iter().filter(|e| self.state.filter.fits(e)).enumerate().map(|e| self.view_entry(e, ctx.link())) }
</ul>
</section>
<footer class={classes!("footer", hidden_class)}>
<span class="todo-count">
<strong>{ self.state.total() }</strong>
{ " item(s) left" }
</span>
<ul class="filters">
{ for Filter::iter().map(|flt| self.view_filter(flt, ctx.link())) }
</ul>
<button class="clear-completed" onclick={ctx.link().callback(|_| Msg::ClearCompleted)}>
{ format!("Clear completed ({})", self.state.total_completed()) }
</button>
</footer>
</section>
<footer class="info">
<p>{ "Double-click to edit a todo" }</p>
<p>{ "Written by " }<a href="https://github.com/DenisKolodin/" target="_blank">{ "Denis Kolodin" }</a></p>
<p>{ "Part of " }<a href="http://todomvc.com/" target="_blank">{ "TodoMVC" }</a></p>
</footer>
</div>
}
}
}
impl App {
fn view_filter(&self, filter: Filter, link: &Scope<Self>) -> Html {
let cls = if self.state.filter == filter {
"selected"
} else {
"not-selected"
};
html! {
<li>
<a class={cls}
href={filter.as_href()}
onclick={link.callback(move |_| Msg::SetFilter(filter))}
>
{ filter }
</a>
</li>
}
}
fn view_input(&self, link: &Scope<Self>) -> Html {
let onkeypress = link.batch_callback(|e: KeyboardEvent| {
if e.key() == "Enter" {
let input: InputElement = e.target_unchecked_into();
let value = input.value();
input.set_value("");
Some(Msg::Add(value))
} else {
None
}
});
html! {
// You can use standard Rust comments. One line:
// <li></li>
<input
class="new-todo"
placeholder="What needs to be done?"
{onkeypress}
/>
/* Or multiline:
<ul>
<li></li>
</ul>
*/
}
}
fn view_entry(&self, (idx, entry): (usize, &Entry), link: &Scope<Self>) -> Html {
let mut class = Classes::from("todo");
if entry.editing {
class.push(" editing");
}
if entry.completed {
class.push(" completed");
}
html! {
<li {class}>
<div class="view">
<input
type="checkbox"
class="toggle"
checked={entry.completed}
onclick={link.callback(move |_| Msg::Toggle(idx))}
/>
<label ondblclick={link.callback(move |_| Msg::ToggleEdit(idx))}>{ &entry.description }</label>
<button class="destroy" onclick={link.callback(move |_| Msg::Remove(idx))} />
</div>
{ self.view_entry_edit_input((idx, entry), link) }
</li>
}
}
fn view_entry_edit_input(&self, (idx, entry): (usize, &Entry), link: &Scope<Self>) -> Html {
let edit = move |input: InputElement| {
let value = input.value();
input.set_value("");
Msg::Edit((idx, value))
};
let onblur = link.callback(move |e: FocusEvent| edit(e.target_unchecked_into()));
let onkeypress = link.batch_callback(move |e: KeyboardEvent| {
(e.key() == "Enter").then(|| edit(e.target_unchecked_into()))
});
if entry.editing {
html! {
<input
class="edit"
type="text"
ref={self.focus_ref.clone()}
value={self.state.edit_value.clone()}
onmouseover={link.callback(|_| Msg::Focus)}
{onblur}
{onkeypress}
/>
}
} else {
html! { <input type="hidden" /> }
}
}
}
pub struct AppWith1000 {
state: State,
focus_ref: NodeRef,
}
impl Component for AppWith1000 {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
let entries = (0..1000)
.map(|id| Entry {
description: format!("Todo #{id}"),
completed: false,
editing: false,
})
.collect();
let state = State {
entries,
filter: Filter::All,
edit_value: "".into(),
};
let focus_ref = NodeRef::default();
Self { state, focus_ref }
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Add(description) => {
if !description.is_empty() {
let entry = Entry {
description: description.trim().to_string(),
completed: false,
editing: false,
};
self.state.entries.push(entry);
}
}
Msg::Edit((idx, edit_value)) => {
self.state.complete_edit(idx, edit_value.trim().to_string());
self.state.edit_value = "".to_string();
}
Msg::Remove(idx) => {
self.state.remove(idx);
}
Msg::SetFilter(filter) => {
self.state.filter = filter;
}
Msg::ToggleEdit(idx) => {
let entry = self
.state
.entries
.iter()
.filter(|e| self.state.filter.fits(e))
.nth(idx)
.unwrap();
self.state.edit_value = entry.description.clone();
self.state.clear_all_edit();
self.state.toggle_edit(idx);
}
Msg::ToggleAll => {
let status = !self.state.is_all_completed();
self.state.toggle_all(status);
}
Msg::Toggle(idx) => {
self.state.toggle(idx);
}
Msg::ClearCompleted => {
self.state.clear_completed();
}
Msg::Focus => {
if let Some(input) = self.focus_ref.cast::<InputElement>() {
input.focus().unwrap();
}
}
}
LocalStorage::set(KEY, &self.state.entries).expect("failed to set");
true
}
fn view(&self, ctx: &Context<Self>) -> Html {
let hidden_class = if self.state.entries.is_empty() {
"hidden"
} else {
""
};
html! {
<div class="todomvc-wrapper">
<section class="todoapp">
<header class="header">
<h1>{ "todos" }</h1>
{ self.view_input(ctx.link()) }
</header>
<section class={classes!("main", hidden_class)}>
<input
type="checkbox"
class="toggle-all"
id="toggle-all"
checked={self.state.is_all_completed()}
onclick={ctx.link().callback(|_| Msg::ToggleAll)}
/>
<label for="toggle-all" />
<ul class="todo-list">
{ for self.state.entries.iter().filter(|e| self.state.filter.fits(e)).enumerate().map(|e| self.view_entry(e, ctx.link())) }
</ul>
</section>
<footer class={classes!("footer", hidden_class)}>
<span class="todo-count">
<strong>{ self.state.total() }</strong>
{ " item(s) left" }
</span>
<ul class="filters">
{ for Filter::iter().map(|flt| self.view_filter(flt, ctx.link())) }
</ul>
<button class="clear-completed" onclick={ctx.link().callback(|_| Msg::ClearCompleted)}>
{ format!("Clear completed ({})", self.state.total_completed()) }
</button>
</footer>
</section>
<footer class="info">
<p>{ "Double-click to edit a todo" }</p>
<p>{ "Written by " }<a href="https://github.com/DenisKolodin/" target="_blank">{ "Denis Kolodin" }</a></p>
<p>{ "Part of " }<a href="http://todomvc.com/" target="_blank">{ "TodoMVC" }</a></p>
</footer>
</div>
}
}
}
impl AppWith1000 {
fn view_filter(&self, filter: Filter, link: &Scope<Self>) -> Html {
let cls = if self.state.filter == filter {
"selected"
} else {
"not-selected"
};
html! {
<li>
<a class={cls}
href={filter.as_href()}
onclick={link.callback(move |_| Msg::SetFilter(filter))}
>
{ filter }
</a>
</li>
}
}
fn view_input(&self, link: &Scope<Self>) -> Html {
let onkeypress = link.batch_callback(|e: KeyboardEvent| {
if e.key() == "Enter" {
let input: InputElement = e.target_unchecked_into();
let value = input.value();
input.set_value("");
Some(Msg::Add(value))
} else {
None
}
});
html! {
// You can use standard Rust comments. One line:
// <li></li>
<input
class="new-todo"
placeholder="What needs to be done?"
{onkeypress}
/>
/* Or multiline:
<ul>
<li></li>
</ul>
*/
}
}
fn view_entry(&self, (idx, entry): (usize, &Entry), link: &Scope<Self>) -> Html {
let mut class = Classes::from("todo");
if entry.editing {
class.push(" editing");
}
if entry.completed {
class.push(" completed");
}
html! {
<li {class}>
<div class="view">
<input
type="checkbox"
class="toggle"
checked={entry.completed}
onclick={link.callback(move |_| Msg::Toggle(idx))}
/>
<label ondblclick={link.callback(move |_| Msg::ToggleEdit(idx))}>{ &entry.description }</label>
<button class="destroy" onclick={link.callback(move |_| Msg::Remove(idx))} />
</div>
{ self.view_entry_edit_input((idx, entry), link) }
</li>
}
}
fn view_entry_edit_input(&self, (idx, entry): (usize, &Entry), link: &Scope<Self>) -> Html {
let edit = move |input: InputElement| {
let value = input.value();
input.set_value("");
Msg::Edit((idx, value))
};
let onblur = link.callback(move |e: FocusEvent| edit(e.target_unchecked_into()));
let onkeypress = link.batch_callback(move |e: KeyboardEvent| {
(e.key() == "Enter").then(|| edit(e.target_unchecked_into()))
});
if entry.editing {
html! {
<input
class="edit"
type="text"
ref={self.focus_ref.clone()}
value={self.state.edit_value.clone()}
onmouseover={link.callback(|_| Msg::Focus)}
{onblur}
{onkeypress}
/>
}
} else {
html! { <input type="hidden" /> }
}
}
}
use serde::{Deserialize, Serialize};
use strum_macros::{Display, EnumIter};
#[derive(Debug, Serialize, Deserialize)]
pub struct State {
pub entries: Vec<Entry>,
pub filter: Filter,
pub edit_value: String,
}
impl State {
pub fn total(&self) -> usize {
self.entries.len()
}
pub fn total_completed(&self) -> usize {
self.entries
.iter()
.filter(|e| Filter::Completed.fits(e))
.count()
}
pub fn is_all_completed(&self) -> bool {
let mut filtered_iter = self
.entries
.iter()
.filter(|e| self.filter.fits(e))
.peekable();
if filtered_iter.peek().is_none() {
return false;
}
filtered_iter.all(|e| e.completed)
}
pub fn clear_completed(&mut self) {
let entries = self
.entries
.drain(..)
.filter(|e| Filter::Active.fits(e))
.collect();
self.entries = entries;
}
pub fn toggle(&mut self, idx: usize) {
let filter = self.filter;
let entry = self
.entries
.iter_mut()
.filter(|e| filter.fits(e))
.nth(idx)
.unwrap();
entry.completed = !entry.completed;
}
pub fn toggle_all(&mut self, value: bool) {
for entry in &mut self.entries {
if self.filter.fits(entry) {
entry.completed = value;
}
}
}
pub fn toggle_edit(&mut self, idx: usize) {
let filter = self.filter;
let entry = self
.entries
.iter_mut()
.filter(|e| filter.fits(e))
.nth(idx)
.unwrap();
entry.editing = !entry.editing;
}
pub fn clear_all_edit(&mut self) {
for entry in &mut self.entries {
entry.editing = false;
}
}
pub fn complete_edit(&mut self, idx: usize, val: String) {
if val.is_empty() {
self.remove(idx);
} else {
let filter = self.filter;
let entry = self
.entries
.iter_mut()
.filter(|e| filter.fits(e))
.nth(idx)
.unwrap();
entry.description = val;
entry.editing = !entry.editing;
}
}
pub fn remove(&mut self, idx: usize) {
let idx = {
let entries = self
.entries
.iter()
.enumerate()
.filter(|&(_, e)| self.filter.fits(e))
.collect::<Vec<_>>();
let &(idx, _) = entries.get(idx).unwrap();
idx
};
self.entries.remove(idx);
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Entry {
pub description: String,
pub completed: bool,
pub editing: bool,
}
#[derive(Clone, Copy, Debug, EnumIter, Display, PartialEq, Serialize, Deserialize, Eq)]
pub enum Filter {
All,
Active,
Completed,
}
impl Filter {
pub fn fits(&self, entry: &Entry) -> bool {
match *self {
Filter::All => true,
Filter::Active => !entry.completed,
Filter::Completed => entry.completed,
}
}
pub fn as_href(&self) -> &'static str {
match self {
Filter::All => "#/",
Filter::Active => "#/active",
Filter::Completed => "#/completed",
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/todomvc/sycamore.rs | benchmarks/src/todomvc/sycamore.rs | use serde::{Deserialize, Serialize};
use sycamore::prelude::*;
use uuid::Uuid;
use wasm_bindgen::JsCast;
use web_sys::{Event, HtmlInputElement, KeyboardEvent};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct Todo {
title: String,
completed: bool,
id: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Filter {
All,
Active,
Completed,
}
impl Default for Filter {
fn default() -> Self {
Self::All
}
}
impl Filter {
fn url(self) -> &'static str {
match self {
Filter::All => "#",
Filter::Active => "#/active",
Filter::Completed => "#/completed",
}
}
fn get_filter_from_hash() -> Self {
let hash = web_sys::window().unwrap().location().hash().unwrap();
match hash.as_str() {
"#/active" => Filter::Active,
"#/completed" => Filter::Completed,
_ => Filter::All,
}
}
}
#[derive(Debug, Default, Clone)]
pub struct AppState {
pub todos: RcSignal<Vec<RcSignal<Todo>>>,
pub filter: RcSignal<Filter>,
}
impl AppState {
fn add_todo(&self, title: String, id: usize) {
self.todos.modify().push(create_rc_signal(Todo {
title,
completed: false,
id,
}))
}
fn remove_todo(&self, id: usize) {
self.todos.modify().retain(|todo| todo.get().id != id);
}
fn todos_left(&self) -> usize {
self.todos.get().iter().fold(
0,
|acc, todo| if todo.get().completed { acc } else { acc + 1 },
)
}
fn toggle_complete_all(&self) {
if self.todos_left() == 0 {
// make all todos active
for todo in self.todos.get().iter() {
if todo.get().completed {
todo.set(Todo {
completed: false,
..todo.get().as_ref().clone()
})
}
}
} else {
// make all todos completed
for todo in self.todos.get().iter() {
if !todo.get().completed {
todo.set(Todo {
completed: true,
..todo.get().as_ref().clone()
})
}
}
}
}
fn clear_completed(&self) {
self.todos.modify().retain(|todo| !todo.get().completed);
}
}
const KEY: &str = "todos-sycamore";
#[component]
pub fn App<G: Html>(cx: Scope) -> View<G> {
// Initialize application state
let todos = create_rc_signal(Vec::new());
let app_state = AppState {
todos,
filter: create_rc_signal(Filter::All),
};
provide_context(cx, app_state);
view! { cx,
div(class="todomvc-wrapper") {
section(class="todoapp") {
Header {}
List {}
Footer {}
}
Copyright {}
}
}
}
#[component]
pub fn AppWith1000<G: Html>(cx: Scope) -> View<G> {
// Initialize application state
let todos = (0..1000)
.map(|id| {
create_rc_signal(Todo {
title: format!("Todo #{id}"),
completed: false,
id,
})
})
.collect();
let todos = create_rc_signal(todos);
let app_state = AppState {
todos,
filter: create_rc_signal(Filter::All),
};
provide_context(cx, app_state);
view! { cx,
div(class="todomvc-wrapper") {
section(class="todoapp") {
Header {}
List {}
Footer {}
}
Copyright {}
}
}
}
#[component]
pub fn Copyright<G: Html>(cx: Scope) -> View<G> {
view! { cx,
footer(class="info") {
p { "Double click to edit a todo" }
p {
"Created by "
a(href="https://github.com/lukechu10", target="_blank") { "lukechu10" }
}
p {
"Part of "
a(href="http://todomvc.com") { "TodoMVC" }
}
}
}
}
#[component]
pub fn Header<G: Html>(cx: Scope) -> View<G> {
let app_state = use_context::<AppState>(cx);
let value = create_signal(cx, String::new());
let input_ref = create_node_ref(cx);
let handle_submit = |event: Event| {
let event: KeyboardEvent = event.unchecked_into();
if event.key() == "Enter" {
let mut task = value.get().as_ref().clone();
task = task.trim().to_string();
if !task.is_empty() {
app_state.add_todo(task, 0);
value.set("".to_string());
input_ref
.get::<DomNode>()
.unchecked_into::<HtmlInputElement>()
.set_value("");
}
}
};
view! { cx,
header(class="header") {
h1 { "todos" }
input(ref=input_ref,
class="new-todo",
placeholder="What needs to be done?",
bind:value=value,
on:keyup=handle_submit,
)
}
}
}
#[component(inline_props)]
pub fn Item<G: Html>(cx: Scope, todo: RcSignal<Todo>) -> View<G> {
let app_state = use_context::<AppState>(cx);
// Make `todo` live as long as the scope.
let todo = create_ref(cx, todo);
let title = || todo.get().title.clone();
let completed = create_selector(cx, || todo.get().completed);
let id = todo.get().id;
let editing = create_signal(cx, false);
let input_ref = create_node_ref(cx);
let value = create_signal(cx, "".to_string());
let handle_input = |event: Event| {
let target: HtmlInputElement = event.target().unwrap().unchecked_into();
value.set(target.value());
};
let toggle_completed = |_| {
todo.set(Todo {
completed: !todo.get().completed,
..todo.get().as_ref().clone()
});
};
let handle_dblclick = move |_| {
editing.set(true);
input_ref
.get::<DomNode>()
.unchecked_into::<HtmlInputElement>()
.focus()
.unwrap();
value.set(title());
};
let handle_blur = move || {
editing.set(false);
let mut value = value.get().as_ref().clone();
value = value.trim().to_string();
if value.is_empty() {
app_state.remove_todo(id);
} else {
todo.set(Todo {
title: value,
..todo.get().as_ref().clone()
})
}
};
let handle_submit = move |event: Event| {
let event: KeyboardEvent = event.unchecked_into();
match event.key().as_str() {
"Enter" => handle_blur(),
"Escape" => {
input_ref
.get::<DomNode>()
.unchecked_into::<HtmlInputElement>()
.set_value(&title());
editing.set(false);
}
_ => {}
}
};
let handle_destroy = move |_| {
app_state.remove_todo(id);
};
// We need a separate signal for checked because clicking the checkbox will detach the binding
// between the attribute and the view.
let checked = create_signal(cx, false);
create_effect(cx, || {
// Calling checked.set will also update the `checked` property on the input element.
checked.set(*completed.get())
});
let class = || {
format!(
"{} {}",
if *completed.get() { "completed" } else { "" },
if *editing.get() { "editing" } else { "" }
)
};
view! { cx,
li(class=class()) {
div(class="view") {
input(
class="toggle",
type="checkbox",
on:input=toggle_completed,
bind:checked=checked
)
label(on:dblclick=handle_dblclick) {
(title())
}
button(class="destroy", on:click=handle_destroy)
}
(if *editing.get() {
view! { cx,
input(ref=input_ref,
class="edit",
prop:value=&todo.get().title,
on:blur=move |_| handle_blur(),
on:keyup=handle_submit,
on:input=handle_input,
)
}
} else {
View::empty()
})
}
}
}
#[component]
pub fn List<G: Html>(cx: Scope) -> View<G> {
let app_state = use_context::<AppState>(cx);
let todos_left = create_selector(cx, || app_state.todos_left());
let filtered_todos = create_memo(cx, || {
app_state
.todos
.get()
.iter()
.filter(|todo| match *app_state.filter.get() {
Filter::All => true,
Filter::Active => !todo.get().completed,
Filter::Completed => todo.get().completed,
})
.cloned()
.collect::<Vec<_>>()
});
// We need a separate signal for checked because clicking the checkbox will detach the binding
// between the attribute and the view.
let checked = create_signal(cx, false);
create_effect(cx, || {
// Calling checked.set will also update the `checked` property on the input element.
checked.set(*todos_left.get() == 0)
});
view! { cx,
section(class="main") {
input(
id="toggle-all",
class="toggle-all",
type="checkbox",
readonly=true,
bind:checked=checked,
on:input=|_| app_state.toggle_complete_all()
)
label(for="toggle-all")
ul(class="todo-list") {
Keyed(
iterable=filtered_todos,
view=|cx, todo| view! { cx,
Item(todo=todo)
},
key=|todo| todo.get().id,
)
}
}
}
}
#[component(inline_props)]
pub fn TodoFilter<G: Html>(cx: Scope, filter: Filter) -> View<G> {
let app_state = use_context::<AppState>(cx);
let selected = move || filter == *app_state.filter.get();
let set_filter = |filter| app_state.filter.set(filter);
view! { cx,
li {
a(
class=if selected() { "selected" } else { "" },
href=filter.url(),
on:click=move |_| set_filter(filter),
) {
(format!("{filter:?}"))
}
}
}
}
#[component]
pub fn Footer<G: Html>(cx: Scope) -> View<G> {
let app_state = use_context::<AppState>(cx);
let items_text = || match app_state.todos_left() {
1 => "item",
_ => "items",
};
let has_completed_todos =
create_selector(cx, || app_state.todos_left() < app_state.todos.get().len());
let handle_clear_completed = |_| app_state.clear_completed();
view! { cx,
footer(class="footer") {
span(class="todo-count") {
strong { (app_state.todos_left()) }
span { " " (items_text()) " left" }
}
ul(class="filters") {
TodoFilter(filter=Filter::All)
TodoFilter(filter=Filter::Active)
TodoFilter(filter=Filter::Completed)
}
(if *has_completed_todos.get() {
view! { cx,
button(class="clear-completed", on:click=handle_clear_completed) {
"Clear completed"
}
}
} else {
view! { cx, }
})
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/todomvc/tera.rs | benchmarks/src/todomvc/tera.rs | use test::Bencher;
static TEMPLATE: &str = r#"<main>
<section class="todoapp">
<header class="header">
<h1>"todos"</h1>
<input class="new-todo" placeholder="What needs to be done? />
</header>
<section class="main" class={{ main_class }}>
<input id="toggle-all" class="toggle-all" type="checkbox"
checked={{ toggle_checked }}
/>
<label for="toggle-all">"Mark all as complete"</label>
<ul class="todo-list">
{% for todo in todos %}
<li
class={{ todo.class }}
>
<div class="view">
<input
class="toggle"
type="checkbox"
checked={{ todo.completed }}
/>
<label>
{{ todo.label }}
</label>
<button class="destroy"/>
</div>
{% if todo.editing %}
<input
class="edit"
value={{ todo.label }}
/>
{% endif %}
</li>
{% endfor %}
</ul>
</section>
{% if todos_empty %}
{% else %}
<footer class="footer">
<span class="todo-count">
<strong>{{ todos_remaining }}</strong>
{% if todos_remaining == 1 %}
item
{% else %}
items
{% endif %}
left
</span>
<ul class="filters">
{% if mode_all %}
<li><a href="/" class="selected">All</a></li>
{% else %}
<li><a href="/">All</a></li>
{% endif %}
{% if mode_active %}
<li><a href="/active" class="selected">Active</a></li>
{% else %}
<li><a href="/active">Active</a></li>
{% endif %}
{% if mode_completed %}
<li><a href="/completed" class="selected">Completed</a></li>
{% else %}
<li><a href="/completed">Completed</a></li>
{% endif %}
</ul>
{% if todos_completed > 0 %}
<button
class="clear-completed hidden"
>
Clear completed
</button>
{% endif %}
</footer>
{% endif %}
</section>
<footer class="info">
<p>"Double-click to edit a todo"</p>
<p>"Created by "<a href="http://todomvc.com">"Greg Johnston"</a></p>
<p>"Part of "<a href="http://todomvc.com">"TodoMVC"</a></p>
</footer>
</main>"#;
#[bench]
fn tera_todomvc_ssr(b: &mut Bencher) {
use serde::{Deserialize, Serialize};
use tera::*;
static LazyLock<TERA>: Tera = LazyLock( || {
let mut tera = Tera::default();
tera.add_raw_templates(vec![("template.html", TEMPLATE)]).unwrap();
tera
});
#[derive(Serialize, Deserialize)]
struct Todo {
label: String,
completed: bool,
editing: bool,
class: String,
}
b.iter(|| {
let mut ctx = Context::new();
let todos = Vec::<Todo>::new();
let remaining = todos.iter().filter(|todo| !todo.completed).count();
let completed = todos.iter().filter(|todo| todo.completed).count();
ctx.insert("todos", &todos);
ctx.insert("main_class", &if todos.is_empty() { "hidden" } else { "" });
ctx.insert("toggle_checked", &(remaining > 0));
ctx.insert("todos_remaining", &remaining);
ctx.insert("todos_completed", &completed);
ctx.insert("todos_empty", &todos.is_empty());
ctx.insert("mode_all", &true);
ctx.insert("mode_active", &false);
ctx.insert("mode_selected", &false);
let _ = TERA.render("template.html", &ctx).unwrap();
});
}
#[bench]
fn tera_todomvc_ssr_1000(b: &mut Bencher) {
use serde::{Deserialize, Serialize};
use tera::*;
static TERA: LazyLock<Tera> = LazyLock::new(|| {
let mut tera = Tera::default();
tera.add_raw_templates(vec![("template.html", TEMPLATE)]).unwrap();
tera
});
#[derive(Serialize, Deserialize)]
struct Todo {
id: usize,
label: String,
completed: bool,
editing: bool,
class: String,
}
b.iter(|| {
let mut ctx = Context::new();
let todos = (0..1000)
.map(|id| Todo {
id,
label: format!("Todo #{id}"),
completed: false,
editing: false,
class: "todo".to_string(),
})
.collect::<Vec<_>>();
let remaining = todos.iter().filter(|todo| !todo.completed).count();
let completed = todos.iter().filter(|todo| todo.completed).count();
ctx.insert("todos", &todos);
ctx.insert("main_class", &if todos.is_empty() { "hidden" } else { "" });
ctx.insert("toggle_checked", &(remaining > 0));
ctx.insert("todos_remaining", &remaining);
ctx.insert("todos_completed", &completed);
ctx.insert("todos_empty", &todos.is_empty());
ctx.insert("mode_all", &true);
ctx.insert("mode_active", &false);
ctx.insert("mode_selected", &false);
let _ = TERA.render("template.html", &ctx).unwrap();
});
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/todomvc/mod.rs | benchmarks/src/todomvc/mod.rs | use test::Bencher;
mod leptos;
mod sycamore;
mod tachys;
mod tera;
mod yew;
#[bench]
fn leptos_todomvc_ssr(b: &mut Bencher) {
use ::leptos::*;
let runtime = create_runtime();
b.iter(|| {
use crate::todomvc::leptos::*;
let html = ::leptos::ssr::render_to_string(|| {
view! { <TodoMVC todos=Todos::new()/> }
});
assert!(html.len() > 1);
});
runtime.dispose();
}
#[bench]
fn tachys_todomvc_ssr(b: &mut Bencher) {
use ::leptos::*;
let runtime = create_runtime();
b.iter(|| {
use crate::todomvc::tachys::*;
use tachydom::view::{Render, RenderHtml};
let rendered = TodoMVC(Todos::new()).to_html();
assert_eq!(
rendered,
"<main><section class=\"todoapp\"><header class=\"header\"><h1>todos</h1><input placeholder=\"What needs to be done?\" autofocus class=\"new-todo\"></header><section class=\"main hidden\"><input id=\"toggle-all\" type=\"checkbox\" class=\"toggle-all\"><label for=\"toggle-all\">Mark all as complete</label><ul class=\"todo-list\"></ul></section><footer class=\"footer hidden\"><span class=\"todo-count\"><strong>0</strong><!> items<!> left</span><ul class=\"filters\"><li><a href=\"#/\" class=\"selected selected\">All</a></li><li><a href=\"#/active\" class=\"\">Active</a></li><li><a href=\"#/completed\" class=\"\">Completed</a></li></ul><button class=\"clear-completed hidden hidden\">Clear completed</button></footer></section><footer class=\"info\"><p>Double-click to edit a todo</p><p>Created by <a href=\"http://todomvc.com\">Greg Johnston</a></p><p>Part of <a href=\"http://todomvc.com\">TodoMVC</a></p></footer></main>" );
});
runtime.dispose();
}
#[bench]
fn sycamore_todomvc_ssr(b: &mut Bencher) {
use self::sycamore::*;
use ::sycamore::{prelude::*, *};
b.iter(|| {
_ = create_scope(|cx| {
let rendered = render_to_string(|cx| {
view! {
cx,
App()
}
});
assert!(rendered.len() > 1);
});
});
}
#[bench]
fn yew_todomvc_ssr(b: &mut Bencher) {
use self::yew::*;
use ::yew::{prelude::*, ServerRenderer};
b.iter(|| {
tokio_test::block_on(async {
let renderer = ServerRenderer::<App>::new();
let rendered = renderer.render().await;
assert!(rendered.len() > 1);
});
});
}
#[bench]
fn leptos_todomvc_ssr_with_1000(b: &mut Bencher) {
b.iter(|| {
use self::leptos::*;
use ::leptos::*;
let html = ::leptos::ssr::render_to_string(|| {
view! {
<TodoMVC todos=Todos::new_with_1000()/>
}
});
assert!(html.len() > 1);
});
}
#[bench]
fn tachys_todomvc_ssr_with_1000(b: &mut Bencher) {
use ::leptos::*;
let runtime = create_runtime();
b.iter(|| {
use crate::todomvc::tachys::*;
use tachydom::view::{Render, RenderHtml};
let rendered = TodoMVC(Todos::new_with_1000()).to_html();
assert!(rendered.len() > 20_000)
});
runtime.dispose();
}
#[bench]
fn sycamore_todomvc_ssr_with_1000(b: &mut Bencher) {
use self::sycamore::*;
use ::sycamore::{prelude::*, *};
b.iter(|| {
_ = create_scope(|cx| {
let rendered = render_to_string(|cx| {
view! {
cx,
AppWith1000()
}
});
assert!(rendered.len() > 1);
});
});
}
#[bench]
fn yew_todomvc_ssr_with_1000(b: &mut Bencher) {
use self::yew::*;
use ::yew::{prelude::*, ServerRenderer};
b.iter(|| {
tokio_test::block_on(async {
let renderer = ServerRenderer::<AppWith1000>::new();
let rendered = renderer.render().await;
assert!(rendered.len() > 1);
});
});
}
#[bench]
fn tera_todomvc_ssr(b: &mut Bencher) {
use ::leptos::*;
let runtime = create_runtime();
b.iter(|| {
use crate::todomvc::leptos::*;
let html = ::leptos::ssr::render_to_string(|| {
view! { <TodoMVC todos=Todos::new()/> }
});
assert!(html.len() > 1);
});
runtime.dispose();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/benchmarks/src/todomvc/tachys.rs | benchmarks/src/todomvc/tachys.rs | pub use leptos_reactive::*;
use miniserde::*;
use tachy_maccy::view;
use tachydom::{
html::{
attribute::global::{ClassAttribute, GlobalAttributes, OnAttribute},
element::ElementChild,
},
renderer::dom::Dom,
view::{keyed::keyed, Render, RenderHtml},
};
use wasm_bindgen::JsCast;
use web_sys::HtmlInputElement;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Todos(pub Vec<Todo>);
const STORAGE_KEY: &str = "todos-leptos";
impl Todos {
pub fn new() -> Self {
Self(vec![])
}
pub fn new_with_1000() -> Self {
let todos = (0..1000)
.map(|id| Todo::new(id, format!("Todo #{id}")))
.collect();
Self(todos)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn add(&mut self, todo: Todo) {
self.0.push(todo);
}
pub fn remove(&mut self, id: usize) {
self.0.retain(|todo| todo.id != id);
}
pub fn remaining(&self) -> usize {
self.0.iter().filter(|todo| !(todo.completed)()).count()
}
pub fn completed(&self) -> usize {
self.0.iter().filter(|todo| (todo.completed)()).count()
}
pub fn toggle_all(&self) {
// if all are complete, mark them all active instead
if self.remaining() == 0 {
for todo in &self.0 {
if todo.completed.get() {
(todo.set_completed)(false);
}
}
}
// otherwise, mark them all complete
else {
for todo in &self.0 {
(todo.set_completed)(true);
}
}
}
fn clear_completed(&mut self) {
self.0.retain(|todo| !todo.completed.get());
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Todo {
pub id: usize,
pub title: ReadSignal<String>,
pub set_title: WriteSignal<String>,
pub completed: ReadSignal<bool>,
pub set_completed: WriteSignal<bool>,
}
impl Todo {
pub fn new(id: usize, title: String) -> Self {
Self::new_with_completed(id, title, false)
}
pub fn new_with_completed(
id: usize,
title: String,
completed: bool,
) -> Self {
let (title, set_title) = create_signal(title);
let (completed, set_completed) = create_signal(completed);
Self {
id,
title,
set_title,
completed,
set_completed,
}
}
pub fn toggle(&self) {
self.set_completed
.update(|completed| *completed = !*completed);
}
}
const ESCAPE_KEY: u32 = 27;
const ENTER_KEY: u32 = 13;
pub fn TodoMVC(todos: Todos) -> impl Render<Dom> + RenderHtml<Dom> {
let mut next_id = todos
.0
.iter()
.map(|todo| todo.id)
.max()
.map(|last| last + 1)
.unwrap_or(0);
let (todos, set_todos) = create_signal(todos);
provide_context(set_todos);
let (mode, set_mode) = create_signal(Mode::All);
let add_todo = move |ev: web_sys::KeyboardEvent| {
todo!()
/* let target = event_target::<HtmlInputElement>(&ev);
ev.stop_propagation();
let key_code = ev.unchecked_ref::<web_sys::KeyboardEvent>().key_code();
if key_code == ENTER_KEY {
let title = event_target_value(&ev);
let title = title.trim();
if !title.is_empty() {
let new = Todo::new(next_id, title.to_string());
set_todos.update(|t| t.add(new));
next_id += 1;
target.set_value("");
}
} */
};
let filtered_todos = create_memo::<Vec<Todo>>(move |_| {
todos.with(|todos| match mode.get() {
Mode::All => todos.0.to_vec(),
Mode::Active => todos
.0
.iter()
.filter(|todo| !todo.completed.get())
.cloned()
.collect(),
Mode::Completed => todos
.0
.iter()
.filter(|todo| todo.completed.get())
.cloned()
.collect(),
})
});
// effect to serialize to JSON
// this does reactive reads, so it will automatically serialize on any relevant change
create_effect(move |_| {
()
/* if let Ok(Some(storage)) = window().local_storage() {
let objs = todos
.get()
.0
.iter()
.map(TodoSerialized::from)
.collect::<Vec<_>>();
let json = json::to_string(&objs);
if storage.set_item(STORAGE_KEY, &json).is_err() {
log::error!("error while trying to set item in localStorage");
}
} */
});
view! {
<main>
<section class="todoapp">
<header class="header">
<h1>"todos"</h1>
<input
class="new-todo"
placeholder="What needs to be done?"
autofocus
/>
</header>
<section class="main" class:hidden=move || todos.with(|t| t.is_empty())>
<input
id="toggle-all"
class="toggle-all"
r#type="checkbox"
//prop:checked=move || todos.with(|t| t.remaining() > 0)
on:input=move |_| set_todos.update(|t| t.toggle_all())
/>
<label r#for="toggle-all">"Mark all as complete"</label>
<ul class="todo-list">
{move || {
keyed(filtered_todos.get(), |todo| todo.id, Todo)
}}
</ul>
</section>
<footer class="footer" class:hidden=move || todos.with(|t| t.is_empty())>
<span class="todo-count">
<strong>{move || todos.with(|t| t.remaining().to_string())}</strong>
{move || if todos.with(|t| t.remaining()) == 1 { " item" } else { " items" }}
" left"
</span>
<ul class="filters">
<li>
<a
href="#/"
class="selected"
class:selected=move || mode() == Mode::All
>
"All"
</a>
</li>
<li>
<a href="#/active" class:selected=move || mode() == Mode::Active>
"Active"
</a>
</li>
<li>
<a href="#/completed" class:selected=move || mode() == Mode::Completed>
"Completed"
</a>
</li>
</ul>
<button
class="clear-completed hidden"
class:hidden=move || todos.with(|t| t.completed() == 0)
on:click=move |_| set_todos.update(|t| t.clear_completed())
>
"Clear completed"
</button>
</footer>
</section>
<footer class="info">
<p>"Double-click to edit a todo"</p>
<p>"Created by " <a href="http://todomvc.com">"Greg Johnston"</a></p>
<p>"Part of " <a href="http://todomvc.com">"TodoMVC"</a></p>
</footer>
</main>
}
}
pub fn Todo(todo: Todo) -> impl Render<Dom> + RenderHtml<Dom> {
let (editing, set_editing) = create_signal(false);
let set_todos = use_context::<WriteSignal<Todos>>().unwrap();
//let input = NodeRef::new();
let save = move |value: &str| {
let value = value.trim();
if value.is_empty() {
set_todos.update(|t| t.remove(todo.id));
} else {
(todo.set_title)(value.to_string());
}
set_editing(false);
};
view! {
<li class="todo" class:editing=editing class:completed=move || (todo.completed)()>
/* <div class="view">
<input class="toggle" r#type="checkbox"/>
<label on:dblclick=move |_| set_editing(true)>{move || todo.title.get()}</label>
<button
class="destroy"
on:click=move |_| set_todos.update(|t| t.remove(todo.id))
></button>
</div>
{move || {
editing()
.then(|| {
view! {
<input
class="edit"
class:hidden=move || !(editing)()
/>
}
})
}} */
</li>
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Active,
Completed,
All,
}
impl Default for Mode {
fn default() -> Self {
Mode::All
}
}
pub fn route(hash: &str) -> Mode {
match hash {
"/active" => Mode::Active,
"/completed" => Mode::Completed,
_ => Mode::All,
}
}
#[derive(Serialize, Deserialize)]
pub struct TodoSerialized {
pub id: usize,
pub title: String,
pub completed: bool,
}
impl TodoSerialized {
pub fn into_todo(self) -> Todo {
Todo::new_with_completed(self.id, self.title, self.completed)
}
}
impl From<&Todo> for TodoSerialized {
fn from(todo: &Todo) -> Self {
Self {
id: todo.id,
title: todo.title.get(),
completed: (todo.completed)(),
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/field.rs | reactive_stores/src/field.rs | use crate::{
arc_field::{StoreFieldReader, StoreFieldWriter},
path::{StorePath, StorePathSegment},
ArcField, ArcStore, AtIndex, AtKeyed, DerefedField, KeyMap, KeyedSubfield,
Store, StoreField, StoreFieldTrigger, Subfield,
};
use reactive_graph::{
owner::{ArenaItem, Storage, SyncStorage},
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
};
use std::{
fmt::Debug,
hash::Hash,
ops::{Deref, DerefMut, IndexMut},
panic::Location,
};
/// Wraps access to a single field of type `T`.
///
/// This can be used to erase the chain of field-accessors, to make it easier to pass this into
/// another component or function without needing to specify the full type signature.
pub struct Field<T, S = SyncStorage>
where
T: 'static,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: ArenaItem<ArcField<T>, S>,
}
impl<T, S> Debug for Field<T, S>
where
T: 'static,
S: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("Field");
#[cfg(any(debug_assertions, leptos_debuginfo))]
let f = f.field("defined_at", &self.defined_at);
f.field("inner", &self.inner).finish()
}
}
impl<T, S> StoreField for Field<T, S>
where
S: Storage<ArcField<T>>,
{
type Value = T;
type Reader = StoreFieldReader<T>;
type Writer = StoreFieldWriter<T>;
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
self.inner
.try_get_value()
.map(|inner| inner.get_trigger(path))
.unwrap_or_default()
}
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
self.inner
.try_get_value()
.map(|inner| inner.get_trigger_unkeyed(path))
.unwrap_or_default()
}
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.try_get_value()
.map(|inner| inner.path().into_iter().collect::<Vec<_>>())
.unwrap_or_default()
}
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.try_get_value()
.map(|inner| inner.path_unkeyed().into_iter().collect::<Vec<_>>())
.unwrap_or_default()
}
fn reader(&self) -> Option<Self::Reader> {
self.inner.try_get_value().and_then(|inner| inner.reader())
}
fn writer(&self) -> Option<Self::Writer> {
self.inner.try_get_value().and_then(|inner| inner.writer())
}
fn keys(&self) -> Option<KeyMap> {
self.inner.try_get_value().and_then(|n| n.keys())
}
}
impl<T, S> From<Store<T, S>> for Field<T, S>
where
T: 'static,
S: Storage<ArcStore<T>> + Storage<ArcField<T>>,
{
#[track_caller]
fn from(value: Store<T, S>) -> Self {
Field {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value.into()),
}
}
}
impl<T, S> From<ArcField<T>> for Field<T, S>
where
T: 'static,
S: Storage<ArcField<T>>,
{
#[track_caller]
fn from(value: ArcField<T>) -> Self {
Field {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value),
}
}
}
impl<T, S> From<ArcStore<T>> for Field<T, S>
where
T: Send + Sync + 'static,
S: Storage<ArcStore<T>> + Storage<ArcField<T>>,
{
#[track_caller]
fn from(value: ArcStore<T>) -> Self {
Field {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value.into()),
}
}
}
impl<Inner, Prev, T, S> From<Subfield<Inner, Prev, T>> for Field<T, S>
where
T: Send + Sync,
S: Storage<ArcField<T>>,
Subfield<Inner, Prev, T>: Clone,
Inner: StoreField<Value = Prev> + Send + Sync + 'static,
Prev: 'static,
{
#[track_caller]
fn from(value: Subfield<Inner, Prev, T>) -> Self {
Field {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value.into()),
}
}
}
impl<Inner, T> From<DerefedField<Inner>> for Field<T>
where
Inner: Clone + StoreField + Send + Sync + 'static,
Inner::Value: Deref<Target = T> + DerefMut,
T: Sized + 'static,
{
#[track_caller]
fn from(value: DerefedField<Inner>) -> Self {
Field {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value.into()),
}
}
}
impl<Inner, Prev, S> From<AtIndex<Inner, Prev>> for Field<Prev::Output, S>
where
AtIndex<Inner, Prev>: Clone,
S: Storage<ArcField<Prev::Output>>,
Inner: StoreField<Value = Prev> + Send + Sync + 'static,
Prev: IndexMut<usize> + Send + Sync + 'static,
Prev::Output: Sized + Send + Sync,
{
#[track_caller]
fn from(value: AtIndex<Inner, Prev>) -> Self {
Field {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value.into()),
}
}
}
impl<Inner, Prev, K, T, S> From<AtKeyed<Inner, Prev, K, T>>
for Field<T::Output, S>
where
S: Storage<ArcField<T::Output>>,
AtKeyed<Inner, Prev, K, T>: Clone,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev> + Send + Sync + 'static,
Prev: 'static,
T: IndexMut<usize> + 'static,
T::Output: Sized,
{
#[track_caller]
fn from(value: AtKeyed<Inner, Prev, K, T>) -> Self {
Field {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(value.into()),
}
}
}
impl<T, S> Clone for Field<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Copy for Field<T, S> {}
impl<T, S> DefinedAt for Field<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> Notify for Field<T, S>
where
S: Storage<ArcField<T>>,
{
fn notify(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.notify();
}
}
}
impl<T, S> Track for Field<T, S>
where
S: Storage<ArcField<T>>,
{
fn track(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.track();
}
}
}
impl<T, S> ReadUntracked for Field<T, S>
where
S: Storage<ArcField<T>>,
{
type Value = StoreFieldReader<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 Field<T> {
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.inner.try_get_value().and_then(|inner| (inner.write)())
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.inner.try_get_value().and_then(|inner| {
let mut guard = (inner.write)()?;
guard.untrack();
Some(guard)
})
}
}
impl<T, S> IsDisposed for Field<T, S> {
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_stores/src/subfield.rs | reactive_stores/src/subfield.rs | use crate::{
path::{StorePath, StorePathSegment},
store_field::StoreField,
KeyMap, StoreFieldTrigger,
};
use reactive_graph::{
signal::{
guards::{Mapped, MappedMut, WriteGuard},
ArcTrigger,
},
traits::{
DefinedAt, Get as _, IsDisposed, Notify, ReadUntracked, Track,
UntrackableGuard, Write,
},
wrappers::read::Signal,
};
use std::{iter, marker::PhantomData, ops::DerefMut, panic::Location};
/// Accesses a single field of a reactive structure.
#[derive(Debug)]
pub struct Subfield<Inner, Prev, T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
path_segment: StorePathSegment,
inner: Inner,
read: fn(&Prev) -> &T,
write: fn(&mut Prev) -> &mut T,
ty: PhantomData<T>,
}
impl<Inner, Prev, T> Clone for Subfield<Inner, Prev, T>
where
Inner: Clone,
{
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
path_segment: self.path_segment,
inner: self.inner.clone(),
read: self.read,
write: self.write,
ty: self.ty,
}
}
}
impl<Inner, Prev, T> Copy for Subfield<Inner, Prev, T> where Inner: Copy {}
impl<Inner, Prev, T> Subfield<Inner, Prev, T> {
/// Creates an accessor for a single field of the inner structure.
#[track_caller]
pub fn new(
inner: Inner,
path_segment: StorePathSegment,
read: fn(&Prev) -> &T,
write: fn(&mut Prev) -> &mut T,
) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner,
path_segment,
read,
write,
ty: PhantomData,
}
}
}
impl<Inner, Prev, T> StoreField for Subfield<Inner, Prev, T>
where
Inner: StoreField<Value = Prev>,
Prev: 'static,
{
type Value = T;
type Reader = Mapped<Inner::Reader, T>;
type Writer = MappedMut<WriteGuard<Vec<ArcTrigger>, Inner::Writer>, T>;
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.path()
.into_iter()
.chain(iter::once(self.path_segment))
}
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.path_unkeyed()
.into_iter()
.chain(iter::once(self.path_segment))
}
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger(path)
}
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger_unkeyed(path)
}
fn reader(&self) -> Option<Self::Reader> {
let inner = self.inner.reader()?;
Some(Mapped::new_with_guard(inner, self.read))
}
fn writer(&self) -> Option<Self::Writer> {
let mut parent = self.inner.writer()?;
// we will manually include all the parent and ancestor `children` triggers
// in triggers_for_current_path() below. we want to untrack the parent writer
// so that it doesn't notify on the parent's `this` trigger, which would notify our
// siblings too
parent.untrack();
let triggers = self.triggers_for_current_path();
let guard = WriteGuard::new(triggers, parent);
Some(MappedMut::new(guard, self.read, self.write))
}
#[inline(always)]
fn keys(&self) -> Option<KeyMap> {
self.inner.keys()
}
#[track_caller]
fn track_field(&self) {
let mut full_path = self.path().into_iter().collect::<StorePath>();
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.track();
trigger.children.track();
// tracks `this` for all ancestors: i.e., it will track any change that is made
// directly to one of its ancestors, but not a change made to a *child* of an ancestor
// (which would end up with every subfield tracking its own siblings, because they are
// children of its parent)
while !full_path.is_empty() {
full_path.pop();
let inner = self.get_trigger(full_path.clone());
inner.this.track();
}
}
}
impl<Inner, Prev, T> DefinedAt for Subfield<Inner, Prev, T>
where
Inner: StoreField<Value = Prev>,
{
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<Inner, Prev, T> IsDisposed for Subfield<Inner, Prev, T>
where
Inner: IsDisposed,
{
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<Inner, Prev, T> Notify for Subfield<Inner, Prev, T>
where
Inner: StoreField<Value = Prev>,
Prev: 'static,
{
#[track_caller]
fn notify(&self) {
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.notify();
trigger.children.notify();
}
}
impl<Inner, Prev, T> Track for Subfield<Inner, Prev, T>
where
Inner: StoreField<Value = Prev> + Track + 'static,
Prev: 'static,
T: 'static,
{
#[track_caller]
fn track(&self) {
self.track_field();
}
}
impl<Inner, Prev, T> ReadUntracked for Subfield<Inner, Prev, T>
where
Inner: StoreField<Value = Prev>,
Prev: 'static,
{
type Value = <Self as StoreField>::Reader;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.reader()
}
}
impl<Inner, Prev, T> Write for Subfield<Inner, Prev, T>
where
T: 'static,
Inner: StoreField<Value = Prev>,
Prev: 'static,
{
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.writer()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.writer().map(|mut writer| {
writer.untrack();
writer
})
}
}
impl<Inner, Prev, T> From<Subfield<Inner, Prev, T>> for Signal<T>
where
Inner: StoreField<Value = Prev> + Track + Send + Sync + 'static,
Prev: 'static,
T: Send + Sync + Clone + 'static,
{
fn from(subfield: Subfield<Inner, Prev, T>) -> Self {
Signal::derive(move || subfield.get())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/path.rs | reactive_stores/src/path.rs | /// The path of a field within some store.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct StorePath(Vec<StorePathSegment>);
impl IntoIterator for StorePath {
type Item = StorePathSegment;
type IntoIter = std::vec::IntoIter<StorePathSegment>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a StorePath {
type Item = &'a StorePathSegment;
type IntoIter = std::slice::Iter<'a, StorePathSegment>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl From<Vec<StorePathSegment>> for StorePath {
fn from(value: Vec<StorePathSegment>) -> Self {
Self(value)
}
}
impl StorePath {
/// Creates a new path.
pub fn new() -> Self {
Self(Vec::new())
}
/// Creates a new path with storage capacity for `capacity` segments.
pub fn with_capacity(capacity: usize) -> Self {
Self(Vec::with_capacity(capacity))
}
/// Adds a new segment to the path.
pub fn push(&mut self, segment: impl Into<StorePathSegment>) {
self.0.push(segment.into());
}
/// Removes a segment from the path and returns it.
pub fn pop(&mut self) -> Option<StorePathSegment> {
self.0.pop()
}
/// Updates the last segment in the place in place.
pub fn replace_last(&mut self, segment: impl Into<StorePathSegment>) {
if let Some(last) = self.0.last_mut() {
*last = segment.into();
}
}
/// Returns `true` if the path contains no elements.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the number of elements in the path.
pub fn len(&self) -> usize {
self.0.len()
}
}
/// One segment of a [`StorePath`].
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct StorePathSegment(pub(crate) usize);
impl From<usize> for StorePathSegment {
fn from(value: usize) -> Self {
Self(value)
}
}
impl From<&usize> for StorePathSegment {
fn from(value: &usize) -> Self {
Self(*value)
}
}
impl FromIterator<StorePathSegment> for StorePath {
fn from_iter<T: IntoIterator<Item = StorePathSegment>>(iter: T) -> Self {
Self(Vec::from_iter(iter))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/lib.rs | reactive_stores/src/lib.rs | #![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Stores are a primitive for creating deeply-nested reactive state, based on [`reactive_graph`].
//!
//! Reactive signals allow you to define atomic units of reactive state. However, signals are
//! imperfect as a mechanism for tracking reactive change in structs or collections, because
//! they do not allow you to track access to individual struct fields or individual items in a
//! collection, rather than the struct as a whole or the collection as a whole. Reactivity for
//! individual fields can be achieved by creating a struct of signals, but this has issues; it
//! means that a struct is no longer a plain data structure, but requires wrappers on each field.
//!
//! Stores attempt to solve this problem by allowing arbitrarily-deep access to the fields of some
//! data structure, while still maintaining fine-grained reactivity.
//!
//! The [`Store`](macro@Store) macro adds getters and setters for the fields of a struct. Call those getters or
//! setters on a reactive [`Store`](struct@Store) or [`ArcStore`], or to a subfield, gives you
//! access to a reactive subfield. This value of this field can be accessed via the ordinary signal
//! traits (`Get`, `Set`, and so on).
//!
//! The [`Patch`](macro@Patch) macro allows you to annotate a struct such that stores and fields have a
//! [`.patch()`](Patch::patch) method, which allows you to provide an entirely new value, but only
//! notify fields that have changed.
//!
//! Updating a field will notify its parents and children, but not its siblings.
//!
//! Stores can therefore
//! 1) work with plain Rust data types, and
//! 2) provide reactive access to individual fields
//!
//! ### Example
//!
//! ```rust
//! use reactive_graph::{
//! effect::Effect,
//! traits::{Read, Write},
//! };
//! use reactive_stores::{Patch, Store};
//!
//! #[derive(Debug, Store, Patch, Default)]
//! struct Todos {
//! user: String,
//! todos: Vec<Todo>,
//! }
//!
//! #[derive(Debug, Store, Patch, Default)]
//! struct Todo {
//! label: String,
//! completed: bool,
//! }
//!
//! let store = Store::new(Todos {
//! user: "Alice".to_string(),
//! todos: Vec::new(),
//! });
//!
//! # if false { // don't run effect in doctests
//! Effect::new(move |_| {
//! // you can access individual store fields with a getter
//! println!("user: {:?}", &*store.user().read());
//! });
//! # }
//!
//! // won't notify the effect that listens to `user`
//! store.todos().write().push(Todo {
//! label: "Test".to_string(),
//! completed: false,
//! });
//! ```
//! ### Generated traits
//! The [`Store`](macro@Store) macro generates traits for each `struct` to which it is applied. When working
//! within a single file or module, this is not an issue. However, when working with multiple modules
//! or files, one needs to `use` the generated traits. The general pattern is that for each `struct`
//! named `Foo`, the macro generates a trait named `FooStoreFields`. For example:
//! ```rust
//! pub mod foo {
//! use reactive_stores::Store;
//! #[derive(Store)]
//! pub struct Foo {
//! field: i32,
//! }
//! }
//!
//! pub mod user {
//! use leptos::prelude::*;
//! use reactive_stores::Field;
//! // Using FooStore fields here.
//! use crate::foo::{ Foo, FooStoreFields };
//!
//! #[component]
//! pub fn UseFoo(foo: Field<Foo>) {
//! // Without FooStoreFields, foo.field() would fail to compile.
//! println!("field: {}", foo.field().read());
//! }
//! }
//!
//! # fn main() {
//! # }
//! ```
//! ### Additional field types
//!
//! Most of the time, your structs will have fields as in the example above: the struct is comprised
//! of primitive types, builtin types like [String], or other structs that implement [Store](struct@Store) or [Field].
//! However, there are some special cases that require some additional understanding.
//!
//! #### Option
//! [`Option<T>`](std::option::Option) behaves pretty much as you would expect, utilizing [.is_some()](std::option::Option::is_some)
//! and [.is_none()](std::option::Option::is_none) to check the value and [.unwrap()](OptionStoreExt::unwrap) method to access the inner value. The [OptionStoreExt]
//! trait is required to use the [.unwrap()](OptionStoreExt::unwrap) method. Here is a quick example:
//! ```rust
//! // Including the trait OptionStoreExt here is required to use unwrap()
//! use reactive_stores::{OptionStoreExt, Store};
//! use reactive_graph::traits::{Get, Read};
//!
//! #[derive(Store)]
//! struct StructWithOption {
//! opt_field: Option<i32>,
//! }
//!
//! fn describe(store: &Store<StructWithOption>) -> String {
//! if store.opt_field().read().is_some() {
//! // Note here we need to use OptionStoreExt or unwrap() would not compile
//! format!("store has a value {}", store.opt_field().unwrap().get())
//! } else {
//! format!("store has no value")
//! }
//! }
//! let none_store = Store::new(StructWithOption { opt_field: None });
//! let some_store = Store::new(StructWithOption { opt_field: Some(42)});
//!
//! assert_eq!(describe(&none_store), "store has no value");
//! assert_eq!(describe(&some_store), "store has a value 42");
//! ```
//! #### Vec
//! [`Vec<T>`](std::vec::Vec) requires some special treatment when trying to access
//! elements of the vector directly. Use the [StoreFieldIterator::at_unkeyed()] method to
//! access a particular value in a [struct@Store] or [Field] for a [std::vec::Vec]. For example:
//! ```rust
//! # use reactive_stores::Store;
//! // Needed to use at_unkeyed() on Vec
//! use reactive_stores::StoreFieldIter;
//! use reactive_stores::StoreFieldIterator;
//! use reactive_graph::traits::Read;
//! use reactive_graph::traits::Get;
//!
//! #[derive(Store)]
//! struct StructWithVec {
//! vec_field: Vec<i32>,
//! }
//!
//! let store = Store::new(StructWithVec { vec_field: vec![1, 2, 3] });
//!
//! assert_eq!(store.vec_field().at_unkeyed(0).get(), 1);
//! assert_eq!(store.vec_field().at_unkeyed(1).get(), 2);
//! assert_eq!(store.vec_field().at_unkeyed(2).get(), 3);
//! ```
//! #### Enum
//! Enumerated types behave a bit differently as the [`Store`](macro@Store) macro builds underlying traits instead of alternate
//! enumerated structures. Each element in an `Enum` generates methods to access it in the store: a
//! method with the name of the field gives a boolean if the `Enum` is that variant, and possible accessor
//! methods for anonymous fields of that variant. For example:
//! ```rust
//! use reactive_stores::Store;
//! use reactive_graph::traits::{Read, Get};
//!
//! #[derive(Store)]
//! enum Choices {
//! First,
//! Second(String),
//! }
//!
//! let choice_one = Store::new(Choices::First);
//! let choice_two = Store::new(Choices::Second("hello".to_string()));
//!
//! assert!(choice_one.first());
//! assert!(!choice_one.second());
//! // Note the use of the accessor method here .second_0()
//! assert_eq!(choice_two.second_0().unwrap().get(), "hello");
//! ```
//! #### Box
//! [`Box<T>`](std::boxed::Box) also requires some special treatment in how you dereference elements of the Box, especially
//! when trying to build a recursive data structure. [DerefField](trait@DerefField) provides a [.deref_value()](DerefField::deref_field) method to access
//! the inner value. For example:
//! ```rust
//! // Note here we need to use DerefField to use deref_field() and OptionStoreExt to use unwrap()
//! use reactive_stores::{Store, DerefField, OptionStoreExt};
//! use reactive_graph::traits::{ Read, Get };
//!
//! #[derive(Store)]
//! struct List {
//! value: i32,
//! #[store]
//! child: Option<Box<List>>,
//! }
//!
//! let tree = Store::new(List {
//! value: 1,
//! child: Some(Box::new(List { value: 2, child: None })),
//! });
//!
//! assert_eq!(tree.child().unwrap().deref_field().value().get(), 2);
//! ```
//! ### Implementation Notes
//!
//! Every struct field can be understood as an index. For example, given the following definition
//! ```rust
//! # use reactive_stores::{Store, Patch};
//! #[derive(Debug, Store, Patch, Default)]
//! struct Name {
//! first: String,
//! last: String,
//! }
//! ```
//! We can think of `first` as `0` and `last` as `1`. This means that any deeply-nested field of a
//! struct can be described as a path of indices. So, for example:
//! ```rust
//! # use reactive_stores::{Store, Patch};
//! #[derive(Debug, Store, Patch, Default)]
//! struct User {
//! user: Name,
//! }
//!
//! #[derive(Debug, Store, Patch, Default)]
//! struct Name {
//! first: String,
//! last: String,
//! }
//! ```
//! Here, given a `User`, `first` can be understood as [`0`, `0`] and `last` is [`0`, `1`].
//!
//! This means we can implement a store as the combination of two things:
//! 1) An `Arc<RwLock<T>>` that holds the actual value
//! 2) A map from field paths to reactive "triggers," which are signals that have no value but
//! track reactivity
//!
//! Accessing a field via its getters returns an iterator-like data structure that describes how to
//! get to that subfield. Calling `.read()` returns a guard that dereferences to the value of that
//! field in the signal inner `Arc<RwLock<_>>`, and tracks the trigger that corresponds with its
//! path; calling `.write()` returns a writeable guard, and notifies that same trigger.
use reactive_graph::{
owner::{ArenaItem, LocalStorage, Storage, SyncStorage},
signal::{
guards::{Plain, ReadGuard, WriteGuard},
ArcTrigger,
},
traits::{
DefinedAt, Dispose, IsDisposed, Notify, ReadUntracked, Track,
UntrackableGuard, Write,
},
};
pub use reactive_stores_macro::{Patch, Store};
use rustc_hash::FxHashMap;
use std::{
any::Any,
fmt::Debug,
hash::Hash,
ops::DerefMut,
panic::Location,
sync::{Arc, RwLock},
};
mod arc_field;
mod deref;
mod field;
mod iter;
mod keyed;
mod len;
mod option;
mod patch;
mod path;
mod store_field;
mod subfield;
pub use arc_field::ArcField;
pub use deref::*;
pub use field::Field;
pub use iter::*;
pub use keyed::*;
pub use len::Len;
pub use option::*;
pub use patch::*;
pub use path::{StorePath, StorePathSegment};
pub use store_field::StoreField;
pub use subfield::Subfield;
#[derive(Debug, Default)]
struct TriggerMap(FxHashMap<StorePath, StoreFieldTrigger>);
/// The reactive trigger that can be used to track updates to a store field.
#[derive(Debug, Clone, Default)]
pub struct StoreFieldTrigger {
pub(crate) this: ArcTrigger,
pub(crate) children: ArcTrigger,
}
impl StoreFieldTrigger {
/// Creates a new trigger.
pub fn new() -> Self {
Self::default()
}
}
impl TriggerMap {
fn get_or_insert(&mut self, key: StorePath) -> StoreFieldTrigger {
if let Some(trigger) = self.0.get(&key) {
trigger.clone()
} else {
let new = StoreFieldTrigger::new();
self.0.insert(key, new.clone());
new
}
}
#[allow(unused)]
fn remove(&mut self, key: &StorePath) -> Option<StoreFieldTrigger> {
self.0.remove(key)
}
}
/// Manages the keys for a keyed field, including the ability to remove and reuse keys.
pub(crate) struct FieldKeys<K> {
spare_keys: Vec<StorePathSegment>,
current_key: usize,
keys: FxHashMap<K, (StorePathSegment, usize)>,
}
impl<K> FieldKeys<K>
where
K: Debug + Hash + PartialEq + Eq,
{
/// Creates a new set of keys.
pub fn new(from_keys: Vec<K>) -> Self {
let mut keys = FxHashMap::with_capacity_and_hasher(
from_keys.len(),
Default::default(),
);
for (idx, key) in from_keys.into_iter().enumerate() {
let segment = idx.into();
keys.insert(key, (segment, idx));
}
Self {
spare_keys: Vec::new(),
current_key: keys.len().saturating_sub(1),
keys,
}
}
}
impl<K> FieldKeys<K>
where
K: Hash + PartialEq + Eq,
{
fn get(&self, key: &K) -> Option<(StorePathSegment, usize)> {
self.keys.get(key).copied()
}
fn next_key(&mut self) -> StorePathSegment {
self.spare_keys.pop().unwrap_or_else(|| {
self.current_key += 1;
self.current_key.into()
})
}
fn update(
&mut self,
iter: impl IntoIterator<Item = K>,
) -> Vec<(usize, StorePathSegment)> {
let new_keys = iter
.into_iter()
.enumerate()
.map(|(idx, key)| (key, idx))
.collect::<FxHashMap<K, usize>>();
let mut index_keys = Vec::with_capacity(new_keys.len());
// remove old keys and recycle the slots
self.keys.retain(|key, old_entry| match new_keys.get(key) {
Some(idx) => {
old_entry.1 = *idx;
true
}
None => {
self.spare_keys.push(old_entry.0);
false
}
});
// add new keys
for (key, idx) in new_keys {
match self.keys.get(&key) {
Some((segment, idx)) => index_keys.push((*idx, *segment)),
None => {
let path = self.next_key();
self.keys.insert(key, (path, idx));
index_keys.push((idx, path));
}
}
}
index_keys
}
}
impl<K> Default for FieldKeys<K> {
fn default() -> Self {
Self {
spare_keys: Default::default(),
current_key: Default::default(),
keys: Default::default(),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
type HashMap<K, V> = Arc<dashmap::DashMap<K, V>>;
#[cfg(target_arch = "wasm32")]
type HashMap<K, V> = send_wrapper::SendWrapper<
std::rc::Rc<std::cell::RefCell<std::collections::HashMap<K, V>>>,
>;
/// A map of the keys for a keyed subfield.
#[derive(Clone)]
pub struct KeyMap(
HashMap<StorePath, Box<dyn Any + Send + Sync>>,
HashMap<(StorePath, usize), StorePathSegment>,
);
impl Default for KeyMap {
fn default() -> Self {
#[cfg(not(target_arch = "wasm32"))]
return Self(Default::default(), Default::default());
#[cfg(target_arch = "wasm32")]
return Self(
send_wrapper::SendWrapper::new(Default::default()),
send_wrapper::SendWrapper::new(Default::default()),
);
}
}
impl KeyMap {
fn with_field_keys<K, T>(
&self,
path: StorePath,
fun: impl FnOnce(&mut FieldKeys<K>) -> (T, Vec<(usize, StorePathSegment)>),
initialize: impl FnOnce() -> Vec<K>,
) -> Option<T>
where
K: Debug + Hash + PartialEq + Eq + Send + Sync + 'static,
{
let initial_keys = initialize();
#[cfg(not(target_arch = "wasm32"))]
let mut entry = self
.0
.entry(path.clone())
.or_insert_with(|| Box::new(FieldKeys::new(initial_keys)));
#[cfg(target_arch = "wasm32")]
let entry = if !self.0.borrow().contains_key(&path) {
Some(Box::new(FieldKeys::new(initial_keys)))
} else {
None
};
#[cfg(target_arch = "wasm32")]
let mut map = self.0.borrow_mut();
#[cfg(target_arch = "wasm32")]
let entry = map.entry(path.clone()).or_insert_with(|| entry.unwrap());
let entry = entry.downcast_mut::<FieldKeys<K>>()?;
let (result, new_keys) = fun(entry);
if !new_keys.is_empty() {
for (idx, segment) in new_keys {
#[cfg(not(target_arch = "wasm32"))]
self.1.insert((path.clone(), idx), segment);
#[cfg(target_arch = "wasm32")]
self.1.borrow_mut().insert((path.clone(), idx), segment);
}
}
Some(result)
}
fn contains_key(&self, key: &StorePath) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
self.0.contains_key(key)
}
#[cfg(target_arch = "wasm32")]
{
self.0.borrow_mut().contains_key(key)
}
}
fn get_key_for_index(
&self,
key: &(StorePath, usize),
) -> Option<StorePathSegment> {
#[cfg(not(target_arch = "wasm32"))]
{
self.1.get(key).as_deref().copied()
}
#[cfg(target_arch = "wasm32")]
{
self.1.borrow().get(key).as_deref().copied()
}
}
}
/// A reference-counted container for a reactive store.
///
/// The type `T` should be a struct that has been annotated with `#[derive(Store)]`.
///
/// This adds a getter method for each field to `Store<T>`, which allow accessing reactive versions
/// of each individual field of the struct.
pub struct ArcStore<T> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
pub(crate) value: Arc<RwLock<T>>,
signals: Arc<RwLock<TriggerMap>>,
keys: KeyMap,
}
impl<T> ArcStore<T> {
/// Creates a new store from the initial value.
pub fn new(value: T) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
value: Arc::new(RwLock::new(value)),
signals: Default::default(),
keys: Default::default(),
}
}
}
impl<T: Default> Default for ArcStore<T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T: Debug> Debug for ArcStore<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("ArcStore");
#[cfg(any(debug_assertions, leptos_debuginfo))]
let f = f.field("defined_at", &self.defined_at);
f.field("value", &self.value)
.field("signals", &self.signals)
.finish()
}
}
impl<T> Clone for ArcStore<T> {
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
value: Arc::clone(&self.value),
signals: Arc::clone(&self.signals),
keys: self.keys.clone(),
}
}
}
impl<T> DefinedAt for ArcStore<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> IsDisposed for ArcStore<T> {
#[inline(always)]
fn is_disposed(&self) -> bool {
false
}
}
impl<T> ReadUntracked for ArcStore<T>
where
T: 'static,
{
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> Write for ArcStore<T>
where
T: 'static,
{
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.writer()
.map(|writer| WriteGuard::new(self.clone(), writer))
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
let mut writer = self.writer()?;
writer.untrack();
Some(writer)
}
}
impl<T: 'static> Track for ArcStore<T> {
fn track(&self) {
self.track_field();
}
}
impl<T: 'static> Notify for ArcStore<T> {
fn notify(&self) {
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.notify();
trigger.children.notify();
}
}
/// An arena-allocated container for a reactive store.
///
/// The type `T` should be a struct that has been annotated with `#[derive(Store)]`.
///
/// This adds a getter method for each field to `Store<T>`, which allow accessing reactive versions
/// of each individual field of the struct.
///
/// This follows the same ownership rules as arena-allocated types like
/// [`RwSignal`](reactive_graph::signal::RwSignal).
pub struct Store<T, S = SyncStorage> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: ArenaItem<ArcStore<T>, S>,
}
impl<T> Store<T>
where
T: Send + Sync + 'static,
{
/// Creates a new store with the initial value.
pub fn new(value: T) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcStore::new(value)),
}
}
}
impl<T, S> PartialEq for Store<T, S> {
fn eq(&self, other: &Self) -> bool {
self.inner == other.inner
}
}
impl<T, S> Eq for Store<T, S> {}
impl<T> Store<T, LocalStorage>
where
T: 'static,
{
/// Creates a new store for a type that is `!Send`.
///
/// This pins the value to the current thread. Accessing it from any other thread will panic.
pub fn new_local(value: T) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: ArenaItem::new_with_storage(ArcStore::new(value)),
}
}
}
impl<T> Default for Store<T>
where
T: Default + Send + Sync + 'static,
{
fn default() -> Self {
Self::new(T::default())
}
}
impl<T> Default for Store<T, LocalStorage>
where
T: Default + 'static,
{
fn default() -> Self {
Self::new_local(T::default())
}
}
impl<T: Debug, S> Debug for Store<T, S>
where
S: Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("Store");
#[cfg(any(debug_assertions, leptos_debuginfo))]
let f = f.field("defined_at", &self.defined_at);
f.field("inner", &self.inner).finish()
}
}
impl<T, S> Clone for Store<T, S> {
fn clone(&self) -> Self {
*self
}
}
impl<T, S> Copy for Store<T, S> {}
impl<T, S> DefinedAt for Store<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 Store<T, S>
where
T: 'static,
{
#[inline(always)]
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<T, S> Dispose for Store<T, S>
where
T: 'static,
{
fn dispose(self) {
self.inner.dispose();
}
}
impl<T, S> ReadUntracked for Store<T, S>
where
T: 'static,
S: Storage<ArcStore<T>>,
{
type Value = ReadGuard<T, Plain<T>>;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.inner
.try_get_value()
.and_then(|inner| inner.try_read_untracked())
}
}
impl<T, S> Write for Store<T, S>
where
T: 'static,
S: Storage<ArcStore<T>>,
{
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.writer().map(|writer| WriteGuard::new(*self, writer))
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
let mut writer = self.writer()?;
writer.untrack();
Some(writer)
}
}
impl<T, S> Track for Store<T, S>
where
T: 'static,
S: Storage<ArcStore<T>>,
{
fn track(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.track();
}
}
}
impl<T, S> Notify for Store<T, S>
where
T: 'static,
S: Storage<ArcStore<T>>,
{
fn notify(&self) {
if let Some(inner) = self.inner.try_get_value() {
inner.notify();
}
}
}
impl<T, S> From<ArcStore<T>> for Store<T, S>
where
T: 'static,
S: Storage<ArcStore<T>>,
{
fn from(value: ArcStore<T>) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: value.defined_at,
inner: ArenaItem::new_with_storage(value),
}
}
}
#[cfg(test)]
mod tests {
use crate::{self as reactive_stores, Patch, Store, StoreFieldIterator};
use reactive_graph::{
effect::Effect,
owner::StoredValue,
traits::{Read, ReadUntracked, Set, Track, Update, Write},
};
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
pub async fn tick() {
tokio::time::sleep(std::time::Duration::from_micros(1)).await;
}
#[derive(Debug, Store, Patch, Default)]
struct Todos {
user: String,
todos: Vec<Todo>,
}
#[derive(Debug, Store, Patch, Default)]
struct Todo {
label: String,
completed: bool,
}
impl Todo {
pub fn new(label: impl ToString) -> Self {
Self {
label: label.to_string(),
completed: false,
}
}
}
fn data() -> Todos {
Todos {
user: "Bob".to_string(),
todos: vec![
Todo {
label: "Create reactive store".to_string(),
completed: true,
},
Todo {
label: "???".to_string(),
completed: false,
},
Todo {
label: "Profit".to_string(),
completed: false,
},
],
}
}
#[derive(Debug, Clone, Store, Patch, Default)]
struct Foo {
id: i32,
bar: Bar,
}
#[derive(Debug, Clone, Store, Patch, Default)]
struct Bar {
bar_signature: i32,
baz: Baz,
}
#[derive(Debug, Clone, Store, Patch, Default)]
struct Baz {
more_data: i32,
baw: Baw,
}
#[derive(Debug, Clone, Store, Patch, Default)]
struct Baw {
more_data: i32,
end: i32,
}
#[tokio::test]
async fn mutating_field_triggers_effect() {
_ = any_spawner::Executor::init_tokio();
let combined_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(data());
assert_eq!(store.read_untracked().todos.len(), 3);
assert_eq!(store.user().read_untracked().as_str(), "Bob");
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("first run");
} else {
println!("next run");
}
println!("{:?}", *store.user().read());
combined_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
tick().await;
store.user().set("Greg".into());
tick().await;
store.user().set("Carol".into());
tick().await;
store.user().update(|name| name.push_str("!!!"));
tick().await;
// the effect reads from `user`, so it should trigger every time
assert_eq!(combined_count.load(Ordering::Relaxed), 4);
}
#[tokio::test]
async fn other_field_does_not_notify() {
_ = any_spawner::Executor::init_tokio();
let combined_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(data());
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("first run");
} else {
println!("next run");
}
println!("{:?}", *store.todos().read());
combined_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
store.user().set("Greg".into());
tick().await;
store.user().set("Carol".into());
tick().await;
store.user().update(|name| name.push_str("!!!"));
tick().await;
// the effect reads from `todos`, so it shouldn't trigger every time
assert_eq!(combined_count.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn parent_does_notify() {
_ = any_spawner::Executor::init_tokio();
let combined_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(data());
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("first run");
} else {
println!("next run");
}
println!("{:?}", *store.todos().read());
combined_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
tick().await;
store.set(Todos::default());
tick().await;
store.set(data());
tick().await;
assert_eq!(combined_count.load(Ordering::Relaxed), 3);
}
#[tokio::test]
async fn changes_do_notify_parent() {
_ = any_spawner::Executor::init_tokio();
let combined_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(data());
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("first run");
} else {
println!("next run");
}
println!("{:?}", *store.read());
combined_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
tick().await;
store.user().set("Greg".into());
tick().await;
store.user().set("Carol".into());
tick().await;
store.user().update(|name| name.push_str("!!!"));
tick().await;
store.todos().write().clear();
tick().await;
assert_eq!(combined_count.load(Ordering::Relaxed), 5);
}
#[tokio::test]
async fn iterator_tracks_the_field() {
_ = any_spawner::Executor::init_tokio();
let combined_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(data());
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("first run");
} else {
println!("next run");
}
println!(
"{:?}",
store.todos().iter_unkeyed().collect::<Vec<_>>()
);
combined_count.store(1, Ordering::Relaxed);
}
});
tick().await;
store
.todos()
.write()
.push(Todo::new("Create reactive store?"));
tick().await;
store.todos().write().push(Todo::new("???"));
tick().await;
store.todos().write().push(Todo::new("Profit!"));
// the effect only reads from `todos`, so it should trigger only the first time
assert_eq!(combined_count.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn patching_only_notifies_changed_field() {
_ = any_spawner::Executor::init_tokio();
let combined_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(Todos {
user: "Alice".into(),
todos: vec![],
});
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("first run");
} else {
println!("next run");
}
println!("{:?}", *store.todos().read());
combined_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
tick().await;
store.patch(Todos {
user: "Bob".into(),
todos: vec![],
});
tick().await;
store.patch(Todos {
user: "Carol".into(),
todos: vec![],
});
tick().await;
assert_eq!(combined_count.load(Ordering::Relaxed), 1);
store.patch(Todos {
user: "Carol".into(),
todos: vec![Todo {
label: "First Todo".into(),
completed: false,
}],
});
tick().await;
assert_eq!(combined_count.load(Ordering::Relaxed), 2);
}
#[tokio::test]
async fn patching_only_notifies_changed_field_with_custom_patch() {
_ = any_spawner::Executor::init_tokio();
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/keyed.rs | reactive_stores/src/keyed.rs | use crate::{
path::{StorePath, StorePathSegment},
store_field::StoreField,
KeyMap, StoreFieldTrigger,
};
use reactive_graph::{
signal::{
guards::{Mapped, MappedMut, MappedMutArc, WriteGuard},
ArcTrigger,
},
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
};
use std::{
collections::VecDeque,
fmt::Debug,
hash::Hash,
iter,
ops::{Deref, DerefMut, IndexMut},
panic::Location,
};
/// Provides access to a subfield that contains some kind of keyed collection.
#[derive(Debug)]
pub struct KeyedSubfield<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
path_segment: StorePathSegment,
inner: Inner,
read: fn(&Prev) -> &T,
write: fn(&mut Prev) -> &mut T,
key_fn: fn(<&T as IntoIterator>::Item) -> K,
}
impl<Inner, Prev, K, T> Clone for KeyedSubfield<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
Inner: Clone,
{
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
path_segment: self.path_segment,
inner: self.inner.clone(),
read: self.read,
write: self.write,
key_fn: self.key_fn,
}
}
}
impl<Inner, Prev, K, T> Copy for KeyedSubfield<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
Inner: Copy,
{
}
impl<Inner, Prev, K, T> KeyedSubfield<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
{
/// Creates a keyed subfield of the inner data type with the given key function.
#[track_caller]
pub fn new(
inner: Inner,
path_segment: StorePathSegment,
key_fn: fn(<&T as IntoIterator>::Item) -> K,
read: fn(&Prev) -> &T,
write: fn(&mut Prev) -> &mut T,
) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner,
path_segment,
read,
write,
key_fn,
}
}
}
impl<Inner, Prev, K, T> StoreField for KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
type Value = T;
type Reader = Mapped<Inner::Reader, T>;
type Writer = MappedMut<WriteGuard<Vec<ArcTrigger>, Inner::Writer>, T>;
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.path()
.into_iter()
.chain(iter::once(self.path_segment))
}
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.path_unkeyed()
.into_iter()
.chain(iter::once(self.path_segment))
}
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger(path)
}
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger_unkeyed(path)
}
fn reader(&self) -> Option<Self::Reader> {
let inner = self.inner.reader()?;
Some(Mapped::new_with_guard(inner, self.read))
}
fn writer(&self) -> Option<Self::Writer> {
let mut parent = self.inner.writer()?;
parent.untrack();
let triggers = self.triggers_for_current_path();
let guard = WriteGuard::new(triggers, parent);
Some(MappedMut::new(guard, self.read, self.write))
}
#[inline(always)]
fn keys(&self) -> Option<KeyMap> {
self.inner.keys()
}
fn track_field(&self) {
let mut full_path = self.path().into_iter().collect::<StorePath>();
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.track();
trigger.children.track();
// tracks `this` for all ancestors: i.e., it will track any change that is made
// directly to one of its ancestors, but not a change made to a *child* of an ancestor
// (which would end up with every subfield tracking its own siblings, because they are
// children of its parent)
while !full_path.is_empty() {
full_path.pop();
let inner = self.get_trigger(full_path.clone());
inner.this.track();
}
}
}
impl<Inner, Prev, K, T> KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
fn latest_keys(&self) -> Vec<K> {
self.reader()
.map(|r| r.deref().into_iter().map(|n| (self.key_fn)(n)).collect())
.unwrap_or_default()
}
}
/// Gives keyed write access to a value in some collection.
pub struct KeyedSubfieldWriteGuard<Inner, Prev, K, T, Guard>
where
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
inner: KeyedSubfield<Inner, Prev, K, T>,
guard: Option<Guard>,
untracked: bool,
}
impl<Inner, Prev, K, T, Guard> Deref
for KeyedSubfieldWriteGuard<Inner, Prev, K, T, Guard>
where
Guard: Deref,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
type Target = Guard::Target;
fn deref(&self) -> &Self::Target {
self.guard
.as_ref()
.expect("should be Some(_) until dropped")
.deref()
}
}
impl<Inner, Prev, K, T, Guard> DerefMut
for KeyedSubfieldWriteGuard<Inner, Prev, K, T, Guard>
where
Guard: DerefMut,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
fn deref_mut(&mut self) -> &mut Self::Target {
self.guard
.as_mut()
.expect("should be Some(_) until dropped")
.deref_mut()
}
}
impl<Inner, Prev, K, T, Guard> UntrackableGuard
for KeyedSubfieldWriteGuard<Inner, Prev, K, T, Guard>
where
Guard: UntrackableGuard,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
fn untrack(&mut self) {
self.untracked = true;
if let Some(inner) = self.guard.as_mut() {
inner.untrack();
}
}
}
impl<Inner, Prev, K, T, Guard> Drop
for KeyedSubfieldWriteGuard<Inner, Prev, K, T, Guard>
where
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
fn drop(&mut self) {
// dropping the inner guard will
// 1) synchronously release its write lock on the store's value
// 2) trigger an (asynchronous) reactive update
drop(self.guard.take());
// now that the write lock is release, we can get a read lock to refresh this keyed field
// based on the new value
self.inner.update_keys();
if !self.untracked {
self.inner.notify();
}
// reactive updates happen on the next tick
}
}
impl<Inner, Prev, K, T> DefinedAt for KeyedSubfield<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
{
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<Inner, Prev, K, T> IsDisposed for KeyedSubfield<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
Inner: IsDisposed,
{
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<Inner, Prev, K, T> Notify for KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
fn notify(&self) {
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.notify();
trigger.children.notify();
}
}
impl<Inner, Prev, K, T> Track for KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev> + Track + 'static,
Prev: 'static,
T: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
fn track(&self) {
self.track_field();
}
}
impl<Inner, Prev, K, T> ReadUntracked for KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
type Value = <Self as StoreField>::Reader;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.reader()
}
}
impl<Inner, Prev, K, T> Write for KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
T: 'static,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
let guard = self.writer()?;
Some(KeyedSubfieldWriteGuard {
inner: self.clone(),
guard: Some(guard),
untracked: false,
})
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
let mut guard = self.writer()?;
guard.untrack();
Some(KeyedSubfieldWriteGuard {
inner: self.clone(),
guard: Some(guard),
untracked: true,
})
}
}
/// Gives access to the value in a collection based on some key.
#[derive(Debug)]
pub struct AtKeyed<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: KeyedSubfield<Inner, Prev, K, T>,
key: K,
}
impl<Inner, Prev, K, T> Clone for AtKeyed<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
KeyedSubfield<Inner, Prev, K, T>: Clone,
K: Debug + Clone,
{
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
inner: self.inner.clone(),
key: self.key.clone(),
}
}
}
impl<Inner, Prev, K, T> Copy for AtKeyed<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
KeyedSubfield<Inner, Prev, K, T>: Copy,
K: Debug + Copy,
{
}
impl<Inner, Prev, K, T> AtKeyed<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
{
/// Provides access to the item in the inner collection at this key.
#[track_caller]
pub fn new(inner: KeyedSubfield<Inner, Prev, K, T>, key: K) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner,
key,
}
}
}
impl<Inner, Prev, K, T> StoreField for AtKeyed<Inner, Prev, K, T>
where
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
T: IndexMut<usize>,
T::Output: Sized,
{
type Value = T::Output;
type Reader = MappedMutArc<
<KeyedSubfield<Inner, Prev, K, T> as StoreField>::Reader,
T::Output,
>;
type Writer = WriteGuard<
Vec<ArcTrigger>,
MappedMutArc<
<KeyedSubfield<Inner, Prev, K, T> as StoreField>::Writer,
T::Output,
>,
>;
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
let inner = self.inner.path().into_iter().collect::<StorePath>();
let keys = self
.inner
.keys()
.expect("using keys on a store with no keys");
let this = keys
.with_field_keys(
inner.clone(),
|keys| (keys.get(&self.key), vec![]),
|| self.inner.latest_keys(),
)
.flatten()
.map(|(path, _)| path);
inner.into_iter().chain(this)
}
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
let inner =
self.inner.path_unkeyed().into_iter().collect::<StorePath>();
let keys = self
.inner
.keys()
.expect("using keys on a store with no keys");
let this = keys
.with_field_keys(
inner.clone(),
|keys| (keys.get(&self.key), vec![]),
|| self.inner.latest_keys(),
)
.flatten()
.map(|(_, idx)| StorePathSegment(idx));
inner.into_iter().chain(this)
}
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger(path)
}
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger_unkeyed(path)
}
fn reader(&self) -> Option<Self::Reader> {
let inner = self.inner.reader()?;
let inner_path = self.inner.path().into_iter().collect();
let keys = self.inner.keys()?;
let index = keys
.with_field_keys(
inner_path,
|keys| (keys.get(&self.key), vec![]),
|| self.inner.latest_keys(),
)
.flatten()
.map(|(_, idx)| idx)?;
Some(MappedMutArc::new(
inner,
move |n| &n[index],
move |n| &mut n[index],
))
}
fn writer(&self) -> Option<Self::Writer> {
let mut inner = self.inner.writer()?;
inner.untrack();
let inner_path = self.inner.path().into_iter().collect::<StorePath>();
let keys = self
.inner
.keys()
.expect("using keys on a store with no keys");
let index = keys
.with_field_keys(
inner_path.clone(),
|keys| (keys.get(&self.key), vec![]),
|| self.inner.latest_keys(),
)
.flatten()
.map(|(_, idx)| idx)?;
let triggers = self.triggers_for_current_path();
Some(WriteGuard::new(
triggers,
MappedMutArc::new(
inner,
move |n| &n[index],
move |n| &mut n[index],
),
))
}
#[inline(always)]
fn keys(&self) -> Option<KeyMap> {
self.inner.keys()
}
}
impl<Inner, Prev, K, T> DefinedAt for AtKeyed<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
{
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<Inner, Prev, K, T> IsDisposed for AtKeyed<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
Inner: IsDisposed,
{
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<Inner, Prev, K, T> Notify for AtKeyed<Inner, Prev, K, T>
where
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
T: IndexMut<usize>,
T::Output: Sized,
{
fn notify(&self) {
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.notify();
trigger.children.notify();
}
}
impl<Inner, Prev, K, T> Track for AtKeyed<Inner, Prev, K, T>
where
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
T: IndexMut<usize>,
T::Output: Sized,
{
fn track(&self) {
self.track_field();
}
}
impl<Inner, Prev, K, T> ReadUntracked for AtKeyed<Inner, Prev, K, T>
where
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
T: IndexMut<usize>,
T::Output: Sized,
{
type Value = <Self as StoreField>::Reader;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.reader()
}
}
impl<Inner, Prev, K, T> Write for AtKeyed<Inner, Prev, K, T>
where
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
T: IndexMut<usize>,
T::Output: Sized + 'static,
{
type Value = T::Output;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.writer()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.writer().map(|mut writer| {
writer.untrack();
writer
})
}
}
impl<Inner, Prev, K, T> KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev>,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
{
/// Generates a new set of keys and registers those keys with the parent store.
pub fn update_keys(&self) {
let inner_path = self.path().into_iter().collect();
let keys = self
.inner
.keys()
.expect("updating keys on a store with no keys");
// generating the latest keys out here means that if we have
// nested keyed fields, the second field will not try to take a
// read-lock on the key map to get the field while the first field
// is still holding the write-lock in the closure below
let latest = self.latest_keys();
keys.with_field_keys(
inner_path,
|keys| ((), keys.update(latest)),
|| self.latest_keys(),
);
}
}
impl<Inner, Prev, K, T> IntoIterator for KeyedSubfield<Inner, Prev, K, T>
where
Self: Clone,
for<'a> &'a T: IntoIterator,
Inner: Clone + StoreField<Value = Prev> + 'static,
Prev: 'static,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
T: IndexMut<usize> + 'static,
T::Output: Sized,
{
type Item = AtKeyed<Inner, Prev, K, T>;
type IntoIter = StoreFieldKeyedIter<Inner, Prev, K, T>;
#[track_caller]
fn into_iter(self) -> StoreFieldKeyedIter<Inner, Prev, K, T> {
// reactively track changes to this field
self.update_keys();
self.track_field();
// get the current length of the field by accessing slice
let reader = self.reader();
let keys = reader
.map(|r| {
r.into_iter()
.map(|item| (self.key_fn)(item))
.collect::<VecDeque<_>>()
})
.unwrap_or_default();
// return the iterator
StoreFieldKeyedIter { inner: self, keys }
}
}
/// An iterator over a [`KeyedSubfield`].
pub struct StoreFieldKeyedIter<Inner, Prev, K, T>
where
for<'a> &'a T: IntoIterator,
T: IndexMut<usize>,
{
inner: KeyedSubfield<Inner, Prev, K, T>,
keys: VecDeque<K>,
}
impl<Inner, Prev, K, T> Iterator for StoreFieldKeyedIter<Inner, Prev, K, T>
where
Inner: StoreField<Value = Prev> + Clone + 'static,
T: IndexMut<usize> + 'static,
T::Output: Sized + 'static,
for<'a> &'a T: IntoIterator,
{
type Item = AtKeyed<Inner, Prev, K, T>;
fn next(&mut self) -> Option<Self::Item> {
self.keys
.pop_front()
.map(|key| AtKeyed::new(self.inner.clone(), key))
}
}
impl<Inner, Prev, K, T> DoubleEndedIterator
for StoreFieldKeyedIter<Inner, Prev, K, T>
where
Inner: StoreField<Value = Prev> + Clone + 'static,
T: IndexMut<usize> + 'static,
T::Output: Sized + 'static,
for<'a> &'a T: IntoIterator,
{
fn next_back(&mut self) -> Option<Self::Item> {
self.keys
.pop_back()
.map(|key| AtKeyed::new(self.inner.clone(), key))
}
}
#[cfg(test)]
mod tests {
use crate::{self as reactive_stores, tests::tick, AtKeyed, Store};
use reactive_graph::{
effect::Effect,
traits::{GetUntracked, ReadUntracked, Set, Track, Write},
};
use reactive_stores::Patch;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
#[derive(Debug, Store, Default, Patch)]
struct Todos {
#[store(key: usize = |todo| todo.id)]
todos: Vec<Todo>,
}
#[derive(Debug, Store, Default, Clone, PartialEq, Eq, Patch)]
struct Todo {
id: usize,
label: String,
}
impl Todo {
pub fn new(id: usize, label: impl ToString) -> Self {
Self {
id,
label: label.to_string(),
}
}
}
fn data() -> Todos {
Todos {
todos: vec![
Todo {
id: 10,
label: "A".to_string(),
},
Todo {
id: 11,
label: "B".to_string(),
},
Todo {
id: 12,
label: "C".to_string(),
},
],
}
}
#[tokio::test]
async fn keyed_fields_can_be_moved() {
_ = any_spawner::Executor::init_tokio();
let store = Store::new(data());
assert_eq!(store.read_untracked().todos.len(), 3);
// create an effect to read from each keyed field
let a_count = Arc::new(AtomicUsize::new(0));
let b_count = Arc::new(AtomicUsize::new(0));
let c_count = Arc::new(AtomicUsize::new(0));
let a = AtKeyed::new(store.todos(), 10);
let b = AtKeyed::new(store.todos(), 11);
let c = AtKeyed::new(store.todos(), 12);
Effect::new_sync({
let a_count = Arc::clone(&a_count);
move || {
a.track();
a_count.fetch_add(1, Ordering::Relaxed);
}
});
Effect::new_sync({
let b_count = Arc::clone(&b_count);
move || {
b.track();
b_count.fetch_add(1, Ordering::Relaxed);
}
});
Effect::new_sync({
let c_count = Arc::clone(&c_count);
move || {
c.track();
c_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
assert_eq!(a_count.load(Ordering::Relaxed), 1);
assert_eq!(b_count.load(Ordering::Relaxed), 1);
assert_eq!(c_count.load(Ordering::Relaxed), 1);
// writing at a key doesn't notify siblings
*a.label().write() = "Foo".into();
tick().await;
assert_eq!(a_count.load(Ordering::Relaxed), 2);
assert_eq!(b_count.load(Ordering::Relaxed), 1);
assert_eq!(c_count.load(Ordering::Relaxed), 1);
// the keys can be reorganized
store.todos().write().swap(0, 2);
let after = store.todos().get_untracked();
assert_eq!(
after,
vec![Todo::new(12, "C"), Todo::new(11, "B"), Todo::new(10, "Foo")]
);
tick().await;
assert_eq!(a_count.load(Ordering::Relaxed), 2);
assert_eq!(b_count.load(Ordering::Relaxed), 1);
assert_eq!(c_count.load(Ordering::Relaxed), 1);
// and after we move the keys around, they still update the moved items
a.label().set("Bar".into());
let after = store.todos().get_untracked();
assert_eq!(
after,
vec![Todo::new(12, "C"), Todo::new(11, "B"), Todo::new(10, "Bar")]
);
tick().await;
assert_eq!(a_count.load(Ordering::Relaxed), 3);
assert_eq!(b_count.load(Ordering::Relaxed), 1);
assert_eq!(c_count.load(Ordering::Relaxed), 1);
// we can remove a key and add a new one
store.todos().write().pop();
store.todos().write().push(Todo::new(13, "New"));
let after = store.todos().get_untracked();
assert_eq!(
after,
vec![Todo::new(12, "C"), Todo::new(11, "B"), Todo::new(13, "New")]
);
tick().await;
assert_eq!(a_count.load(Ordering::Relaxed), 3);
assert_eq!(b_count.load(Ordering::Relaxed), 1);
assert_eq!(c_count.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn untracked_write_on_keyed_subfield_shouldnt_notify() {
_ = any_spawner::Executor::init_tokio();
let store = Store::new(data());
assert_eq!(store.read_untracked().todos.len(), 3);
// create an effect to read from the keyed subfield
let todos_count = Arc::new(AtomicUsize::new(0));
Effect::new_sync({
let todos_count = Arc::clone(&todos_count);
move || {
store.todos().track();
todos_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
assert_eq!(todos_count.load(Ordering::Relaxed), 1);
// writing to keyed subfield notifies the iterator
store.todos().write().push(Todo {
id: 13,
label: "D".into(),
});
tick().await;
assert_eq!(todos_count.load(Ordering::Relaxed), 2);
// but an untracked write doesn't
store.todos().write_untracked().push(Todo {
id: 14,
label: "E".into(),
});
tick().await;
assert_eq!(todos_count.load(Ordering::Relaxed), 2);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/store_field.rs | reactive_stores/src/store_field.rs | use crate::{
path::{StorePath, StorePathSegment},
ArcStore, KeyMap, Store, StoreFieldTrigger,
};
use or_poisoned::OrPoisoned;
use reactive_graph::{
owner::Storage,
signal::{
guards::{Plain, UntrackedWriteGuard, WriteGuard},
ArcTrigger,
},
traits::{Track, UntrackableGuard},
};
use std::{iter, ops::Deref, sync::Arc};
/// Describes a type that can be accessed as a reactive store field.
pub trait StoreField: Sized {
/// The value this field contains.
type Value;
/// A read guard to access this field.
type Reader: Deref<Target = Self::Value>;
/// A write guard to update this field.
type Writer: UntrackableGuard<Target = Self::Value>;
/// Returns the trigger that tracks access and updates for this field.
#[track_caller]
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger;
/// Returns the trigger that tracks access and updates for this field.
///
/// This uses *unkeyed* paths: i.e., if any field in the path is keyed, it will
/// try to look up the key for the item at the index given in the path, rather than
/// the keyed item.
#[track_caller]
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger;
/// The path of this field (see [`StorePath`]).
#[track_caller]
fn path(&self) -> impl IntoIterator<Item = StorePathSegment>;
/// The path of this field (see [`StorePath`]). Uses unkeyed indices for any keyed fields.
#[track_caller]
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
// TODO remove default impl next time we do a breaking release
self.path()
}
/// Reactively tracks this field.
#[track_caller]
fn track_field(&self) {
let path = self.path().into_iter().collect();
let trigger = self.get_trigger(path);
trigger.this.track();
trigger.children.track();
}
/// Returns a read guard to access this field.
#[track_caller]
fn reader(&self) -> Option<Self::Reader>;
/// Returns a write guard to update this field.
#[track_caller]
fn writer(&self) -> Option<Self::Writer>;
/// The keys for this field, if it is a keyed field.
#[track_caller]
fn keys(&self) -> Option<KeyMap>;
/// Returns triggers for this field, and all parent fields.
fn triggers_for_current_path(&self) -> Vec<ArcTrigger> {
self.triggers_for_path(self.path().into_iter().collect())
}
/// Returns triggers for the field at the given path, and all parent fields
fn triggers_for_path(&self, path: StorePath) -> Vec<ArcTrigger> {
let trigger = self.get_trigger(path.clone());
let mut full_path = path;
// build a list of triggers, starting with the full path to this node and ending with the root
// this will mean that the root is the final item, and this path is first
let mut triggers = Vec::with_capacity(full_path.len() + 2);
triggers.push(trigger.this.clone());
triggers.push(trigger.children.clone());
while !full_path.is_empty() {
full_path.pop();
let inner = self.get_trigger(full_path.clone());
triggers.push(inner.children.clone());
}
// when the WriteGuard is dropped, each trigger will be notified, in order
// reversing the list will cause the triggers to be notified starting from the root,
// then to each child down to this one
//
// notifying from the root down is important for things like OptionStoreExt::map()/unwrap(),
// where it's really important that any effects that subscribe to .is_some() run before effects
// that subscribe to the inner value, so that the inner effect can be canceled if the outer switches to `None`
// (see https://github.com/leptos-rs/leptos/issues/3704)
triggers.reverse();
triggers
}
/// Returns triggers for the field at the given path, and all parent fields
fn triggers_for_path_unkeyed(&self, path: StorePath) -> Vec<ArcTrigger> {
// see notes on triggers_for_path() for additional comments on implementation
let trigger = self.get_trigger_unkeyed(path.clone());
let mut full_path = path;
let mut triggers = Vec::with_capacity(full_path.len() + 2);
triggers.push(trigger.this.clone());
triggers.push(trigger.children.clone());
while !full_path.is_empty() {
full_path.pop();
let inner = self.get_trigger_unkeyed(full_path.clone());
triggers.push(inner.children.clone());
}
triggers.reverse();
triggers
}
}
impl<T> StoreField for ArcStore<T>
where
T: 'static,
{
type Value = T;
type Reader = Plain<T>;
type Writer = WriteGuard<ArcTrigger, UntrackedWriteGuard<T>>;
#[track_caller]
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
let triggers = &self.signals;
let trigger = triggers.write().or_poisoned().get_or_insert(path);
trigger
}
#[track_caller]
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
let caller = std::panic::Location::caller();
let orig_path = path.clone();
let mut path = StorePath::with_capacity(orig_path.len());
for segment in &orig_path {
let parent_is_keyed = self.keys.contains_key(&path);
if parent_is_keyed {
let key = self
.keys
.get_key_for_index(&(path.clone(), segment.0))
.unwrap_or_else(|| {
panic!(
"could not find key for index {:?} at {}",
&(path.clone(), segment.0),
caller
)
});
path.push(key);
} else {
path.push(*segment);
}
}
self.get_trigger(path)
}
#[track_caller]
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
iter::empty()
}
#[track_caller]
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
iter::empty()
}
#[track_caller]
fn reader(&self) -> Option<Self::Reader> {
Plain::try_new(Arc::clone(&self.value))
}
#[track_caller]
fn writer(&self) -> Option<Self::Writer> {
let trigger = self.get_trigger(Default::default());
let guard = UntrackedWriteGuard::try_new(Arc::clone(&self.value))?;
Some(WriteGuard::new(trigger.children, guard))
}
#[track_caller]
fn keys(&self) -> Option<KeyMap> {
Some(self.keys.clone())
}
}
impl<T, S> StoreField for Store<T, S>
where
T: 'static,
S: Storage<ArcStore<T>>,
{
type Value = T;
type Reader = Plain<T>;
type Writer = WriteGuard<ArcTrigger, UntrackedWriteGuard<T>>;
#[track_caller]
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
self.inner
.try_get_value()
.map(|n| n.get_trigger(path))
.unwrap_or_default()
}
#[track_caller]
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
self.inner
.try_get_value()
.map(|n| n.get_trigger_unkeyed(path))
.unwrap_or_default()
}
#[track_caller]
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.try_get_value()
.map(|n| n.path().into_iter().collect::<Vec<_>>())
.unwrap_or_default()
}
#[track_caller]
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.try_get_value()
.map(|n| n.path_unkeyed().into_iter().collect::<Vec<_>>())
.unwrap_or_default()
}
#[track_caller]
fn reader(&self) -> Option<Self::Reader> {
self.inner.try_get_value().and_then(|n| n.reader())
}
#[track_caller]
fn writer(&self) -> Option<Self::Writer> {
self.inner.try_get_value().and_then(|n| n.writer())
}
#[track_caller]
fn keys(&self) -> Option<KeyMap> {
self.inner.try_get_value().and_then(|inner| inner.keys())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/option.rs | reactive_stores/src/option.rs | use crate::{StoreField, Subfield};
use reactive_graph::traits::{FlattenOptionRefOption, Read, ReadUntracked};
use std::ops::Deref;
/// Extends optional store fields, with the ability to unwrap or map over them.
pub trait OptionStoreExt
where
Self: StoreField<Value = Option<Self::Output>>,
{
/// The inner type of the `Option<_>` this field holds.
type Output;
/// Provides access to the inner value, as a subfield, unwrapping the outer value.
fn unwrap(self) -> Subfield<Self, Option<Self::Output>, Self::Output>;
/// Inverts a subfield of an `Option` to an `Option` of a subfield.
fn invert(
self,
) -> Option<Subfield<Self, Option<Self::Output>, Self::Output>> {
self.map(|f| f)
}
/// Reactively maps over the field.
///
/// This returns `None` if the subfield is currently `None`,
/// and a new store subfield with the inner value if it is `Some`. This can be used in some
/// other reactive context, which will cause it to re-run if the field toggles between `None`
/// and `Some(_)`.
fn map<U>(
self,
map_fn: impl FnOnce(Subfield<Self, Option<Self::Output>, Self::Output>) -> U,
) -> Option<U>;
/// Unreactively maps over the field.
///
/// This returns `None` if the subfield is currently `None`,
/// and a new store subfield with the inner value if it is `Some`. This is an unreactive variant of
/// `[OptionStoreExt::map]`, and will not cause the reactive context to re-run if the field changes.
fn map_untracked<U>(
self,
map_fn: impl FnOnce(Subfield<Self, Option<Self::Output>, Self::Output>) -> U,
) -> Option<U>;
}
impl<T, S> OptionStoreExt for S
where
S: StoreField<Value = Option<T>> + Read + ReadUntracked,
<S as Read>::Value: Deref<Target = Option<T>>,
<S as ReadUntracked>::Value: Deref<Target = Option<T>>,
{
type Output = T;
fn unwrap(self) -> Subfield<Self, Option<Self::Output>, Self::Output> {
Subfield::new(
self,
0.into(),
|t| t.as_ref().unwrap(),
|t| t.as_mut().unwrap(),
)
}
fn map<U>(
self,
map_fn: impl FnOnce(Subfield<S, Option<T>, T>) -> U,
) -> Option<U> {
if self.try_read().as_deref().flatten().is_some() {
Some(map_fn(self.unwrap()))
} else {
None
}
}
fn map_untracked<U>(
self,
map_fn: impl FnOnce(Subfield<S, Option<T>, T>) -> U,
) -> Option<U> {
if self.try_read_untracked().as_deref().flatten().is_some() {
Some(map_fn(self.unwrap()))
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use crate::{self as reactive_stores, Patch as _, Store};
use any_spawner::Executor;
use reactive_graph::{
effect::Effect,
traits::{Get, Read, ReadUntracked, Set, Write},
};
use reactive_stores_macro::Patch;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
pub async fn tick() {
Executor::tick().await;
}
#[derive(Debug, Clone, Store)]
pub struct User {
pub name: Option<Name>,
}
#[derive(Debug, Clone, Store)]
pub struct Name {
pub first_name: Option<String>,
}
#[tokio::test]
async fn substores_reachable_through_option() {
use crate::OptionStoreExt;
_ = any_spawner::Executor::init_tokio();
let combined_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(User { name: None });
Effect::new_sync({
let combined_count = Arc::clone(&combined_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("first run");
} else {
println!("next run");
}
if store.name().read().is_some() {
println!(
"inner value = {:?}",
*store.name().unwrap().first_name().read()
);
} else {
println!("no inner value");
}
combined_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
store.name().set(Some(Name {
first_name: Some("Greg".into()),
}));
tick().await;
store.name().set(None);
tick().await;
store.name().set(Some(Name {
first_name: Some("Bob".into()),
}));
tick().await;
store
.name()
.unwrap()
.first_name()
.write()
.as_mut()
.unwrap()
.push_str("!!!");
tick().await;
assert_eq!(combined_count.load(Ordering::Relaxed), 5);
assert_eq!(
store
.name()
.read_untracked()
.as_ref()
.unwrap()
.first_name
.as_ref()
.unwrap(),
"Bob!!!"
);
}
#[tokio::test]
async fn mapping_over_optional_store_field() {
use crate::OptionStoreExt;
_ = any_spawner::Executor::init_tokio();
let parent_count = Arc::new(AtomicUsize::new(0));
let inner_count = Arc::new(AtomicUsize::new(0));
let store = Store::new(User { name: None });
Effect::new_sync({
let parent_count = Arc::clone(&parent_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("parent: first run");
} else {
println!("parent: next run");
}
println!(" is_some = {}", store.name().read().is_some());
parent_count.fetch_add(1, Ordering::Relaxed);
}
});
Effect::new_sync({
let inner_count = Arc::clone(&inner_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("inner: first run");
} else {
println!("inner: next run");
}
println!(
"store inner value length = {:?}",
store.name().map(|inner| inner
.first_name()
.get()
.unwrap_or_default()
.len())
);
inner_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
assert_eq!(parent_count.load(Ordering::Relaxed), 1);
assert_eq!(inner_count.load(Ordering::Relaxed), 1);
store.name().set(Some(Name {
first_name: Some("Greg".into()),
}));
tick().await;
assert_eq!(parent_count.load(Ordering::Relaxed), 2);
assert_eq!(inner_count.load(Ordering::Relaxed), 2);
println!("\nUpdating first name only");
store
.name()
.unwrap()
.first_name()
.write()
.as_mut()
.unwrap()
.push_str("!!!");
tick().await;
assert_eq!(parent_count.load(Ordering::Relaxed), 3);
assert_eq!(inner_count.load(Ordering::Relaxed), 3);
}
#[tokio::test]
async fn patch() {
use crate::OptionStoreExt;
_ = any_spawner::Executor::init_tokio();
#[derive(Debug, Clone, Store, Patch)]
struct Outer {
inner: Option<Inner>,
}
#[derive(Debug, Clone, Store, Patch)]
struct Inner {
first: String,
second: String,
}
let store = Store::new(Outer {
inner: Some(Inner {
first: "A".to_owned(),
second: "B".to_owned(),
}),
});
let parent_count = Arc::new(AtomicUsize::new(0));
let inner_first_count = Arc::new(AtomicUsize::new(0));
let inner_second_count = Arc::new(AtomicUsize::new(0));
Effect::new_sync({
let parent_count = Arc::clone(&parent_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("parent: first run");
} else {
println!("parent: next run");
}
println!(" value = {:?}", store.inner().get());
parent_count.fetch_add(1, Ordering::Relaxed);
}
});
Effect::new_sync({
let inner_first_count = Arc::clone(&inner_first_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("inner_first: first run");
} else {
println!("inner_first: next run");
}
// note: we specifically want to test whether using `.patch()`
// correctly limits notifications on the first field when only the second
// field has changed
//
// `.map()` would also track the parent field (to track when it changed from Some
// to None), which would mean the notification numbers were always the same
//
// so here, we'll do `.map_untracked()`, but in general in a real case you'd want
// to use `.map()` so that if the parent switches to None you do track that
println!(
" value = {:?}",
store.inner().map_untracked(|inner| inner.first().get())
);
inner_first_count.fetch_add(1, Ordering::Relaxed);
}
});
Effect::new_sync({
let inner_second_count = Arc::clone(&inner_second_count);
move |prev: Option<()>| {
if prev.is_none() {
println!("inner_second: first run");
} else {
println!("inner_second: next run");
}
println!(
" value = {:?}",
store.inner().map(|inner| inner.second().get())
);
inner_second_count.fetch_add(1, Ordering::Relaxed);
}
});
tick().await;
assert_eq!(parent_count.load(Ordering::Relaxed), 1);
assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
assert_eq!(inner_second_count.load(Ordering::Relaxed), 1);
println!("\npatching with A/C");
store.patch(Outer {
inner: Some(Inner {
first: "A".to_string(),
second: "C".to_string(),
}),
});
tick().await;
assert_eq!(parent_count.load(Ordering::Relaxed), 2);
assert_eq!(inner_first_count.load(Ordering::Relaxed), 1);
assert_eq!(inner_second_count.load(Ordering::Relaxed), 2);
store.patch(Outer { inner: None });
tick().await;
assert_eq!(parent_count.load(Ordering::Relaxed), 3);
assert_eq!(inner_first_count.load(Ordering::Relaxed), 2);
assert_eq!(inner_second_count.load(Ordering::Relaxed), 3);
println!("\npatching with A/B");
store.patch(Outer {
inner: Some(Inner {
first: "A".to_string(),
second: "B".to_string(),
}),
});
tick().await;
assert_eq!(parent_count.load(Ordering::Relaxed), 4);
assert_eq!(inner_first_count.load(Ordering::Relaxed), 2);
assert_eq!(inner_second_count.load(Ordering::Relaxed), 4);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/deref.rs | reactive_stores/src/deref.rs | use crate::{
path::{StorePath, StorePathSegment},
store_field::StoreField,
KeyMap, StoreFieldTrigger,
};
use reactive_graph::{
signal::guards::{Mapped, MappedMut},
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
};
use std::{
ops::{Deref, DerefMut},
panic::Location,
};
/// Maps a store field that is a smart pointer to a subfield of the dereferenced inner type.
pub trait DerefField
where
Self: StoreField,
Self::Value: Deref + DerefMut,
<Self::Value as Deref>::Target: Sized + 'static,
{
/// Returns a new store field with the value mapped to the target type of dereferencing this
/// field
///
/// For example, if you have a store field with a `Box<T>`, `.deref_field()` will return a
/// new store field containing a `T`.
fn deref_field(self) -> DerefedField<Self>;
}
impl<S> DerefField for S
where
S: StoreField,
S::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized + 'static,
{
#[track_caller]
fn deref_field(self) -> DerefedField<Self> {
DerefedField {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner: self,
}
}
}
/// A wrapper from a store field containing a smart pointer to a store field containing the
/// dereferenced target type of that smart pointer.
#[derive(Debug, Copy, Clone)]
pub struct DerefedField<S> {
inner: S,
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
}
impl<S> StoreField for DerefedField<S>
where
S: StoreField,
S::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized + 'static,
{
type Value = <S::Value as Deref>::Target;
type Reader = Mapped<S::Reader, Self::Value>;
type Writer = MappedMut<S::Writer, Self::Value>;
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger(path)
}
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger_unkeyed(path)
}
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner.path()
}
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner.path_unkeyed()
}
fn reader(&self) -> Option<Self::Reader> {
let inner = self.inner.reader()?;
Some(Mapped::new_with_guard(inner, |n| n.deref()))
}
fn writer(&self) -> Option<Self::Writer> {
let inner = self.inner.writer()?;
Some(MappedMut::new(inner, |n| n.deref(), |n| n.deref_mut()))
}
#[inline(always)]
fn keys(&self) -> Option<KeyMap> {
self.inner.keys()
}
}
impl<S> DefinedAt for DerefedField<S>
where
S: StoreField,
S::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized + '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<S> IsDisposed for DerefedField<S>
where
S: IsDisposed,
{
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<S> Notify for DerefedField<S>
where
S: StoreField,
S::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized + 'static,
{
fn notify(&self) {
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.notify();
trigger.children.notify();
}
}
impl<S> Track for DerefedField<S>
where
S: StoreField,
S::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized + 'static,
{
fn track(&self) {
self.track_field();
}
}
impl<S> ReadUntracked for DerefedField<S>
where
S: StoreField,
S::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized + 'static,
{
type Value = <Self as StoreField>::Reader;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.reader()
}
}
impl<S> Write for DerefedField<S>
where
S: StoreField,
S::Value: Deref + DerefMut,
<S::Value as Deref>::Target: Sized + 'static,
{
type Value = <S::Value as Deref>::Target;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.writer()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.writer().map(|mut writer| {
writer.untrack();
writer
})
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/arc_field.rs | reactive_stores/src/arc_field.rs | use crate::{
path::{StorePath, StorePathSegment},
ArcStore, AtIndex, AtKeyed, DerefedField, KeyMap, KeyedSubfield, Store,
StoreField, StoreFieldTrigger, Subfield,
};
use reactive_graph::{
owner::Storage,
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
};
use std::{
fmt::Debug,
hash::Hash,
ops::{Deref, DerefMut, IndexMut},
panic::Location,
sync::Arc,
};
/// Reference-counted access to a single field of type `T`.
///
/// This can be used to erase the chain of field-accessors, to make it easier to pass this into
/// another component or function without needing to specify the full type signature.
pub struct ArcField<T>
where
T: 'static,
{
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
path: Arc<dyn Fn() -> StorePath + Send + Sync>,
path_unkeyed: Arc<dyn Fn() -> StorePath + Send + Sync>,
get_trigger: Arc<dyn Fn(StorePath) -> StoreFieldTrigger + Send + Sync>,
get_trigger_unkeyed:
Arc<dyn Fn(StorePath) -> StoreFieldTrigger + Send + Sync>,
read: Arc<dyn Fn() -> Option<StoreFieldReader<T>> + Send + Sync>,
pub(crate) write:
Arc<dyn Fn() -> Option<StoreFieldWriter<T>> + Send + Sync>,
keys: Arc<dyn Fn() -> Option<KeyMap> + Send + Sync>,
track_field: Arc<dyn Fn() + Send + Sync>,
notify: Arc<dyn Fn() + Send + Sync>,
}
impl<T> Debug for ArcField<T>
where
T: 'static,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut f = f.debug_struct("ArcField");
#[cfg(any(debug_assertions, leptos_debuginfo))]
let f = f.field("defined_at", &self.defined_at);
f.finish_non_exhaustive()
}
}
pub struct StoreFieldReader<T>(Box<dyn Deref<Target = T>>);
impl<T> StoreFieldReader<T> {
pub fn new(inner: impl Deref<Target = T> + 'static) -> Self {
Self(Box::new(inner))
}
}
impl<T> Deref for StoreFieldReader<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
pub struct StoreFieldWriter<T>(Box<dyn UntrackableGuard<Target = T>>);
impl<T> StoreFieldWriter<T> {
pub fn new(inner: impl UntrackableGuard<Target = T> + 'static) -> Self {
Self(Box::new(inner))
}
}
impl<T> Deref for StoreFieldWriter<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl<T> DerefMut for StoreFieldWriter<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.deref_mut()
}
}
impl<T> UntrackableGuard for StoreFieldWriter<T> {
fn untrack(&mut self) {
self.0.untrack();
}
}
impl<T> StoreField for ArcField<T> {
type Value = T;
type Reader = StoreFieldReader<T>;
type Writer = StoreFieldWriter<T>;
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
(self.get_trigger)(path)
}
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
(self.get_trigger_unkeyed)(path)
}
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
(self.path)()
}
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
(self.path_unkeyed)()
}
fn reader(&self) -> Option<Self::Reader> {
(self.read)().map(StoreFieldReader::new)
}
fn writer(&self) -> Option<Self::Writer> {
(self.write)().map(StoreFieldWriter::new)
}
fn keys(&self) -> Option<KeyMap> {
(self.keys)()
}
}
impl<T, S> From<Store<T, S>> for ArcField<T>
where
T: 'static,
S: Storage<ArcStore<T>>,
{
#[track_caller]
fn from(value: Store<T, S>) -> Self {
ArcField {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
path: Arc::new(move || value.path().into_iter().collect()),
path_unkeyed: Arc::new(move || {
value.path_unkeyed().into_iter().collect()
}),
get_trigger: Arc::new(move |path| value.get_trigger(path)),
get_trigger_unkeyed: Arc::new(move |path| {
value.get_trigger_unkeyed(path)
}),
read: Arc::new(move || value.reader().map(StoreFieldReader::new)),
write: Arc::new(move || value.writer().map(StoreFieldWriter::new)),
keys: Arc::new(move || value.keys()),
track_field: Arc::new(move || value.track_field()),
notify: Arc::new(move || value.notify()),
}
}
}
impl<T> From<ArcStore<T>> for ArcField<T>
where
T: Send + Sync + 'static,
{
#[track_caller]
fn from(value: ArcStore<T>) -> Self {
ArcField {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
path: Arc::new({
let value = value.clone();
move || value.path().into_iter().collect()
}),
path_unkeyed: Arc::new({
let value = value.clone();
move || value.path_unkeyed().into_iter().collect()
}),
get_trigger: Arc::new({
let value = value.clone();
move |path| value.get_trigger(path)
}),
get_trigger_unkeyed: Arc::new({
let value = value.clone();
move |path| value.get_trigger_unkeyed(path)
}),
read: Arc::new({
let value = value.clone();
move || value.reader().map(StoreFieldReader::new)
}),
write: Arc::new({
let value = value.clone();
move || value.writer().map(StoreFieldWriter::new)
}),
keys: Arc::new({
let value = value.clone();
move || value.keys()
}),
track_field: Arc::new({
let value = value.clone();
move || value.track_field()
}),
notify: Arc::new({
let value = value.clone();
move || value.notify()
}),
}
}
}
impl<Inner, Prev, T> From<Subfield<Inner, Prev, T>> for ArcField<T>
where
T: Send + Sync,
Subfield<Inner, Prev, T>: Clone,
Inner: StoreField<Value = Prev> + Send + Sync + 'static,
Prev: 'static,
{
#[track_caller]
fn from(value: Subfield<Inner, Prev, T>) -> Self {
ArcField {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
path: Arc::new({
let value = value.clone();
move || value.path().into_iter().collect()
}),
path_unkeyed: Arc::new({
let value = value.clone();
move || value.path_unkeyed().into_iter().collect()
}),
get_trigger: Arc::new({
let value = value.clone();
move |path| value.get_trigger(path)
}),
get_trigger_unkeyed: Arc::new({
let value = value.clone();
move |path| value.get_trigger_unkeyed(path)
}),
read: Arc::new({
let value = value.clone();
move || value.reader().map(StoreFieldReader::new)
}),
write: Arc::new({
let value = value.clone();
move || value.writer().map(StoreFieldWriter::new)
}),
keys: Arc::new({
let value = value.clone();
move || value.keys()
}),
track_field: Arc::new({
let value = value.clone();
move || value.track_field()
}),
notify: Arc::new({
let value = value.clone();
move || value.notify()
}),
}
}
}
impl<Inner, T> From<DerefedField<Inner>> for ArcField<T>
where
Inner: Clone + StoreField + Send + Sync + 'static,
Inner::Value: Deref<Target = T> + DerefMut,
T: Sized + 'static,
{
#[track_caller]
fn from(value: DerefedField<Inner>) -> Self {
ArcField {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
path: Arc::new({
let value = value.clone();
move || value.path().into_iter().collect()
}),
path_unkeyed: Arc::new({
let value = value.clone();
move || value.path_unkeyed().into_iter().collect()
}),
get_trigger: Arc::new({
let value = value.clone();
move |path| value.get_trigger(path)
}),
get_trigger_unkeyed: Arc::new({
let value = value.clone();
move |path| value.get_trigger_unkeyed(path)
}),
read: Arc::new({
let value = value.clone();
move || value.reader().map(StoreFieldReader::new)
}),
write: Arc::new({
let value = value.clone();
move || value.writer().map(StoreFieldWriter::new)
}),
keys: Arc::new({
let value = value.clone();
move || value.keys()
}),
track_field: Arc::new({
let value = value.clone();
move || value.track_field()
}),
notify: Arc::new({
let value = value.clone();
move || value.notify()
}),
}
}
}
impl<Inner, Prev> From<AtIndex<Inner, Prev>> for ArcField<Prev::Output>
where
AtIndex<Inner, Prev>: Clone,
Inner: StoreField<Value = Prev> + Send + Sync + 'static,
Prev: IndexMut<usize> + Send + Sync + 'static,
Prev::Output: Sized + Send + Sync,
{
#[track_caller]
fn from(value: AtIndex<Inner, Prev>) -> Self {
ArcField {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
path: Arc::new({
let value = value.clone();
move || value.path().into_iter().collect()
}),
path_unkeyed: Arc::new({
let value = value.clone();
move || value.path_unkeyed().into_iter().collect()
}),
get_trigger: Arc::new({
let value = value.clone();
move |path| value.get_trigger(path)
}),
get_trigger_unkeyed: Arc::new({
let value = value.clone();
move |path| value.get_trigger_unkeyed(path)
}),
read: Arc::new({
let value = value.clone();
move || value.reader().map(StoreFieldReader::new)
}),
write: Arc::new({
let value = value.clone();
move || value.writer().map(StoreFieldWriter::new)
}),
keys: Arc::new({
let value = value.clone();
move || value.keys()
}),
track_field: Arc::new({
let value = value.clone();
move || value.track_field()
}),
notify: Arc::new({
let value = value.clone();
move || value.notify()
}),
}
}
}
impl<Inner, Prev, K, T> From<AtKeyed<Inner, Prev, K, T>> for ArcField<T::Output>
where
AtKeyed<Inner, Prev, K, T>: Clone,
K: Debug + Send + Sync + PartialEq + Eq + Hash + 'static,
KeyedSubfield<Inner, Prev, K, T>: Clone,
for<'a> &'a T: IntoIterator,
Inner: StoreField<Value = Prev> + Send + Sync + 'static,
Prev: 'static,
T: IndexMut<usize> + 'static,
T::Output: Sized,
{
#[track_caller]
fn from(value: AtKeyed<Inner, Prev, K, T>) -> Self {
ArcField {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
path: Arc::new({
let value = value.clone();
move || value.path().into_iter().collect()
}),
path_unkeyed: Arc::new({
let value = value.clone();
move || value.path_unkeyed().into_iter().collect()
}),
get_trigger: Arc::new({
let value = value.clone();
move |path| value.get_trigger(path)
}),
get_trigger_unkeyed: Arc::new({
let value = value.clone();
move |path| value.get_trigger_unkeyed(path)
}),
read: Arc::new({
let value = value.clone();
move || value.reader().map(StoreFieldReader::new)
}),
write: Arc::new({
let value = value.clone();
move || value.writer().map(StoreFieldWriter::new)
}),
keys: Arc::new({
let value = value.clone();
move || value.keys()
}),
track_field: Arc::new({
let value = value.clone();
move || value.track_field()
}),
notify: Arc::new({
let value = value.clone();
move || value.notify()
}),
}
}
}
impl<T> Clone for ArcField<T> {
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
path: self.path.clone(),
path_unkeyed: self.path_unkeyed.clone(),
get_trigger: Arc::clone(&self.get_trigger),
get_trigger_unkeyed: Arc::clone(&self.get_trigger_unkeyed),
read: Arc::clone(&self.read),
write: Arc::clone(&self.write),
keys: Arc::clone(&self.keys),
track_field: Arc::clone(&self.track_field),
notify: Arc::clone(&self.notify),
}
}
}
impl<T> DefinedAt for ArcField<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 ArcField<T> {
fn notify(&self) {
(self.notify)()
}
}
impl<T> Track for ArcField<T> {
fn track(&self) {
(self.track_field)();
}
}
impl<T> ReadUntracked for ArcField<T> {
type Value = StoreFieldReader<T>;
fn try_read_untracked(&self) -> Option<Self::Value> {
(self.read)()
}
}
impl<T> Write for ArcField<T> {
type Value = T;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
(self.write)()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
let mut guard = (self.write)()?;
guard.untrack();
Some(guard)
}
}
impl<T> IsDisposed for ArcField<T> {
fn is_disposed(&self) -> bool {
false
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/iter.rs | reactive_stores/src/iter.rs | use crate::{
len::Len,
path::{StorePath, StorePathSegment},
store_field::StoreField,
KeyMap, StoreFieldTrigger,
};
use reactive_graph::{
signal::{
guards::{MappedMutArc, WriteGuard},
ArcTrigger,
},
traits::{
DefinedAt, IsDisposed, Notify, ReadUntracked, Track, UntrackableGuard,
Write,
},
};
use std::{
iter,
marker::PhantomData,
ops::{DerefMut, IndexMut},
panic::Location,
};
/// Provides access to the data at some index in another collection.
#[derive(Debug)]
pub struct AtIndex<Inner, Prev> {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: &'static Location<'static>,
inner: Inner,
index: usize,
ty: PhantomData<Prev>,
}
impl<Inner, Prev> Clone for AtIndex<Inner, Prev>
where
Inner: Clone,
{
fn clone(&self) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: self.defined_at,
inner: self.inner.clone(),
index: self.index,
ty: self.ty,
}
}
}
impl<Inner, Prev> Copy for AtIndex<Inner, Prev> where Inner: Copy {}
impl<Inner, Prev> AtIndex<Inner, Prev> {
/// Creates a new accessor for the inner collection at the given index.
#[track_caller]
pub fn new(inner: Inner, index: usize) -> Self {
Self {
#[cfg(any(debug_assertions, leptos_debuginfo))]
defined_at: Location::caller(),
inner,
index,
ty: PhantomData,
}
}
}
impl<Inner, Prev> StoreField for AtIndex<Inner, Prev>
where
Inner: StoreField<Value = Prev>,
Prev: IndexMut<usize> + 'static,
Prev::Output: Sized,
{
type Value = Prev::Output;
type Reader = MappedMutArc<Inner::Reader, Prev::Output>;
type Writer =
MappedMutArc<WriteGuard<ArcTrigger, Inner::Writer>, Prev::Output>;
fn path(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.path()
.into_iter()
.chain(iter::once(self.index.into()))
}
fn path_unkeyed(&self) -> impl IntoIterator<Item = StorePathSegment> {
self.inner
.path_unkeyed()
.into_iter()
.chain(iter::once(self.index.into()))
}
fn get_trigger(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger(path)
}
fn get_trigger_unkeyed(&self, path: StorePath) -> StoreFieldTrigger {
self.inner.get_trigger_unkeyed(path)
}
fn reader(&self) -> Option<Self::Reader> {
let inner = self.inner.reader()?;
let index = self.index;
Some(MappedMutArc::new(
inner,
move |n| &n[index],
move |n| &mut n[index],
))
}
fn writer(&self) -> Option<Self::Writer> {
let trigger = self.get_trigger(self.path().into_iter().collect());
let inner = WriteGuard::new(trigger.children, self.inner.writer()?);
let index = self.index;
Some(MappedMutArc::new(
inner,
move |n| &n[index],
move |n| &mut n[index],
))
}
#[inline(always)]
fn keys(&self) -> Option<KeyMap> {
self.inner.keys()
}
fn track_field(&self) {
let mut full_path = self.path().into_iter().collect::<StorePath>();
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.track();
trigger.children.track();
// tracks `this` for all ancestors: i.e., it will track any change that is made
// directly to one of its ancestors, but not a change made to a *child* of an ancestor
// (which would end up with every subfield tracking its own siblings, because they are
// children of its parent)
while !full_path.is_empty() {
full_path.pop();
let inner = self.get_trigger(full_path.clone());
inner.this.track();
}
}
}
impl<Inner, Prev> DefinedAt for AtIndex<Inner, Prev>
where
Inner: StoreField<Value = Prev>,
{
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<Inner, Prev> IsDisposed for AtIndex<Inner, Prev>
where
Inner: StoreField<Value = Prev> + IsDisposed,
{
fn is_disposed(&self) -> bool {
self.inner.is_disposed()
}
}
impl<Inner, Prev> Notify for AtIndex<Inner, Prev>
where
Inner: StoreField<Value = Prev>,
Prev: IndexMut<usize> + 'static,
Prev::Output: Sized,
{
fn notify(&self) {
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.notify();
}
}
impl<Inner, Prev> Track for AtIndex<Inner, Prev>
where
Inner: StoreField<Value = Prev> + Send + Sync + Clone + 'static,
Prev: IndexMut<usize> + 'static,
Prev::Output: Sized + 'static,
{
fn track(&self) {
self.track_field();
}
}
impl<Inner, Prev> ReadUntracked for AtIndex<Inner, Prev>
where
Inner: StoreField<Value = Prev>,
Prev: IndexMut<usize> + 'static,
Prev::Output: Sized,
{
type Value = <Self as StoreField>::Reader;
fn try_read_untracked(&self) -> Option<Self::Value> {
self.reader()
}
}
impl<Inner, Prev> Write for AtIndex<Inner, Prev>
where
Inner: StoreField<Value = Prev>,
Prev: IndexMut<usize> + 'static,
Prev::Output: Sized + 'static,
{
type Value = Prev::Output;
fn try_write(&self) -> Option<impl UntrackableGuard<Target = Self::Value>> {
self.writer()
}
fn try_write_untracked(
&self,
) -> Option<impl DerefMut<Target = Self::Value>> {
self.writer().map(|mut writer| {
writer.untrack();
writer
})
}
}
/// Provides unkeyed reactive access to the fields of some collection.
pub trait StoreFieldIterator<Prev>
where
Self: StoreField<Value = Prev>,
{
/// Reactive access to the value at some index.
fn at_unkeyed(self, index: usize) -> AtIndex<Self, Prev>;
/// An iterator over the values in the collection.
fn iter_unkeyed(self) -> StoreFieldIter<Self, Prev>;
}
impl<Inner, Prev> StoreFieldIterator<Prev> for Inner
where
Inner: StoreField<Value = Prev> + Clone,
Prev::Output: Sized,
Prev: IndexMut<usize> + Len,
{
#[track_caller]
fn at_unkeyed(self, index: usize) -> AtIndex<Inner, Prev> {
AtIndex::new(self.clone(), index)
}
#[track_caller]
fn iter_unkeyed(self) -> StoreFieldIter<Inner, Prev> {
// reactively track changes to this field
let trigger = self.get_trigger(self.path().into_iter().collect());
trigger.this.track();
trigger.children.track();
// get the current length of the field by accessing slice
let len = self.reader().map(|n| n.len()).unwrap_or(0);
// return the iterator
StoreFieldIter {
inner: self,
idx: 0,
len,
prev: PhantomData,
}
}
}
/// An iterator over the values in a collection, as reactive fields.
pub struct StoreFieldIter<Inner, Prev> {
inner: Inner,
idx: usize,
len: usize,
prev: PhantomData<Prev>,
}
impl<Inner, Prev> Iterator for StoreFieldIter<Inner, Prev>
where
Inner: StoreField<Value = Prev> + Clone + 'static,
Prev: IndexMut<usize> + 'static,
Prev::Output: Sized + 'static,
{
type Item = AtIndex<Inner, Prev>;
fn next(&mut self) -> Option<Self::Item> {
if self.idx < self.len {
let field = AtIndex::new(self.inner.clone(), self.idx);
self.idx += 1;
Some(field)
} else {
None
}
}
}
impl<Inner, Prev> DoubleEndedIterator for StoreFieldIter<Inner, Prev>
where
Inner: StoreField<Value = Prev> + Clone + 'static,
Prev: IndexMut<usize> + 'static,
Prev::Output: Sized + 'static,
{
fn next_back(&mut self) -> Option<Self::Item> {
if self.len > self.idx {
self.len -= 1;
let field = AtIndex::new(self.inner.clone(), self.len);
Some(field)
} else {
None
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/len.rs | reactive_stores/src/len.rs | use std::{
borrow::Cow,
collections::{LinkedList, VecDeque},
};
/// A trait for getting the length of a collection.
pub trait Len {
/// Returns the length of the collection.
fn len(&self) -> usize;
/// Returns true if the collection is empty
#[inline(always)]
fn is_empty(&self) -> bool {
self.len() == 0
}
}
macro_rules! delegate_impl_len {
(<$($lt: lifetime,)*$($generics: ident,)*> $ty:ty) => {
impl<$($lt,)*$($generics,)*> Len for $ty {
#[inline(always)]
fn len(&self) -> usize {
<$ty>::len(self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
<$ty>::is_empty(self)
}
}
impl<$($lt,)*$($generics,)*> Len for &$ty {
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl<$($lt,)*$($generics,)*> Len for &mut $ty {
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
};
($ty:ty) => {
delegate_impl_len!(<> $ty);
};
}
delegate_impl_len!(<T,> [T]);
delegate_impl_len!(<T,> Vec<T>);
delegate_impl_len!(str);
delegate_impl_len!(String);
impl Len for Cow<'_, str> {
#[inline(always)]
fn len(&self) -> usize {
<str>::len(self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
<str>::is_empty(self)
}
}
impl Len for &Cow<'_, str> {
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl Len for &mut Cow<'_, str> {
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl<T> Len for Cow<'_, [T]>
where
[T]: ToOwned,
{
#[inline(always)]
fn len(&self) -> usize {
<[T]>::len(self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
<[T]>::is_empty(self)
}
}
impl<T> Len for &Cow<'_, [T]>
where
[T]: ToOwned,
{
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl<T> Len for &mut Cow<'_, [T]>
where
[T]: ToOwned,
{
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl<T> Len for VecDeque<T> {
#[inline(always)]
fn len(&self) -> usize {
<VecDeque<T>>::len(self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
<VecDeque<T>>::is_empty(self)
}
}
impl<T> Len for &VecDeque<T> {
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl<T> Len for &mut VecDeque<T> {
#[inline(always)]
fn len(&self) -> usize {
Len::len(&**self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl<T> Len for LinkedList<T> {
#[inline(always)]
fn len(&self) -> usize {
<LinkedList<T>>::len(self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
<LinkedList<T>>::is_empty(self)
}
}
impl<T> Len for &LinkedList<T> {
#[inline(always)]
fn len(&self) -> usize {
Len::len(*self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
impl<T> Len for &mut LinkedList<T> {
#[inline(always)]
fn len(&self) -> usize {
Len::len(&**self)
}
#[inline(always)]
fn is_empty(&self) -> bool {
Len::is_empty(*self)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/reactive_stores/src/patch.rs | reactive_stores/src/patch.rs | use crate::{path::StorePath, StoreField};
use itertools::{EitherOrBoth, Itertools};
use reactive_graph::traits::{Notify, UntrackableGuard};
use std::{
borrow::Cow,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
num::{
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8,
NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64,
NonZeroU8, NonZeroUsize,
},
rc::Rc,
sync::Arc,
};
/// Allows updating a store or field in place with a new value.
pub trait Patch {
/// The type of the new value.
type Value;
/// Patches a store or field with a new value, only notifying fields that have changed.
fn patch(&self, new: Self::Value);
}
impl<T> Patch for T
where
T: StoreField,
T::Value: PatchField,
{
type Value = T::Value;
fn patch(&self, new: Self::Value) {
let path = self.path_unkeyed().into_iter().collect::<StorePath>();
if let Some(mut writer) = self.writer() {
// don't track the writer for the whole store
writer.untrack();
let mut notify = |path: &StorePath| {
self.triggers_for_path_unkeyed(path.to_owned()).notify();
};
writer.patch_field(new, &path, &mut notify);
}
}
}
/// Allows patching a store field with some new value.
pub trait PatchField {
/// Patches the field with some new value, only notifying if the value has changed.
fn patch_field(
&mut self,
new: Self,
path: &StorePath,
notify: &mut dyn FnMut(&StorePath),
);
}
macro_rules! patch_primitives {
($($ty:ty),*) => {
$(impl PatchField for $ty {
fn patch_field(
&mut self,
new: Self,
path: &StorePath,
notify: &mut dyn FnMut(&StorePath),
) {
if new != *self {
*self = new;
notify(path);
}
}
})*
};
}
patch_primitives! {
&str,
String,
Arc<str>,
Rc<str>,
Cow<'_, str>,
usize,
u8,
u16,
u32,
u64,
u128,
isize,
i8,
i16,
i32,
i64,
i128,
f32,
f64,
char,
bool,
IpAddr,
SocketAddr,
SocketAddrV4,
SocketAddrV6,
Ipv4Addr,
Ipv6Addr,
NonZeroI8,
NonZeroU8,
NonZeroI16,
NonZeroU16,
NonZeroI32,
NonZeroU32,
NonZeroI64,
NonZeroU64,
NonZeroI128,
NonZeroU128,
NonZeroIsize,
NonZeroUsize
}
impl<T> PatchField for Option<T>
where
T: PatchField,
{
fn patch_field(
&mut self,
new: Self,
path: &StorePath,
notify: &mut dyn FnMut(&StorePath),
) {
match (self, new) {
(None, None) => {}
(old @ Some(_), None) => {
old.take();
notify(path);
}
(old @ None, new @ Some(_)) => {
*old = new;
notify(path);
}
(Some(old), Some(new)) => {
let mut new_path = path.to_owned();
new_path.push(0);
old.patch_field(new, &new_path, notify);
}
}
}
}
impl<T> PatchField for Vec<T>
where
T: PatchField,
{
fn patch_field(
&mut self,
new: Self,
path: &StorePath,
notify: &mut dyn FnMut(&StorePath),
) {
if self.is_empty() && new.is_empty() {
return;
}
if new.is_empty() {
self.clear();
notify(path);
} else if self.is_empty() {
self.extend(new);
notify(path);
} else {
let mut adds = vec![];
let mut removes_at_end = 0;
let mut new_path = path.to_owned();
new_path.push(0);
for (idx, item) in
new.into_iter().zip_longest(self.iter_mut()).enumerate()
{
match item {
EitherOrBoth::Both(new, old) => {
old.patch_field(new, &new_path, notify);
}
EitherOrBoth::Left(new) => {
adds.push(new);
}
EitherOrBoth::Right(_) => {
removes_at_end += 1;
}
}
new_path.replace_last(idx + 1);
}
let length_changed = removes_at_end > 0 || !adds.is_empty();
self.truncate(self.len() - removes_at_end);
self.append(&mut adds);
if length_changed {
notify(path);
}
}
}
}
macro_rules! patch_tuple {
($($ty:ident),*) => {
impl<$($ty),*> PatchField for ($($ty,)*)
where
$($ty: PatchField),*,
{
fn patch_field(
&mut self,
new: Self,
path: &StorePath,
notify: &mut dyn FnMut(&StorePath),
) {
let mut idx = 0;
let mut new_path = path.to_owned();
new_path.push(0);
paste::paste! {
#[allow(non_snake_case)]
let ($($ty,)*) = self;
let ($([<new_ $ty:lower>],)*) = new;
$(
$ty.patch_field([<new_ $ty:lower>], &new_path, notify);
idx += 1;
new_path.replace_last(idx);
)*
}
}
}
}
}
impl PatchField for () {
fn patch_field(
&mut self,
_new: Self,
_path: &StorePath,
_notify: &mut dyn FnMut(&StorePath),
) {
}
}
patch_tuple!(A);
patch_tuple!(A, B);
patch_tuple!(A, B, C);
patch_tuple!(A, B, C, D);
patch_tuple!(A, B, C, D, E);
patch_tuple!(A, B, C, D, E, F);
patch_tuple!(A, B, C, D, E, F, G);
patch_tuple!(A, B, C, D, E, F, G, H);
patch_tuple!(A, B, C, D, E, F, G, H, I);
patch_tuple!(A, B, C, D, E, F, G, H, I, J);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U);
patch_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V);
patch_tuple!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W
);
patch_tuple!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X
);
patch_tuple!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y
);
patch_tuple!(
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
);
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/integrations/axum/src/lib.rs | integrations/axum/src/lib.rs | #![forbid(unsafe_code)]
#![deny(missing_docs)]
#![allow(clippy::type_complexity)]
//! Provides functions to easily integrate Leptos with Axum.
//!
//! ## JS Fetch Integration
//! The `leptos_axum` integration supports running in JavaScript-hosted WebAssembly
//! runtimes, e.g., running inside Deno, Cloudflare Workers, or other JS environments.
//! To run in this environment, you need to disable the default feature set and enable
//! the `wasm` feature on `leptos_axum` in your `Cargo.toml`.
//! ```toml
//! leptos_axum = { version = "0.6.0", default-features = false, features = ["wasm"] }
//! ```
//!
//! ## Features
//! - `default`: supports running in a typical native Tokio/Axum environment
//! - `wasm`: with `default-features = false`, supports running in a JS Fetch-based
//! environment
//!
//! ### Important Note
//! Prior to 0.5, using `default-features = false` on `leptos_axum` simply did nothing. Now, it actively
//! disables features necessary to support the normal native/Tokio runtime environment we create. This can
//! generate errors like the following, which don’t point to an obvious culprit:
//! `
//! `spawn_local` called from outside of a `task::LocalSet`
//! `
//! If you are not using the `wasm` feature, do not set `default-features = false` on this package.
//!
//!
//! ## More information
//!
//! For more details on how to use the integrations, see the
//! [`examples`](https://github.com/leptos-rs/leptos/tree/main/examples)
//! directory in the Leptos repository.
#[cfg(feature = "default")]
use axum::http::Uri;
use axum::{
body::{Body, Bytes},
extract::{FromRef, FromRequestParts, MatchedPath, State},
http::{
header::{self, HeaderName, HeaderValue, ACCEPT, LOCATION, REFERER},
request::Parts,
HeaderMap, Method, Request, Response, StatusCode,
},
response::IntoResponse,
routing::{delete, get, patch, post, put},
};
#[cfg(feature = "default")]
use dashmap::DashMap;
use futures::{stream::once, Future, Stream, StreamExt};
use hydration_context::SsrSharedContext;
use leptos::{
config::LeptosOptions,
context::{provide_context, use_context},
prelude::*,
reactive::{computed::ScopedFuture, owner::Owner},
IntoView,
};
use leptos_integration_utils::{
BoxedFnOnce, ExtendResponse, PinnedFuture, PinnedStream,
};
use leptos_meta::ServerMetaContext;
#[cfg(feature = "default")]
use leptos_router::static_routes::ResolvedStaticPath;
use leptos_router::{
components::provide_server_redirect, location::RequestUrl,
static_routes::RegenerationFn, ExpandOptionals, PathSegment, RouteList,
RouteListing, SsrMode,
};
use parking_lot::RwLock;
use server_fn::{error::ServerFnErrorErr, redirect::REDIRECT_HEADER};
#[cfg(feature = "default")]
use std::path::Path;
#[cfg(feature = "default")]
use std::sync::LazyLock;
use std::{collections::HashSet, fmt::Debug, io, pin::Pin, sync::Arc};
#[cfg(feature = "default")]
use tower::util::ServiceExt;
#[cfg(feature = "default")]
use tower_http::services::ServeDir;
// use tracing::Instrument; // TODO check tracing span -- was this used in 0.6 for a missing link?
/// This struct lets you define headers and override the status of the Response from an Element or a Server Function
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
#[derive(Debug, Clone, Default)]
pub struct ResponseParts {
/// If provided, this will overwrite any other status code for this response.
pub status: Option<StatusCode>,
/// The map of headers that should be added to the response.
pub headers: HeaderMap,
}
impl ResponseParts {
/// Insert a header, overwriting any previous value with the same key
pub fn insert_header(&mut self, key: HeaderName, value: HeaderValue) {
self.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact
pub fn append_header(&mut self, key: HeaderName, value: HeaderValue) {
self.headers.append(key, value);
}
}
/// Allows you to override details of the HTTP response like the status code and add Headers/Cookies.
///
/// `ResponseOptions` is provided via context when you use most of the handlers provided in this
/// crate, including [`.leptos_routes`](LeptosRoutes::leptos_routes),
/// [`.leptos_routes_with_context`](LeptosRoutes::leptos_routes_with_context), [`handle_server_fns`], etc.
/// You can find the full set of provided context types in each handler function.
///
/// If you provide your own handler, you will need to provide `ResponseOptions` via context
/// yourself if you want to access it via context.
/// ```
/// use leptos::prelude::*;
///
/// #[server]
/// pub async fn get_opts() -> Result<(), ServerFnError> {
/// let opts = expect_context::<leptos_axum::ResponseOptions>();
/// Ok(())
/// }
#[derive(Debug, Clone, Default)]
pub struct ResponseOptions(pub Arc<RwLock<ResponseParts>>);
impl ResponseOptions {
/// A simpler way to overwrite the contents of `ResponseOptions` with a new `ResponseParts`.
pub fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write();
*writable = parts
}
/// Set the status of the returned Response.
pub fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.status = Some(status);
}
/// Insert a header, overwriting any previous value with the same key.
pub fn insert_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact.
pub fn append_header(&self, key: HeaderName, value: HeaderValue) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.append(key, value);
}
}
struct AxumResponse(Response<Body>);
impl ExtendResponse for AxumResponse {
type ResponseOptions = ResponseOptions;
fn from_stream(
stream: impl Stream<Item = String> + Send + 'static,
) -> Self {
AxumResponse(
Body::from_stream(
stream.map(|chunk| Ok(chunk) as Result<String, std::io::Error>),
)
.into_response(),
)
}
fn extend_response(&mut self, res_options: &Self::ResponseOptions) {
let mut res_options = res_options.0.write();
if let Some(status) = res_options.status {
*self.0.status_mut() = status;
}
self.0
.headers_mut()
.extend(std::mem::take(&mut res_options.headers));
}
fn set_default_content_type(&mut self, content_type: &str) {
let headers = self.0.headers_mut();
if !headers.contains_key(header::CONTENT_TYPE) {
// Set the Content Type headers on all responses. This makes Firefox show the page source
// without complaining
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_str(content_type).unwrap(),
);
}
}
}
/// Provides an easy way to redirect the user from within a server function.
///
/// Calling `redirect` in a server function will redirect the browser in three
/// situations:
/// 1. A server function that is calling in a [blocking
/// resource](leptos::server::Resource::new_blocking).
/// 2. A server function that is called from WASM running in the client (e.g., a dispatched action
/// or a spawned `Future`).
/// 3. A `<form>` submitted to the server function endpoint using default browser APIs (often due
/// to using [`ActionForm`] without JS/WASM present.)
///
/// Using it with a non-blocking [`Resource`] will not work if you are using streaming rendering,
/// as the response's headers will already have been sent by the time the server function calls `redirect()`.
///
/// ### Implementation
///
/// This sets the `Location` header to the URL given.
///
/// If the route or server function in which this is called is being accessed
/// by an ordinary `GET` request or an HTML `<form>` without any enhancement, it also sets a
/// status code of `302` for a temporary redirect. (This is determined by whether the `Accept`
/// header contains `text/html` as it does for an ordinary navigation.)
///
/// Otherwise, it sets a custom header that indicates to the client that it should redirect,
/// without actually setting the status code. This means that the client will not follow the
/// redirect, and can therefore return the value of the server function and then handle
/// the redirect with client-side routing.
pub fn redirect(path: &str) {
if let (Some(req), Some(res)) =
(use_context::<Parts>(), use_context::<ResponseOptions>())
{
// insert the Location header in any case
res.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path)
.expect("Failed to create HeaderValue"),
);
let accepts_html = req
.headers
.get(ACCEPT)
.and_then(|v| v.to_str().ok())
.map(|v| v.contains("text/html"))
.unwrap_or(false);
if accepts_html {
// if the request accepts text/html, it's a plain form request and needs
// to have the 302 code set
res.set_status(StatusCode::FOUND);
} else {
// otherwise, we sent it from the server fn client and actually don't want
// to set a real redirect, as this will break the ability to return data
// instead, set the REDIRECT_HEADER to indicate that the client should redirect
res.insert_header(
HeaderName::from_static(REDIRECT_HEADER),
HeaderValue::from_str("").unwrap(),
);
}
} else {
#[cfg(feature = "tracing")]
{
tracing::warn!(
"Couldn't retrieve either Parts or ResponseOptions while \
trying to redirect()."
);
}
#[cfg(not(feature = "tracing"))]
{
eprintln!(
"Couldn't retrieve either Parts or ResponseOptions while \
trying to redirect()."
);
}
}
}
/// Decomposes an HTTP request into its parts, allowing you to read its headers
/// and other data without consuming the body. Creates a new Request from the
/// original parts for further processing
pub fn generate_request_and_parts(
req: Request<Body>,
) -> (Request<Body>, Parts) {
let (parts, body) = req.into_parts();
let parts2 = parts.clone();
(Request::from_parts(parts, body), parts2)
}
/// An Axum handlers to listens for a request with Leptos server function arguments in the body,
/// run the server function if found, and return the resulting [`Response`].
///
/// This can then be set up at an appropriate route in your application:
///
/// ```no_run
/// use axum::{handler::Handler, routing::post, Router};
/// use leptos::prelude::*;
/// use std::net::SocketAddr;
///
/// #[cfg(feature = "default")]
/// #[tokio::main]
/// async fn main() {
/// let addr = SocketAddr::from(([127, 0, 0, 1], 8082));
///
/// // build our application with a route
/// let app = Router::new()
/// .route("/api/*fn_name", post(leptos_axum::handle_server_fns));
///
/// // run our app with hyper
/// let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
/// axum::serve(listener, app.into_make_service())
/// .await
/// .unwrap();
/// }
///
/// # #[cfg(not(feature = "default"))]
/// # fn main() { }
/// ```
/// Leptos provides a generic implementation of `handle_server_fns`. If access to more specific parts of the Request is desired,
/// you can specify your own server fn handler based on this one and give it it's own route in the server macro.
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub async fn handle_server_fns(req: Request<Body>) -> impl IntoResponse {
handle_server_fns_inner(|| {}, req).await
}
fn init_executor() {
#[cfg(feature = "wasm")]
let _ = any_spawner::Executor::init_wasm_bindgen();
#[cfg(all(not(feature = "wasm"), feature = "default"))]
let _ = any_spawner::Executor::init_tokio();
#[cfg(all(not(feature = "wasm"), not(feature = "default")))]
{
eprintln!(
"It appears you have set 'default-features = false' on \
'leptos_axum', but are not using the 'wasm' feature. Either \
remove 'default-features = false' or, if you are running in a \
JS-hosted WASM server environment, add the 'wasm' feature."
);
}
}
/// An Axum handlers to listens for a request with Leptos server function arguments in the body,
/// run the server function if found, and return the resulting [`Response`].
///
/// This can then be set up at an appropriate route in your application:
///
/// This version allows you to pass in a closure to capture additional data from the layers above leptos
/// and store it in context. To use it, you'll need to define your own route, and a handler function
/// that takes in the data you'd like. See the [render_app_to_stream_with_context] docs for an example
/// of one that should work much like this one.
///
/// **NOTE**: If your server functions expect a context, make sure to provide it both in
/// [`handle_server_fns_with_context`] **and** in
/// [`leptos_routes_with_context`](LeptosRoutes::leptos_routes_with_context) (or whatever
/// rendering method you are using). During SSR, server functions are called by the rendering
/// method, while subsequent calls from the client are handled by the server function handler.
/// The same context needs to be provided to both handlers.
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub async fn handle_server_fns_with_context(
additional_context: impl Fn() + 'static + Clone + Send,
req: Request<Body>,
) -> impl IntoResponse {
handle_server_fns_inner(additional_context, req).await
}
async fn handle_server_fns_inner(
additional_context: impl Fn() + 'static + Clone + Send,
req: Request<Body>,
) -> impl IntoResponse {
let method = req.method().clone();
let path = req.uri().path().to_string();
let (req, parts) = generate_request_and_parts(req);
if let Some(mut service) =
server_fn::axum::get_server_fn_service(&path, method)
{
let owner = Owner::new();
owner
.with(|| {
ScopedFuture::new(async move {
provide_context(parts);
let res_options = ResponseOptions::default();
provide_context(res_options.clone());
additional_context();
// store Accepts and Referer in case we need them for redirect (below)
let accepts_html = req
.headers()
.get(ACCEPT)
.and_then(|v| v.to_str().ok())
.map(|v| v.contains("text/html"))
.unwrap_or(false);
let referrer = req.headers().get(REFERER).cloned();
// actually run the server fn
let mut res = AxumResponse(service.run(req).await);
// if it accepts text/html (i.e., is a plain form post) and doesn't already have a
// Location set, then redirect to the Referer
if accepts_html {
if let Some(referrer) = referrer {
let has_location =
res.0.headers().get(LOCATION).is_some();
if !has_location {
*res.0.status_mut() = StatusCode::FOUND;
res.0.headers_mut().insert(LOCATION, referrer);
}
}
}
// apply status code and headers if user changed them
res.extend_response(&res_options);
Ok(res.0)
})
})
.await
} else {
Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from(format!(
"Could not find a server function at the route {path}. \
\n\nIt's likely that either
1. The API prefix you specify in the `#[server]` \
macro doesn't match the prefix at which your server function \
handler is mounted, or \n2. You are on a platform that \
doesn't support automatic server function registration and \
you need to call ServerFn::register_explicit() on the server \
function type, somewhere in your `main` function.",
)))
}
.expect("could not build Response")
}
/// A stream of bytes of HTML.
pub type PinnedHtmlStream =
Pin<Box<dyn Stream<Item = io::Result<Bytes>> + Send>>;
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application.
///
/// This can then be set up at an appropriate route in your application:
/// ```no_run
/// use axum::{handler::Handler, Router};
/// use leptos::{config::get_configuration, prelude::*};
/// use std::{env, net::SocketAddr};
///
/// #[component]
/// fn MyApp() -> impl IntoView {
/// view! { <main>"Hello, world!"</main> }
/// }
///
/// #[cfg(feature = "default")]
/// #[tokio::main]
/// async fn main() {
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
/// let leptos_options = conf.leptos_options;
/// let addr = leptos_options.site_addr.clone();
///
/// // build our application with a route
/// let app = Router::new().fallback(leptos_axum::render_app_to_stream(
/// || { /* your application here */ },
/// ));
///
/// // run our app with hyper
/// let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
/// axum::serve(listener, app.into_make_service())
/// .await
/// .unwrap();
/// }
///
/// # #[cfg(not(feature = "default"))]
/// # fn main() { }
/// ```
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream<IV>(
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
) -> impl Fn(
Request<Body>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
+ Clone
+ Send
+ 'static
where
IV: IntoView + 'static,
{
render_app_to_stream_with_context(|| {}, app_fn)
}
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application.
/// The difference between calling this and `render_app_to_stream_with_context()` is that this
/// one respects the `SsrMode` on each Route and thus requires `Vec<AxumRouteListing>` for route checking.
/// This is useful if you are using `.leptos_routes_with_handler()`
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_route<S, IV>(
paths: Vec<AxumRouteListing>,
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
) -> impl Fn(
State<S>,
Request<Body>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
+ Clone
+ Send
+ 'static
where
IV: IntoView + 'static,
LeptosOptions: FromRef<S>,
S: Send + 'static,
{
render_route_with_context(paths, || {}, app_fn)
}
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an in-order HTML stream of your application.
/// This stream will pause at each `<Suspense/>` node and wait for it to resolve before
/// sending down its HTML. The app will become interactive once it has fully loaded.
///
/// This can then be set up at an appropriate route in your application:
/// ```no_run
/// use axum::{handler::Handler, Router};
/// use leptos::{config::get_configuration, prelude::*};
/// use std::{env, net::SocketAddr};
///
/// #[component]
/// fn MyApp() -> impl IntoView {
/// view! { <main>"Hello, world!"</main> }
/// }
///
/// #[cfg(feature = "default")]
/// #[tokio::main]
/// async fn main() {
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
/// let leptos_options = conf.leptos_options;
/// let addr = leptos_options.site_addr.clone();
///
/// // build our application with a route
/// let app = Router::new().fallback(
/// leptos_axum::render_app_to_stream_in_order(|| view! { <MyApp/> }),
/// );
///
/// // run our app with hyper
/// let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
/// axum::serve(listener, app.into_make_service())
/// .await
/// .unwrap();
/// }
///
/// # #[cfg(not(feature = "default"))]
/// # fn main() { }
/// ```
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_in_order<IV>(
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
) -> impl Fn(
Request<Body>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
+ Clone
+ Send
+ 'static
where
IV: IntoView + 'static,
{
render_app_to_stream_in_order_with_context(|| {}, app_fn)
}
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application.
///
/// This version allows us to pass Axum State/Extension/Extractor or other info from Axum or network
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
/// the data to leptos in a closure. An example is below
/// ```
/// use axum::{
/// body::Body,
/// extract::Path,
/// http::Request,
/// response::{IntoResponse, Response},
/// };
/// use leptos::{config::LeptosOptions, context::provide_context, prelude::*};
///
/// async fn custom_handler(
/// Path(id): Path<String>,
/// req: Request<Body>,
/// ) -> Response {
/// let handler = leptos_axum::render_app_to_stream_with_context(
/// move || {
/// provide_context(id.clone());
/// },
/// || { /* your app here */ },
/// );
/// handler(req).await.into_response()
/// }
/// ```
/// Otherwise, this function is identical to [render_app_to_stream].
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_with_context<IV>(
additional_context: impl Fn() + 'static + Clone + Send + Sync,
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
) -> impl Fn(
Request<Body>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
+ Clone
+ Send
+ Sync
+ 'static
where
IV: IntoView + 'static,
{
render_app_to_stream_with_context_and_replace_blocks(
additional_context,
app_fn,
false,
)
}
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application. It allows you
/// to pass in a context function with additional info to be made available to the app
/// The difference between calling this and `render_app_to_stream_with_context()` is that this
/// one respects the `SsrMode` on each Route, and thus requires `Vec<AxumRouteListing>` for route checking.
/// This is useful if you are using `.leptos_routes_with_handler()`.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_route_with_context<S, IV>(
paths: Vec<AxumRouteListing>,
additional_context: impl Fn() + 'static + Clone + Send + Sync,
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
) -> impl Fn(
State<S>,
Request<Body>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
+ Clone
+ Send
+ 'static
where
IV: IntoView + 'static,
LeptosOptions: FromRef<S>,
S: Send + 'static,
{
let ooo = render_app_to_stream_with_context(
additional_context.clone(),
app_fn.clone(),
);
let pb = render_app_to_stream_with_context_and_replace_blocks(
additional_context.clone(),
app_fn.clone(),
true,
);
let io = render_app_to_stream_in_order_with_context(
additional_context.clone(),
app_fn.clone(),
);
let asyn = render_app_async_stream_with_context(
additional_context.clone(),
app_fn.clone(),
);
move |state, req| {
// 1. Process route to match the values in routeListing
let path = req
.extensions()
.get::<MatchedPath>()
.expect("Failed to get Axum router rule")
.as_str();
// 2. Find RouteListing in paths. This should probably be optimized, we probably don't want to
// search for this every time
let listing: &AxumRouteListing =
paths.iter().find(|r| r.path() == path).unwrap_or_else(|| {
panic!(
"Failed to find the route {path} requested by the user. \
This suggests that the routing rules in the Router that \
call this handler needs to be edited!"
)
});
// 3. Match listing mode against known, and choose function
match listing.mode() {
SsrMode::OutOfOrder => ooo(req),
SsrMode::PartiallyBlocked => pb(req),
SsrMode::InOrder => io(req),
SsrMode::Async => asyn(req),
SsrMode::Static(_) => {
#[cfg(feature = "default")]
{
let regenerate = listing.regenerate.clone();
handle_static_route(
additional_context.clone(),
app_fn.clone(),
regenerate,
)(state, req)
}
#[cfg(not(feature = "default"))]
{
_ = state;
panic!(
"Static routes are not currently supported on WASM32 \
server targets."
);
}
}
}
}
}
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application.
///
/// This version allows us to pass Axum State/Extension/Extractor or other info from Axum or network
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
/// the data to leptos in a closure.
///
/// `replace_blocks` additionally lets you specify whether `<Suspense/>` fragments that read
/// from blocking resources should be retrojected into the HTML that's initially served, rather
/// than dynamically inserting them with JavaScript on the client. This means you will have
/// better support if JavaScript is not enabled, in exchange for a marginally slower response time.
///
/// Otherwise, this function is identical to [render_app_to_stream_with_context].
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_with_context_and_replace_blocks<IV>(
additional_context: impl Fn() + 'static + Clone + Send + Sync,
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
replace_blocks: bool,
) -> impl Fn(
Request<Body>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
+ Clone
+ Send
+ Sync
+ 'static
where
IV: IntoView + 'static,
{
_ = replace_blocks; // TODO
handle_response(additional_context, app_fn, |app, chunks, supports_ooo| {
Box::pin(async move {
let app = if cfg!(feature = "islands-router") {
if supports_ooo {
app.to_html_stream_out_of_order_branching()
} else {
app.to_html_stream_in_order_branching()
}
} else if supports_ooo {
app.to_html_stream_out_of_order()
} else {
app.to_html_stream_in_order()
};
Box::pin(app.chain(chunks())) as PinnedStream<String>
})
})
}
/// Returns an Axum [Handler](axum::handler::Handler) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an in-order HTML stream of your application.
/// This stream will pause at each `<Suspense/>` node and wait for it to resolve before
/// sending down its HTML. The app will become interactive once it has fully loaded.
///
/// This version allows us to pass Axum State/Extension/Extractor or other info from Axum or network
/// layers above Leptos itself. To use it, you'll need to write your own handler function that provides
/// the data to leptos in a closure. An example is below
/// ```
/// use axum::{
/// body::Body,
/// extract::Path,
/// http::Request,
/// response::{IntoResponse, Response},
/// };
/// use leptos::context::provide_context;
///
/// async fn custom_handler(
/// Path(id): Path<String>,
/// req: Request<Body>,
/// ) -> Response {
/// let handler = leptos_axum::render_app_to_stream_in_order_with_context(
/// move || {
/// provide_context(id.clone());
/// },
/// || { /* your application here */ },
/// );
/// handler(req).await.into_response()
/// }
/// ```
/// Otherwise, this function is identical to [render_app_to_stream].
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [`Parts`]
/// - [`ResponseOptions`]
/// - [`ServerMetaContext`]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_in_order_with_context<IV>(
additional_context: impl Fn() + 'static + Clone + Send + Sync,
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
) -> impl Fn(
Request<Body>,
) -> Pin<Box<dyn Future<Output = Response<Body>> + Send + 'static>>
+ Clone
+ Send
+ 'static
where
IV: IntoView + 'static,
{
handle_response(additional_context, app_fn, |app, chunks, _supports_ooo| {
let app = if cfg!(feature = "islands-router") {
app.to_html_stream_in_order_branching()
} else {
app.to_html_stream_in_order()
};
Box::pin(async move {
Box::pin(app.chain(chunks())) as PinnedStream<String>
})
})
}
fn handle_response<IV>(
additional_context: impl Fn() + 'static + Clone + Send + Sync,
app_fn: impl Fn() -> IV + Clone + Send + Sync + 'static,
stream_builder: fn(
IV,
BoxedFnOnce<PinnedStream<String>>,
bool,
) -> PinnedFuture<PinnedStream<String>>,
) -> impl Fn(Request<Body>) -> PinnedFuture<Response<Body>>
+ Clone
+ Send
+ Sync
+ 'static
where
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/integrations/utils/src/lib.rs | integrations/utils/src/lib.rs | #![allow(clippy::type_complexity)]
use futures::{stream::once, Stream, StreamExt};
use hydration_context::{SharedContext, SsrSharedContext};
use leptos::{
context::provide_context,
nonce::use_nonce,
prelude::ReadValue,
reactive::owner::{Owner, Sandboxed},
IntoView, PrefetchLazyFn, WasmSplitManifest,
};
use leptos_config::LeptosOptions;
use leptos_meta::{Link, ServerMetaContextOutput};
use std::{future::Future, pin::Pin, sync::Arc};
pub type PinnedStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
pub type PinnedFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
pub type BoxedFnOnce<T> = Box<dyn FnOnce() -> T + Send>;
pub trait ExtendResponse: Sized {
type ResponseOptions: Send;
fn from_stream(stream: impl Stream<Item = String> + Send + 'static)
-> Self;
fn extend_response(&mut self, opt: &Self::ResponseOptions);
fn set_default_content_type(&mut self, content_type: &str);
fn from_app<IV>(
app_fn: impl FnOnce() -> IV + Send + 'static,
meta_context: ServerMetaContextOutput,
additional_context: impl FnOnce() + Send + 'static,
res_options: Self::ResponseOptions,
stream_builder: fn(
IV,
BoxedFnOnce<PinnedStream<String>>,
bool,
) -> PinnedFuture<PinnedStream<String>>,
supports_ooo: bool,
) -> impl Future<Output = Self> + Send
where
IV: IntoView + 'static,
{
async move {
let prefetches = PrefetchLazyFn::default();
let (owner, stream) = build_response(
app_fn,
additional_context,
stream_builder,
supports_ooo,
);
owner.with(|| provide_context(prefetches.clone()));
let sc = owner.shared_context().unwrap();
let stream = stream.await.ready_chunks(32).map(|n| n.join(""));
while let Some(pending) = sc.await_deferred() {
pending.await;
}
if !prefetches.0.read_value().is_empty() {
use leptos::prelude::*;
let nonce =
use_nonce().map(|n| n.to_string()).unwrap_or_default();
if let Some(manifest) = use_context::<WasmSplitManifest>() {
let (pkg_path, manifest, wasm_split_file) =
&*manifest.0.read_value();
let prefetches = prefetches.0.read_value();
let all_prefetches = prefetches.iter().flat_map(|key| {
manifest.get(*key).into_iter().flatten()
});
for module in all_prefetches {
// to_html() on leptos_meta components registers them with the meta context,
// rather than returning HTML directly
_ = view! {
<Link
rel="preload"
href=format!("{pkg_path}/{module}.wasm")
as_="fetch"
type_="application/wasm"
crossorigin=nonce.clone()
/>
}
.to_html();
}
_ = view! {
<Link rel="modulepreload" href=format!("{pkg_path}/{wasm_split_file}") crossorigin=nonce/>
}
.to_html();
}
}
let mut stream = Box::pin(
meta_context.inject_meta_context(stream).await.then({
let sc = Arc::clone(&sc);
move |chunk| {
let sc = Arc::clone(&sc);
async move {
while let Some(pending) = sc.await_deferred() {
pending.await;
}
chunk
}
}
}),
);
// wait for the first chunk of the stream, then set the status and headers
let first_chunk = stream.next().await.unwrap_or_default();
let mut res = Self::from_stream(Sandboxed::new(
once(async move { first_chunk })
.chain(stream)
// drop the owner, cleaning up the reactive runtime,
// once the stream is over
.chain(once(async move {
owner.unset_with_forced_cleanup();
Default::default()
})),
));
res.extend_response(&res_options);
// Set the Content Type headers on all responses. This makes Firefox show the page source
// without complaining
res.set_default_content_type("text/html; charset=utf-8");
res
}
}
}
pub fn build_response<IV>(
app_fn: impl FnOnce() -> IV + Send + 'static,
additional_context: impl FnOnce() + Send + 'static,
stream_builder: fn(
IV,
BoxedFnOnce<PinnedStream<String>>,
// this argument indicates whether a request wants to support out-of-order streaming
// responses
bool,
) -> PinnedFuture<PinnedStream<String>>,
is_islands_router_navigation: bool,
) -> (Owner, PinnedFuture<PinnedStream<String>>)
where
IV: IntoView + 'static,
{
let shared_context = Arc::new(SsrSharedContext::new())
as Arc<dyn SharedContext + Send + Sync>;
let owner = Owner::new_root(Some(Arc::clone(&shared_context)));
let stream = Box::pin(Sandboxed::new({
let owner = owner.clone();
async move {
let stream = owner.with(|| {
additional_context();
// run app
let app = app_fn();
let nonce = use_nonce()
.as_ref()
.map(|nonce| format!(" nonce=\"{nonce}\""))
.unwrap_or_default();
let shared_context = Owner::current_shared_context().unwrap();
let chunks = Box::new({
let shared_context = shared_context.clone();
move || {
Box::pin(shared_context.pending_data().unwrap().map(
move |chunk| {
format!("<script{nonce}>{chunk}</script>")
},
))
as Pin<Box<dyn Stream<Item = String> + Send>>
}
});
// convert app to appropriate response type
// and chain the app stream, followed by chunks
// in theory, we could select here, and intersperse them
// the problem is that during the DOM walk, that would be mean random <script> tags
// interspersed where we expect other children
//
// we also don't actually start hydrating until after the whole stream is complete,
// so it's not useful to send those scripts down earlier.
stream_builder(app, chunks, is_islands_router_navigation)
});
stream.await
}
}));
(owner, stream)
}
pub fn static_file_path(options: &LeptosOptions, path: &str) -> String {
let trimmed_path = path.trim_start_matches('/');
let path = if trimmed_path.is_empty() {
"index"
} else {
trimmed_path
};
format!("{}/{}.html", options.site_root, path)
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/integrations/actix/src/lib.rs | integrations/actix/src/lib.rs | #![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Provides functions to easily integrate Leptos with Actix.
//!
//! For more details on how to use the integrations, see the
//! [`examples`](https://github.com/leptos-rs/leptos/tree/main/examples)
//! directory in the Leptos repository.
use actix_files::NamedFile;
use actix_http::header::{HeaderName, HeaderValue, ACCEPT, LOCATION, REFERER};
use actix_web::{
dev::{ServiceFactory, ServiceRequest},
http::header,
test,
web::{Data, Payload, ServiceConfig},
*,
};
use dashmap::DashMap;
use futures::{stream::once, Stream, StreamExt};
use http::StatusCode;
use hydration_context::SsrSharedContext;
use leptos::{
config::LeptosOptions,
context::{provide_context, use_context},
hydration::IslandsRouterNavigation,
prelude::expect_context,
reactive::{computed::ScopedFuture, owner::Owner},
IntoView,
};
use leptos_integration_utils::{
BoxedFnOnce, ExtendResponse, PinnedFuture, PinnedStream,
};
use leptos_meta::ServerMetaContext;
use leptos_router::{
components::provide_server_redirect,
location::RequestUrl,
static_routes::{RegenerationFn, ResolvedStaticPath},
ExpandOptionals, Method, PathSegment, RouteList, RouteListing, SsrMode,
};
use parking_lot::RwLock;
use send_wrapper::SendWrapper;
use server_fn::{
error::ServerFnErrorErr, redirect::REDIRECT_HEADER,
request::actix::ActixRequest,
};
use std::{
collections::HashSet,
fmt::{Debug, Display},
future::Future,
ops::{Deref, DerefMut},
path::Path,
sync::{Arc, LazyLock},
};
/// This struct lets you define headers and override the status of the Response from an Element or a Server Function
/// Typically contained inside of a ResponseOptions. Setting this is useful for cookies and custom responses.
#[derive(Debug, Clone, Default)]
pub struct ResponseParts {
/// If provided, this will overwrite any other status code for this response.
pub status: Option<StatusCode>,
/// The map of headers that should be added to the response.
pub headers: header::HeaderMap,
}
impl ResponseParts {
/// Insert a header, overwriting any previous value with the same key
pub fn insert_header(
&mut self,
key: header::HeaderName,
value: header::HeaderValue,
) {
self.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact
pub fn append_header(
&mut self,
key: header::HeaderName,
value: header::HeaderValue,
) {
self.headers.append(key, value);
}
}
/// A wrapper for an Actix [`HttpRequest`] that allows it to be used in an
/// `Send`/`Sync` setting like Leptos's Context API.
#[derive(Debug, Clone)]
pub struct Request(SendWrapper<HttpRequest>);
impl Request {
/// Wraps an existing Actix request.
pub fn new(req: &HttpRequest) -> Self {
Self(SendWrapper::new(req.clone()))
}
/// Consumes the wrapper and returns the inner Actix request.
pub fn into_inner(self) -> HttpRequest {
self.0.take()
}
}
impl Deref for Request {
type Target = HttpRequest;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Request {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// Allows you to override details of the HTTP response like the status code and add Headers/Cookies.
#[derive(Debug, Clone, Default)]
pub struct ResponseOptions(pub Arc<RwLock<ResponseParts>>);
impl ResponseOptions {
/// A simpler way to overwrite the contents of `ResponseOptions` with a new `ResponseParts`.
pub fn overwrite(&self, parts: ResponseParts) {
let mut writable = self.0.write();
*writable = parts
}
/// Set the status of the returned Response.
pub fn set_status(&self, status: StatusCode) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.status = Some(status);
}
/// Insert a header, overwriting any previous value with the same key.
pub fn insert_header(
&self,
key: header::HeaderName,
value: header::HeaderValue,
) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.insert(key, value);
}
/// Append a header, leaving any header with the same key intact.
pub fn append_header(
&self,
key: header::HeaderName,
value: header::HeaderValue,
) {
let mut writeable = self.0.write();
let res_parts = &mut *writeable;
res_parts.headers.append(key, value);
}
}
struct ActixResponse(HttpResponse);
impl ExtendResponse for ActixResponse {
type ResponseOptions = ResponseOptions;
fn from_stream(
stream: impl Stream<Item = String> + Send + 'static,
) -> Self {
ActixResponse(
HttpResponse::Ok()
.content_type("text/html")
.streaming(stream.map(|chunk| {
Ok(web::Bytes::from(chunk)) as Result<web::Bytes>
})),
)
}
fn extend_response(&mut self, res_options: &Self::ResponseOptions) {
let mut res_options = res_options.0.write();
let headers = self.0.headers_mut();
for (key, value) in std::mem::take(&mut res_options.headers) {
headers.append(key, value);
}
// Set status to what is returned in the function
if let Some(status) = res_options.status {
*self.0.status_mut() = status;
}
}
fn set_default_content_type(&mut self, content_type: &str) {
let headers = self.0.headers_mut();
if !headers.contains_key(header::CONTENT_TYPE) {
// Set the Content Type headers on all responses. This makes Firefox show the page source
// without complaining
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_str(content_type).unwrap(),
);
}
}
}
/// Provides an easy way to redirect the user from within a server function.
///
/// Calling `redirect` in a server function will redirect the browser in three
/// situations:
/// 1. A server function that is calling in a [blocking
/// resource](leptos::server::Resource::new_blocking).
/// 2. A server function that is called from WASM running in the client (e.g., a dispatched action
/// or a spawned `Future`).
/// 3. A `<form>` submitted to the server function endpoint using default browser APIs (often due
/// to using [`ActionForm`](leptos::form::ActionForm) without JS/WASM present.)
///
/// Using it with a non-blocking [`Resource`](leptos::server::Resource) will not work if you are using streaming rendering,
/// as the response's headers will already have been sent by the time the server function calls `redirect()`.
///
/// ### Implementation
///
/// This sets the `Location` header to the URL given.
///
/// If the route or server function in which this is called is being accessed
/// by an ordinary `GET` request or an HTML `<form>` without any enhancement, it also sets a
/// status code of `302` for a temporary redirect. (This is determined by whether the `Accept`
/// header contains `text/html` as it does for an ordinary navigation.)
///
/// Otherwise, it sets a custom header that indicates to the client that it should redirect,
/// without actually setting the status code. This means that the client will not follow the
/// redirect, and can therefore return the value of the server function and then handle
/// the redirect with client-side routing.
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn redirect(path: &str) {
if let (Some(req), Some(res)) =
(use_context::<Request>(), use_context::<ResponseOptions>())
{
// insert the Location header in any case
res.insert_header(
header::LOCATION,
header::HeaderValue::from_str(path)
.expect("Failed to create HeaderValue"),
);
let accepts_html = req
.headers()
.get(ACCEPT)
.and_then(|v| v.to_str().ok())
.map(|v| v.contains("text/html"))
.unwrap_or(false);
if accepts_html {
// if the request accepts text/html, it's a plain form request and needs
// to have the 302 code set
res.set_status(StatusCode::FOUND);
} else {
// otherwise, we sent it from the server fn client and actually don't want
// to set a real redirect, as this will break the ability to return data
// instead, set the REDIRECT_HEADER to indicate that the client should redirect
res.insert_header(
HeaderName::from_static(REDIRECT_HEADER),
HeaderValue::from_str("").unwrap(),
);
}
} else {
let msg = "Couldn't retrieve either Parts or ResponseOptions while \
trying to redirect().";
#[cfg(feature = "tracing")]
tracing::warn!("{}", &msg);
#[cfg(not(feature = "tracing"))]
eprintln!("{}", &msg);
}
}
/// An Actix [struct@Route](actix_web::Route) that listens for a `POST` request with
/// Leptos server function arguments in the body, runs the server function if found,
/// and returns the resulting [HttpResponse].
///
/// This can then be set up at an appropriate route in your application:
///
/// ```no_run
/// use actix_web::*;
///
/// fn register_server_functions() {
/// // call ServerFn::register() for each of the server functions you've defined
/// }
///
/// # #[cfg(feature = "default")]
/// #[actix_web::main]
/// async fn main() -> std::io::Result<()> {
/// // make sure you actually register your server functions
/// register_server_functions();
///
/// HttpServer::new(|| {
/// App::new()
/// // "/api" should match the prefix, if any, declared when defining server functions
/// // {tail:.*} passes the remainder of the URL as the server function name
/// .route("/api/{tail:.*}", leptos_actix::handle_server_fns())
/// })
/// .bind(("127.0.0.1", 8080))?
/// .run()
/// .await
/// }
/// # #[cfg(not(feature = "default"))]
/// # fn main() {}
/// ```
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn handle_server_fns() -> Route {
handle_server_fns_with_context(|| {})
}
/// An Actix [struct@Route](actix_web::Route) that listens for `GET` or `POST` requests with
/// Leptos server function arguments in the URL (`GET`) or body (`POST`),
/// runs the server function if found, and returns the resulting [HttpResponse].
///
/// This can then be set up at an appropriate route in your application:
///
/// This version allows you to pass in a closure that adds additional route data to the
/// context, allowing you to pass in info about the route or user from Actix, or other info.
///
/// **NOTE**: If your server functions expect a context, make sure to provide it both in
/// [`handle_server_fns_with_context`] **and** in [`LeptosRoutes::leptos_routes_with_context`] (or whatever
/// rendering method you are using). During SSR, server functions are called by the rendering
/// method, while subsequent calls from the client are handled by the server function handler.
/// The same context needs to be provided to both handlers.
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn handle_server_fns_with_context(
additional_context: impl Fn() + 'static + Clone + Send,
) -> Route {
web::to(move |req: HttpRequest, payload: Payload| {
let additional_context = additional_context.clone();
async move {
let additional_context = additional_context.clone();
let path = req.path();
let method = req.method();
if let Some(mut service) =
server_fn::actix::get_server_fn_service(path, method)
{
let owner = Owner::new();
owner
.with(|| {
ScopedFuture::new(async move {
provide_context(Request::new(&req));
let res_options = ResponseOptions::default();
provide_context(res_options.clone());
additional_context();
// store Accepts and Referer in case we need them for redirect (below)
let accepts_html = req
.headers()
.get(ACCEPT)
.and_then(|v| v.to_str().ok())
.map(|v| v.contains("text/html"))
.unwrap_or(false);
let referrer = req.headers().get(REFERER).cloned();
// actually run the server fn
let mut res = ActixResponse(
service
.run(ActixRequest::from((req, payload)))
.await
.take(),
);
// if it accepts text/html (i.e., is a plain form post) and doesn't already have a
// Location set, then redirect to the Referer
if accepts_html {
if let Some(referrer) = referrer {
let has_location =
res.0.headers().get(LOCATION).is_some();
if !has_location {
*res.0.status_mut() = StatusCode::FOUND;
res.0
.headers_mut()
.insert(LOCATION, referrer);
}
}
}
// the Location header may have been set to Referer, so any redirection by the
// user must overwrite it
{
let mut res_options = res_options.0.write();
let headers = res.0.headers_mut();
for location in
res_options.headers.remove(header::LOCATION)
{
headers.insert(header::LOCATION, location);
}
}
// apply status code and headers if user changed them
res.extend_response(&res_options);
res.0
})
})
.await
} else {
HttpResponse::BadRequest().body(format!(
"Could not find a server function at the route {:?}. \
\n\nIt's likely that either
1. The API prefix you specify in the `#[server]` \
macro doesn't match the prefix at which your server \
function handler is mounted, or \n2. You are on a \
platform that doesn't support automatic server function \
registration and you need to call \
ServerFn::register_explicit() on the server function \
type, somewhere in your `main` function.",
req.path()
))
}
}
})
}
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application. The stream
/// will include fallback content for any `<Suspense/>` nodes, and be immediately interactive,
/// but requires some client-side JavaScript.
///
/// This can then be set up at an appropriate route in your application:
/// ```no_run
/// use actix_web::{App, HttpServer};
/// use leptos::prelude::*;
/// use leptos_router::Method;
/// use std::{env, net::SocketAddr};
///
/// #[component]
/// fn MyApp() -> impl IntoView {
/// view! { <main>"Hello, world!"</main> }
/// }
///
/// # #[cfg(feature = "default")]
/// #[actix_web::main]
/// async fn main() -> std::io::Result<()> {
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
/// let addr = conf.leptos_options.site_addr.clone();
/// HttpServer::new(move || {
/// let leptos_options = &conf.leptos_options;
///
/// App::new()
/// // {tail:.*} passes the remainder of the URL as the route
/// // the actual routing will be handled by `leptos_router`
/// .route(
/// "/{tail:.*}",
/// leptos_actix::render_app_to_stream(MyApp, Method::Get),
/// )
/// })
/// .bind(&addr)?
/// .run()
/// .await
/// }
/// # #[cfg(not(feature = "default"))]
/// # fn main() {}
/// ```
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [MetaContext](leptos_meta::MetaContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream<IV>(
app_fn: impl Fn() -> IV + Clone + Send + 'static,
method: Method,
) -> Route
where
IV: IntoView + 'static,
{
render_app_to_stream_with_context(|| {}, app_fn, method)
}
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an in-order HTML stream of your application.
/// This stream will pause at each `<Suspense/>` node and wait for it to resolve before
/// sending down its HTML. The app will become interactive once it has fully loaded.
///
/// This can then be set up at an appropriate route in your application:
/// ```no_run
/// use actix_web::{App, HttpServer};
/// use leptos::prelude::*;
/// use leptos_router::Method;
/// use std::{env, net::SocketAddr};
///
/// #[component]
/// fn MyApp() -> impl IntoView {
/// view! { <main>"Hello, world!"</main> }
/// }
///
/// # #[cfg(feature = "default")]
/// #[actix_web::main]
/// async fn main() -> std::io::Result<()> {
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
/// let addr = conf.leptos_options.site_addr.clone();
/// HttpServer::new(move || {
/// let leptos_options = &conf.leptos_options;
///
/// App::new()
/// // {tail:.*} passes the remainder of the URL as the route
/// // the actual routing will be handled by `leptos_router`
/// .route(
/// "/{tail:.*}",
/// leptos_actix::render_app_to_stream_in_order(
/// MyApp,
/// Method::Get,
/// ),
/// )
/// })
/// .bind(&addr)?
/// .run()
/// .await
/// }
///
/// # #[cfg(not(feature = "default"))]
/// # fn main() {}
/// ```
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_in_order<IV>(
app_fn: impl Fn() -> IV + Clone + Send + 'static,
method: Method,
) -> Route
where
IV: IntoView + 'static,
{
render_app_to_stream_in_order_with_context(|| {}, app_fn, method)
}
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], asynchronously rendering an HTML page after all
/// `async` resources have loaded.
///
/// This can then be set up at an appropriate route in your application:
/// ```no_run
/// use actix_web::{App, HttpServer};
/// use leptos::prelude::*;
/// use leptos_router::Method;
/// use std::{env, net::SocketAddr};
///
/// #[component]
/// fn MyApp() -> impl IntoView {
/// view! { <main>"Hello, world!"</main> }
/// }
///
/// # #[cfg(feature = "default")]
/// #[actix_web::main]
/// async fn main() -> std::io::Result<()> {
/// let conf = get_configuration(Some("Cargo.toml")).unwrap();
/// let addr = conf.leptos_options.site_addr.clone();
/// HttpServer::new(move || {
/// let leptos_options = &conf.leptos_options;
///
/// App::new()
/// // {tail:.*} passes the remainder of the URL as the route
/// // the actual routing will be handled by `leptos_router`
/// .route(
/// "/{tail:.*}",
/// leptos_actix::render_app_async(MyApp, Method::Get),
/// )
/// })
/// .bind(&addr)?
/// .run()
/// .await
/// }
/// # #[cfg(not(feature = "default"))]
/// # fn main() {}
/// ```
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_async<IV>(
app_fn: impl Fn() -> IV + Clone + Send + 'static,
method: Method,
) -> Route
where
IV: IntoView + 'static,
{
render_app_async_with_context(|| {}, app_fn, method)
}
/// Returns an Actix [struct@Route] that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application.
///
/// This function allows you to provide additional information to Leptos for your route.
/// It could be used to pass in Path Info, Connection Info, or anything your heart desires.
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_with_context<IV>(
additional_context: impl Fn() + 'static + Clone + Send,
app_fn: impl Fn() -> IV + Clone + Send + 'static,
method: Method,
) -> Route
where
IV: IntoView + 'static,
{
render_app_to_stream_with_context_and_replace_blocks(
additional_context,
app_fn,
method,
false,
)
}
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an HTML stream of your application.
///
/// This function allows you to provide additional information to Leptos for your route.
/// It could be used to pass in Path Info, Connection Info, or anything your heart desires.
///
/// `replace_blocks` additionally lets you specify whether `<Suspense/>` fragments that read
/// from blocking resources should be retrojected into the HTML that's initially served, rather
/// than dynamically inserting them with JavaScript on the client. This means you will have
/// better support if JavaScript is not enabled, in exchange for a marginally slower response time.
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_with_context_and_replace_blocks<IV>(
additional_context: impl Fn() + 'static + Clone + Send,
app_fn: impl Fn() -> IV + Clone + Send + 'static,
method: Method,
replace_blocks: bool,
) -> Route
where
IV: IntoView + 'static,
{
_ = replace_blocks; // TODO
handle_response(
method,
additional_context,
app_fn,
|app, chunks, supports_ooo| {
Box::pin(async move {
let app = if cfg!(feature = "islands-router") {
if supports_ooo {
app.to_html_stream_out_of_order_branching()
} else {
app.to_html_stream_in_order_branching()
}
} else if supports_ooo {
app.to_html_stream_out_of_order()
} else {
app.to_html_stream_in_order()
};
Box::pin(app.chain(chunks())) as PinnedStream<String>
})
},
)
}
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], serving an in-order HTML stream of your application.
///
/// This function allows you to provide additional information to Leptos for your route.
/// It could be used to pass in Path Info, Connection Info, or anything your heart desires.
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
/// - [MetaContext](leptos_meta::MetaContext)
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_to_stream_in_order_with_context<IV>(
additional_context: impl Fn() + 'static + Clone + Send,
app_fn: impl Fn() -> IV + Clone + Send + 'static,
method: Method,
) -> Route
where
IV: IntoView + 'static,
{
handle_response(
method,
additional_context,
app_fn,
|app, chunks, _supports_ooo| {
Box::pin(async move {
let app = if cfg!(feature = "islands-router") {
app.to_html_stream_in_order_branching()
} else {
app.to_html_stream_in_order()
};
Box::pin(app.chain(chunks())) as PinnedStream<String>
})
},
)
}
/// Returns an Actix [struct@Route](actix_web::Route) that listens for a `GET` request and tries
/// to route it using [leptos_router], asynchronously serving the page once all `async`
/// resources have loaded.
///
/// This function allows you to provide additional information to Leptos for your route.
/// It could be used to pass in Path Info, Connection Info, or anything your heart desires.
///
/// ## Provided Context Types
/// This function always provides context values including the following types:
/// - [ResponseOptions]
/// - [Request]
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
pub fn render_app_async_with_context<IV>(
additional_context: impl Fn() + 'static + Clone + Send,
app_fn: impl Fn() -> IV + Clone + Send + 'static,
method: Method,
) -> Route
where
IV: IntoView + 'static,
{
handle_response(method, additional_context, app_fn, async_stream_builder)
}
fn async_stream_builder<IV>(
app: IV,
chunks: BoxedFnOnce<PinnedStream<String>>,
_supports_ooo: bool,
) -> PinnedFuture<PinnedStream<String>>
where
IV: IntoView + 'static,
{
Box::pin(async move {
let app = if cfg!(feature = "islands-router") {
app.to_html_stream_in_order_branching()
} else {
app.to_html_stream_in_order()
};
let app = app.collect::<String>().await;
let chunks = chunks();
Box::pin(once(async move { app }).chain(chunks)) as PinnedStream<String>
})
}
#[cfg_attr(
feature = "tracing",
tracing::instrument(level = "trace", fields(error), skip_all)
)]
fn provide_contexts(
req: Request,
meta_context: &ServerMetaContext,
res_options: &ResponseOptions,
) {
let path = leptos_corrected_path(&req);
provide_context(RequestUrl::new(&path));
provide_context(meta_context.clone());
provide_context(res_options.clone());
provide_context(req);
provide_server_redirect(redirect);
leptos::nonce::provide_nonce();
}
fn leptos_corrected_path(req: &HttpRequest) -> String {
let path = req.path();
let query = req.query_string();
if query.is_empty() {
"http://leptos".to_string() + path
} else {
"http://leptos".to_string() + path + "?" + query
}
}
#[allow(clippy::type_complexity)]
fn handle_response<IV>(
method: Method,
additional_context: impl Fn() + 'static + Clone + Send,
app_fn: impl Fn() -> IV + Clone + Send + 'static,
stream_builder: fn(
IV,
BoxedFnOnce<PinnedStream<String>>,
bool,
) -> PinnedFuture<PinnedStream<String>>,
) -> Route
where
IV: IntoView + 'static,
{
let handler = move |req: HttpRequest| {
let app_fn = app_fn.clone();
let add_context = additional_context.clone();
async move {
let is_island_router_navigation = cfg!(feature = "islands-router")
&& req.headers().get("Islands-Router").is_some();
let res_options = ResponseOptions::default();
let (meta_context, meta_output) = ServerMetaContext::new();
let additional_context = {
let meta_context = meta_context.clone();
let res_options = res_options.clone();
let req = Request::new(&req);
move || {
provide_contexts(req, &meta_context, &res_options);
add_context();
if is_island_router_navigation {
provide_context(IslandsRouterNavigation);
}
}
};
let res = ActixResponse::from_app(
app_fn,
meta_output,
additional_context,
res_options,
stream_builder,
!is_island_router_navigation,
)
.await;
res.0
}
};
match method {
Method::Get => web::get().to(handler),
Method::Post => web::post().to(handler),
Method::Put => web::put().to(handler),
Method::Delete => web::delete().to(handler),
Method::Patch => web::patch().to(handler),
}
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
/// create routes in Actix's App without having to use wildcard matching or fallbacks. Takes in your root app Element
/// as an argument so it can walk you app tree. This version is tailored to generated Actix compatible paths.
pub fn generate_route_list<IV>(
app_fn: impl Fn() -> IV + 'static + Send + Clone,
) -> Vec<ActixRouteListing>
where
IV: IntoView + 'static,
{
generate_route_list_with_exclusions_and_ssg(app_fn, None).0
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
/// create routes in Actix's App without having to use wildcard matching or fallbacks. Takes in your root app Element
/// as an argument so it can walk you app tree. This version is tailored to generated Actix compatible paths.
pub fn generate_route_list_with_ssg<IV>(
app_fn: impl Fn() -> IV + 'static + Send + Clone,
) -> (Vec<ActixRouteListing>, StaticRouteGenerator)
where
IV: IntoView + 'static,
{
generate_route_list_with_exclusions_and_ssg(app_fn, None)
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
/// create routes in Actix's App without having to use wildcard matching or fallbacks. Takes in your root app Element
/// as an argument so it can walk you app tree. This version is tailored to generated Actix compatible paths. Adding excluded_routes
/// to this function will stop `.leptos_routes()` from generating a route for it, allowing a custom handler. These need to be in Actix path format
pub fn generate_route_list_with_exclusions<IV>(
app_fn: impl Fn() -> IV + 'static + Send + Clone,
excluded_routes: Option<Vec<String>>,
) -> Vec<ActixRouteListing>
where
IV: IntoView + 'static,
{
generate_route_list_with_exclusions_and_ssg(app_fn, excluded_routes).0
}
/// Generates a list of all routes defined in Leptos's Router in your app. We can then use this to automatically
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/integrations/actix/tests/extract_routes.rs | integrations/actix/tests/extract_routes.rs | // TODO these tests relate to trailing-slash logic, which is still TBD for 0.7
// use leptos::*;
// use leptos_actix::generate_route_list;
// use leptos_router::{
// components::{Route, Router, Routes},
// path,
// };
//
// #[component]
// fn DefaultApp() -> impl IntoView {
// let view = || view! { "" };
// view! {
// <Router>
// <Routes>
// <Route path=path!("/foo") view/>
// <Route path=path!("/bar/") view/>
// <Route path=path!("/baz/:id") view/>
// <Route path=path!("/baz/:name/") view/>
// <Route path=path!("/baz/*any") view/>
// </Routes>
// </Router>
// }
// }
//
// #[test]
// fn test_default_app() {
// let routes = generate_route_list(DefaultApp);
//
// // We still have access to the original (albeit normalized) Leptos paths:
// assert_same(
// &routes,
// |r| r.leptos_path(),
// &["/bar", "/baz/*any", "/baz/:id", "/baz/:name", "/foo"],
// );
//
// // ... But leptos-actix has also reformatted "paths" to work for Actix.
// assert_same(
// &routes,
// |r| r.path(),
// &["/bar", "/baz/{id}", "/baz/{name}", "/baz/{tail:.*}", "/foo"],
// );
// }
//
// #[component]
// fn ExactApp() -> impl IntoView {
// let view = || view! { "" };
// //let trailing_slash = TrailingSlash::Exact;
// view! {
// <Router>
// <Routes>
// <Route path=path!("/foo") view/>
// <Route path=path!("/bar/") view/>
// <Route path=path!("/baz/:id") view/>
// <Route path=path!("/baz/:name/") view/>
// <Route path=path!("/baz/*any") view/>
// </Routes>
// </Router>
// }
// }
//
// #[test]
// fn test_exact_app() {
// let routes = generate_route_list(ExactApp);
//
// // In Exact mode, the Leptos paths no longer have their trailing slashes stripped:
// assert_same(
// &routes,
// |r| r.leptos_path(),
// &["/bar/", "/baz/*any", "/baz/:id", "/baz/:name/", "/foo"],
// );
//
// // Actix paths also have trailing slashes as a result:
// assert_same(
// &routes,
// |r| r.path(),
// &[
// "/bar/",
// "/baz/{id}",
// "/baz/{name}/",
// "/baz/{tail:.*}",
// "/foo",
// ],
// );
// }
//
// #[component]
// fn RedirectApp() -> impl IntoView {
// let view = || view! { "" };
// //let trailing_slash = TrailingSlash::Redirect;
// view! {
// <Router>
// <Routes>
// <Route path=path!("/foo") view/>
// <Route path=path!("/bar/") view/>
// <Route path=path!("/baz/:id") view/>
// <Route path=path!("/baz/:name/") view/>
// <Route path=path!("/baz/*any") view/>
// </Routes>
// </Router>
// }
// }
//
// #[test]
// fn test_redirect_app() {
// let routes = generate_route_list(RedirectApp);
//
// assert_same(
// &routes,
// |r| r.leptos_path(),
// &[
// "/bar",
// "/bar/",
// "/baz/*any",
// "/baz/:id",
// "/baz/:id/",
// "/baz/:name",
// "/baz/:name/",
// "/foo",
// "/foo/",
// ],
// );
//
// // ... But leptos-actix has also reformatted "paths" to work for Actix.
// assert_same(
// &routes,
// |r| r.path(),
// &[
// "/bar",
// "/bar/",
// "/baz/{id}",
// "/baz/{id}/",
// "/baz/{name}",
// "/baz/{name}/",
// "/baz/{tail:.*}",
// "/foo",
// "/foo/",
// ],
// );
// }
//
// fn assert_same<'t, T, F, U>(
// input: &'t Vec<T>,
// mapper: F,
// expected_sorted_values: &[U],
// ) where
// F: Fn(&'t T) -> U + 't,
// U: Ord + std::fmt::Debug,
// {
// let mut values: Vec<U> = input.iter().map(mapper).collect();
// values.sort();
// assert_eq!(values, expected_sorted_values);
// }
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/src/lib.rs | any_spawner/src/lib.rs | //! This crate makes it easier to write asynchronous code that is executor-agnostic, by providing a
//! utility that can be used to spawn tasks in a variety of executors.
//!
//! It only supports single executor per program, but that executor can be set at runtime, anywhere
//! in your crate (or an application that depends on it).
//!
//! This can be extended to support any executor or runtime that supports spawning [`Future`]s.
//!
//! This is a least common denominator implementation in many ways. Limitations include:
//! - setting an executor is a one-time, global action
//! - no "join handle" or other result is returned from the spawn
//! - the `Future` must output `()`
//!
//! ```no_run
//! use any_spawner::Executor;
//!
//! // make sure an Executor has been initialized with one of the init_ functions
//!
//! // spawn a thread-safe Future
//! Executor::spawn(async { /* ... */ });
//!
//! // spawn a Future that is !Send
//! Executor::spawn_local(async { /* ... */ });
//! ```
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
use std::{future::Future, pin::Pin, sync::OnceLock};
use thiserror::Error;
/// A future that has been pinned.
pub type PinnedFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
/// A future that has been pinned.
pub type PinnedLocalFuture<T> = Pin<Box<dyn Future<Output = T>>>;
// Type alias for the spawn function pointer.
type SpawnFn = fn(PinnedFuture<()>);
// Type alias for the spawn_local function pointer.
type SpawnLocalFn = fn(PinnedLocalFuture<()>);
// Type alias for the poll_local function pointer.
type PollLocalFn = fn();
/// Holds the function pointers for the current global executor.
#[derive(Clone, Copy)]
struct ExecutorFns {
spawn: SpawnFn,
spawn_local: SpawnLocalFn,
poll_local: PollLocalFn,
}
// Use a single OnceLock to ensure atomic initialization of all functions.
static EXECUTOR_FNS: OnceLock<ExecutorFns> = OnceLock::new();
// No-op functions to use when an executor doesn't support a specific operation.
#[cfg(any(feature = "tokio", feature = "wasm-bindgen", feature = "glib"))]
#[cold]
#[inline(never)]
fn no_op_poll() {}
#[cfg(all(not(feature = "wasm-bindgen"), not(debug_assertions)))]
#[cold]
#[inline(never)]
fn no_op_spawn(_: PinnedFuture<()>) {
#[cfg(debug_assertions)]
eprintln!(
"Warning: Executor::spawn called, but no global 'spawn' function is \
configured (perhaps only spawn_local is supported, e.g., on wasm \
without threading?)."
);
}
// Wasm panics if you spawn without an executor
#[cfg(feature = "wasm-bindgen")]
#[cold]
#[inline(never)]
fn no_op_spawn(_: PinnedFuture<()>) {
panic!(
"Executor::spawn called, but no global 'spawn' function is configured."
);
}
#[cfg(not(debug_assertions))]
#[cold]
#[inline(never)]
fn no_op_spawn_local(_: PinnedLocalFuture<()>) {
panic!(
"Executor::spawn_local called, but no global 'spawn_local' function \
is configured."
);
}
/// Errors that can occur when using the executor.
#[derive(Error, Debug)]
pub enum ExecutorError {
/// The executor has already been set.
#[error("Global executor has already been set.")]
AlreadySet,
}
/// A global async executor that can spawn tasks.
pub struct Executor;
impl Executor {
/// Spawns a thread-safe [`Future`].
///
/// Uses the globally configured executor.
/// Panics if no global executor has been initialized.
#[inline(always)]
#[track_caller]
pub fn spawn(fut: impl Future<Output = ()> + Send + 'static) {
let pinned_fut = Box::pin(fut);
if let Some(fns) = EXECUTOR_FNS.get() {
(fns.spawn)(pinned_fut)
} else {
// No global executor set.
handle_uninitialized_spawn(pinned_fut);
}
}
/// Spawns a [`Future`] that cannot be sent across threads.
///
/// Uses the globally configured executor.
/// Panics if no global executor has been initialized.
#[inline(always)]
#[track_caller]
pub fn spawn_local(fut: impl Future<Output = ()> + 'static) {
let pinned_fut = Box::pin(fut);
if let Some(fns) = EXECUTOR_FNS.get() {
(fns.spawn_local)(pinned_fut)
} else {
// No global executor set.
handle_uninitialized_spawn_local(pinned_fut);
}
}
/// Waits until the next "tick" of the current async executor.
/// Respects the global executor.
#[inline(always)]
pub async fn tick() {
let (tx, rx) = futures::channel::oneshot::channel();
#[cfg(not(all(feature = "wasm-bindgen", target_family = "wasm")))]
Executor::spawn(async move {
_ = tx.send(());
});
#[cfg(all(feature = "wasm-bindgen", target_family = "wasm"))]
Executor::spawn_local(async move {
_ = tx.send(());
});
_ = rx.await;
}
/// Polls the global async executor.
///
/// Uses the globally configured executor.
/// Does nothing if the global executor does not support polling.
#[inline(always)]
pub fn poll_local() {
if let Some(fns) = EXECUTOR_FNS.get() {
(fns.poll_local)()
}
// If not initialized or doesn't support polling, do nothing gracefully.
}
}
impl Executor {
/// Globally sets the [`tokio`] runtime as the executor used to spawn tasks.
///
/// Returns `Err(_)` if a global executor has already been set.
///
/// Requires the `tokio` feature to be activated on this crate.
#[cfg(feature = "tokio")]
#[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
pub fn init_tokio() -> Result<(), ExecutorError> {
let executor_impl = ExecutorFns {
spawn: |fut| {
tokio::spawn(fut);
},
spawn_local: |fut| {
tokio::task::spawn_local(fut);
},
// Tokio doesn't have an explicit global poll function like LocalPool::run_until_stalled
poll_local: no_op_poll,
};
EXECUTOR_FNS
.set(executor_impl)
.map_err(|_| ExecutorError::AlreadySet)
}
/// Globally sets the [`wasm-bindgen-futures`] runtime as the executor used to spawn tasks.
///
/// Returns `Err(_)` if a global executor has already been set.
///
/// Requires the `wasm-bindgen` feature to be activated on this crate.
#[cfg(feature = "wasm-bindgen")]
#[cfg_attr(docsrs, doc(cfg(feature = "wasm-bindgen")))]
pub fn init_wasm_bindgen() -> Result<(), ExecutorError> {
let executor_impl = ExecutorFns {
// wasm-bindgen-futures only supports spawn_local
spawn: no_op_spawn,
spawn_local: |fut| {
wasm_bindgen_futures::spawn_local(fut);
},
poll_local: no_op_poll,
};
EXECUTOR_FNS
.set(executor_impl)
.map_err(|_| ExecutorError::AlreadySet)
}
/// Globally sets the [`glib`] runtime as the executor used to spawn tasks.
///
/// Returns `Err(_)` if a global executor has already been set.
///
/// Requires the `glib` feature to be activated on this crate.
#[cfg(feature = "glib")]
#[cfg_attr(docsrs, doc(cfg(feature = "glib")))]
pub fn init_glib() -> Result<(), ExecutorError> {
let executor_impl = ExecutorFns {
spawn: |fut| {
let main_context = glib::MainContext::default();
main_context.spawn(fut);
},
spawn_local: |fut| {
let main_context = glib::MainContext::default();
main_context.spawn_local(fut);
},
// Glib needs event loop integration, explicit polling isn't the standard model here.
poll_local: no_op_poll,
};
EXECUTOR_FNS
.set(executor_impl)
.map_err(|_| ExecutorError::AlreadySet)
}
/// Globally sets the [`futures`] executor as the executor used to spawn tasks,
/// lazily creating a thread pool to spawn tasks into.
///
/// Returns `Err(_)` if a global executor has already been set.
///
/// Requires the `futures-executor` feature to be activated on this crate.
#[cfg(feature = "futures-executor")]
#[cfg_attr(docsrs, doc(cfg(feature = "futures-executor")))]
pub fn init_futures_executor() -> Result<(), ExecutorError> {
use futures::{
executor::{LocalPool, LocalSpawner, ThreadPool},
task::{LocalSpawnExt, SpawnExt},
};
use std::cell::RefCell;
// Keep the lazy-init ThreadPool and thread-local LocalPool for spawn_local impl
static THREAD_POOL: OnceLock<ThreadPool> = OnceLock::new();
thread_local! {
static LOCAL_POOL: RefCell<LocalPool> = RefCell::new(LocalPool::new());
// SPAWNER is derived from LOCAL_POOL, keep it for efficiency inside the closure
static SPAWNER: LocalSpawner = LOCAL_POOL.with(|pool| pool.borrow().spawner());
}
fn get_thread_pool() -> &'static ThreadPool {
THREAD_POOL.get_or_init(|| {
ThreadPool::new()
.expect("could not create futures executor ThreadPool")
})
}
let executor_impl = ExecutorFns {
spawn: |fut| {
get_thread_pool()
.spawn(fut)
.expect("failed to spawn future on ThreadPool");
},
spawn_local: |fut| {
// Use the thread_local SPAWNER derived from LOCAL_POOL
SPAWNER.with(|spawner| {
spawner
.spawn_local(fut)
.expect("failed to spawn local future");
});
},
poll_local: || {
// Use the thread_local LOCAL_POOL
LOCAL_POOL.with(|pool| {
// Use try_borrow_mut to prevent panic during re-entrant calls
if let Ok(mut pool) = pool.try_borrow_mut() {
pool.run_until_stalled();
}
// If already borrowed, we're likely in a nested poll, so do nothing.
});
},
};
EXECUTOR_FNS
.set(executor_impl)
.map_err(|_| ExecutorError::AlreadySet)
}
/// Globally sets the [`async_executor`] executor as the executor used to spawn tasks,
/// lazily creating a thread pool to spawn tasks into.
///
/// Returns `Err(_)` if a global executor has already been set.
///
/// Requires the `async-executor` feature to be activated on this crate.
#[cfg(feature = "async-executor")]
#[cfg_attr(docsrs, doc(cfg(feature = "async-executor")))]
pub fn init_async_executor() -> Result<(), ExecutorError> {
use async_executor::{Executor as AsyncExecutor, LocalExecutor};
// Keep the lazy-init global Executor and thread-local LocalExecutor for spawn_local impl
static ASYNC_EXECUTOR: OnceLock<AsyncExecutor<'static>> =
OnceLock::new();
thread_local! {
static LOCAL_EXECUTOR_POOL: LocalExecutor<'static> = const { LocalExecutor::new() };
}
fn get_async_executor() -> &'static AsyncExecutor<'static> {
ASYNC_EXECUTOR.get_or_init(AsyncExecutor::new)
}
let executor_impl = ExecutorFns {
spawn: |fut| {
get_async_executor().spawn(fut).detach();
},
spawn_local: |fut| {
LOCAL_EXECUTOR_POOL.with(|pool| pool.spawn(fut).detach());
},
poll_local: || {
LOCAL_EXECUTOR_POOL.with(|pool| {
// try_tick polls the local executor without blocking
// This prevents issues if called recursively or from within a task.
pool.try_tick();
});
},
};
EXECUTOR_FNS
.set(executor_impl)
.map_err(|_| ExecutorError::AlreadySet)
}
/// Globally sets a custom executor as the executor used to spawn tasks.
///
/// Requires the custom executor to be `Send + Sync` as it will be stored statically.
///
/// Returns `Err(_)` if a global executor has already been set.
pub fn init_custom_executor(
custom_executor: impl CustomExecutor + Send + Sync + 'static,
) -> Result<(), ExecutorError> {
// Store the custom executor instance itself to call its methods.
// Use Box for dynamic dispatch.
static CUSTOM_EXECUTOR_INSTANCE: OnceLock<
Box<dyn CustomExecutor + Send + Sync>,
> = OnceLock::new();
CUSTOM_EXECUTOR_INSTANCE
.set(Box::new(custom_executor))
.map_err(|_| ExecutorError::AlreadySet)?;
// Now set the ExecutorFns using the stored instance
let executor_impl = ExecutorFns {
spawn: |fut| {
// Unwrap is safe because we just set it successfully or returned Err.
CUSTOM_EXECUTOR_INSTANCE.get().unwrap().spawn(fut);
},
spawn_local: |fut| {
CUSTOM_EXECUTOR_INSTANCE.get().unwrap().spawn_local(fut);
},
poll_local: || {
CUSTOM_EXECUTOR_INSTANCE.get().unwrap().poll_local();
},
};
EXECUTOR_FNS
.set(executor_impl)
.map_err(|_| ExecutorError::AlreadySet)
// If setting EXECUTOR_FNS fails (extremely unlikely race if called *concurrently*
// with another init_* after CUSTOM_EXECUTOR_INSTANCE was set), we technically
// leave CUSTOM_EXECUTOR_INSTANCE set but EXECUTOR_FNS not. This is an edge case,
// but the primary race condition is solved.
}
/// Sets a custom executor *for the current thread only*.
///
/// This overrides the global executor for calls to `spawn`, `spawn_local`, and `poll_local`
/// made *from the current thread*. It does not affect other threads or the global state.
///
/// The provided `custom_executor` must implement [`CustomExecutor`] and `'static`, but does
/// **not** need to be `Send` or `Sync`.
///
/// Returns `Err(ExecutorError::AlreadySet)` if a *local* executor has already been set
/// *for this thread*.
pub fn init_local_custom_executor(
custom_executor: impl CustomExecutor + 'static,
) -> Result<(), ExecutorError> {
// Store the custom executor instance itself to call its methods.
// Use Box for dynamic dispatch.
thread_local! {
static CUSTOM_EXECUTOR_INSTANCE: OnceLock<
Box<dyn CustomExecutor>,
> = OnceLock::new();
};
CUSTOM_EXECUTOR_INSTANCE.with(|this| {
this.set(Box::new(custom_executor))
.map_err(|_| ExecutorError::AlreadySet)
})?;
// Now set the ExecutorFns using the stored instance
let executor_impl = ExecutorFns {
spawn: |fut| {
// Unwrap is safe because we just set it successfully or returned Err.
CUSTOM_EXECUTOR_INSTANCE
.with(|this| this.get().unwrap().spawn(fut));
},
spawn_local: |fut| {
CUSTOM_EXECUTOR_INSTANCE
.with(|this| this.get().unwrap().spawn_local(fut));
},
poll_local: || {
CUSTOM_EXECUTOR_INSTANCE
.with(|this| this.get().unwrap().poll_local());
},
};
EXECUTOR_FNS
.set(executor_impl)
.map_err(|_| ExecutorError::AlreadySet)
}
}
/// A trait for custom executors.
/// Custom executors can be used to integrate with any executor that supports spawning futures.
///
/// If used with `init_custom_executor`, the implementation must be `Send + Sync + 'static`.
///
/// All methods can be called recursively. Implementors should be mindful of potential
/// deadlocks or excessive resource consumption if recursive calls are not handled carefully
/// (e.g., using `try_borrow_mut` or non-blocking polls within implementations).
pub trait CustomExecutor {
/// Spawns a future, usually on a thread pool.
fn spawn(&self, fut: PinnedFuture<()>);
/// Spawns a local future. May require calling `poll_local` to make progress.
fn spawn_local(&self, fut: PinnedLocalFuture<()>);
/// Polls the executor, if it supports polling. Implementations should ideally be
/// non-blocking or use mechanisms like `try_tick` or `try_borrow_mut` to handle
/// re-entrant calls safely.
fn poll_local(&self);
}
// Ensure CustomExecutor is object-safe
#[allow(dead_code)]
fn test_object_safety(_: Box<dyn CustomExecutor + Send + Sync>) {} // Added Send + Sync constraint here for global usage
/// Handles the case where `Executor::spawn` is called without an initialized executor.
#[cold] // Less likely path
#[inline(never)]
#[track_caller]
fn handle_uninitialized_spawn(_fut: PinnedFuture<()>) {
let caller = std::panic::Location::caller();
#[cfg(all(debug_assertions, feature = "tracing"))]
{
tracing::error!(
target: "any_spawner",
spawn_caller=%caller,
"Executor::spawn called before a global executor was initialized. Task dropped."
);
// Drop the future implicitly after logging
drop(_fut);
}
#[cfg(all(debug_assertions, not(feature = "tracing")))]
{
panic!(
"At {caller}, tried to spawn a Future with Executor::spawn() \
before a global executor was initialized."
);
}
// In release builds (without tracing), call the specific no-op function.
#[cfg(not(debug_assertions))]
{
no_op_spawn(_fut);
}
}
/// Handles the case where `Executor::spawn_local` is called without an initialized executor.
#[cold] // Less likely path
#[inline(never)]
#[track_caller]
fn handle_uninitialized_spawn_local(_fut: PinnedLocalFuture<()>) {
let caller = std::panic::Location::caller();
#[cfg(all(debug_assertions, feature = "tracing"))]
{
tracing::error!(
target: "any_spawner",
spawn_caller=%caller,
"Executor::spawn_local called before a global executor was initialized. \
Task likely dropped or panicked."
);
// Fall through to panic or no-op depending on build/target
}
#[cfg(all(debug_assertions, not(feature = "tracing")))]
{
panic!(
"At {caller}, tried to spawn a Future with \
Executor::spawn_local() before a global executor was initialized."
);
}
// In release builds (without tracing), call the specific no-op function (which usually panics).
#[cfg(not(debug_assertions))]
{
no_op_spawn_local(_fut);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/futures_runtime.rs | any_spawner/tests/futures_runtime.rs | #![cfg(feature = "futures-executor")]
use any_spawner::Executor;
// All tests in this file use the same executor.
#[test]
fn can_spawn_local_future() {
use std::rc::Rc;
let _ = Executor::init_futures_executor();
let rc = Rc::new(());
Executor::spawn_local(async {
_ = rc;
});
Executor::spawn(async {});
}
#[test]
fn can_make_local_progress() {
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
let _ = Executor::init_futures_executor();
let counter = Arc::new(AtomicUsize::new(0));
Executor::spawn_local({
let counter = Arc::clone(&counter);
async move {
assert_eq!(counter.fetch_add(1, Ordering::AcqRel), 0);
Executor::spawn_local(async {
// Should not crash
});
}
});
Executor::poll_local();
assert_eq!(counter.load(Ordering::Acquire), 1);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/already_set_error.rs | any_spawner/tests/already_set_error.rs | use any_spawner::{Executor, ExecutorError};
#[test]
fn test_already_set_error() {
struct SimpleExecutor;
impl any_spawner::CustomExecutor for SimpleExecutor {
fn spawn(&self, _fut: any_spawner::PinnedFuture<()>) {}
fn spawn_local(&self, _fut: any_spawner::PinnedLocalFuture<()>) {}
fn poll_local(&self) {}
}
// First initialization should succeed
Executor::init_custom_executor(SimpleExecutor)
.expect("First initialization failed");
// Second initialization should fail with AlreadySet error
let result = Executor::init_custom_executor(SimpleExecutor);
assert!(matches!(result, Err(ExecutorError::AlreadySet)));
// First local initialization should fail
let result = Executor::init_local_custom_executor(SimpleExecutor);
assert!(matches!(result, Err(ExecutorError::AlreadySet)));
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/futures_executor.rs | any_spawner/tests/futures_executor.rs | #![cfg(feature = "futures-executor")]
use any_spawner::Executor;
use futures::channel::oneshot;
use std::{
sync::{Arc, Mutex},
time::Duration,
};
#[test]
fn test_futures_executor() {
// Initialize the futures executor
Executor::init_futures_executor()
.expect("Failed to initialize futures executor");
let (tx, rx) = oneshot::channel();
let result = Arc::new(Mutex::new(None));
let result_clone = result.clone();
// Spawn a task
Executor::spawn(async move {
tx.send(84).expect("Failed to send value");
});
// Spawn a task that waits for the result
Executor::spawn(async move {
match rx.await {
Ok(val) => *result_clone.lock().unwrap() = Some(val),
Err(_) => panic!("Failed to receive value"),
}
});
// Poll a few times to ensure the task completes
for _ in 0..10 {
Executor::poll_local();
std::thread::sleep(Duration::from_millis(10));
if result.lock().unwrap().is_some() {
break;
}
}
assert_eq!(*result.lock().unwrap(), Some(84));
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/wasm_bindgen_tests.rs | any_spawner/tests/wasm_bindgen_tests.rs | #![cfg(all(feature = "wasm-bindgen", target_family = "wasm"))]
use any_spawner::Executor;
use futures::channel::oneshot;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
async fn test_wasm_bindgen_spawn_local() {
// Initialize the wasm-bindgen executor
let _ = Executor::init_wasm_bindgen();
// Create a channel to verify the task completes
let (tx, rx) = oneshot::channel();
// Spawn a local task (wasm doesn't support sending futures between threads)
Executor::spawn_local(async move {
// Simulate some async work
Executor::tick().await;
tx.send(42).expect("Failed to send result");
});
// Wait for the task to complete
let result = rx.await.expect("Failed to receive result");
assert_eq!(result, 42);
}
#[wasm_bindgen_test]
async fn test_wasm_bindgen_tick() {
// Initialize the wasm-bindgen executor if not already initialized
let _ = Executor::init_wasm_bindgen();
let flag = Arc::new(AtomicBool::new(false));
let flag_clone = flag.clone();
// Spawn a task that will set the flag
Executor::spawn_local(async move {
flag_clone.store(true, Ordering::SeqCst);
});
// Wait for a tick, which should allow the spawned task to run
Executor::tick().await;
// Verify the flag was set
assert!(flag.load(Ordering::SeqCst));
}
#[wasm_bindgen_test]
async fn test_multiple_wasm_bindgen_tasks() {
// Initialize once for all tests
let _ = Executor::init_wasm_bindgen();
// Create channels for multiple tasks
let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel();
// Spawn multiple tasks
Executor::spawn_local(async move {
tx1.send("task1").expect("Failed to send from task1");
});
Executor::spawn_local(async move {
tx2.send("task2").expect("Failed to send from task2");
});
// Wait for both tasks to complete
let (result1, result2) = futures::join!(rx1, rx2);
assert_eq!(result1.unwrap(), "task1");
assert_eq!(result2.unwrap(), "task2");
}
// This test verifies that spawn (not local) fails on wasm as expected
#[wasm_bindgen_test]
#[should_panic]
fn test_wasm_bindgen_spawn_errors() {
let _ = Executor::init_wasm_bindgen();
// Using should_panic to test that Executor::spawn panics in wasm
Executor::spawn(async {
// This should panic since wasm-bindgen doesn't support Send futures
});
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/local_custom_executor.rs | any_spawner/tests/local_custom_executor.rs | use any_spawner::Executor;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
#[test]
fn test_local_custom_executor() {
// Define a thread-local custom executor
struct LocalTestExecutor {
spawn_called: Arc<AtomicBool>,
spawn_local_called: Arc<AtomicBool>,
}
impl any_spawner::CustomExecutor for LocalTestExecutor {
fn spawn(&self, fut: any_spawner::PinnedFuture<()>) {
self.spawn_called.store(true, Ordering::SeqCst);
futures::executor::block_on(fut);
}
fn spawn_local(&self, fut: any_spawner::PinnedLocalFuture<()>) {
self.spawn_local_called.store(true, Ordering::SeqCst);
futures::executor::block_on(fut);
}
fn poll_local(&self) {
// No-op for this test
}
}
let local_spawn_called = Arc::new(AtomicBool::new(false));
let local_spawn_local_called = Arc::new(AtomicBool::new(false));
let local_executor = LocalTestExecutor {
spawn_called: local_spawn_called.clone(),
spawn_local_called: local_spawn_local_called.clone(),
};
// Initialize a thread-local executor
Executor::init_local_custom_executor(local_executor)
.expect("Failed to initialize local custom executor");
// Test spawn - should use the thread-local executor
Executor::spawn(async {
// Simple task
});
assert!(local_spawn_called.load(Ordering::SeqCst));
// Test spawn_local - should use the thread-local executor
Executor::spawn_local(async {
// Simple local task
});
assert!(local_spawn_local_called.load(Ordering::SeqCst));
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/async_executor.rs | any_spawner/tests/async_executor.rs | #![cfg(feature = "async-executor")]
use std::{
future::Future,
pin::Pin,
sync::{Arc, Mutex},
};
// A simple async executor for testing
struct TestExecutor {
tasks: Mutex<Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>>,
}
impl TestExecutor {
fn new() -> Self {
TestExecutor {
tasks: Mutex::new(Vec::new()),
}
}
fn spawn<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static,
{
self.tasks.lock().unwrap().push(Box::pin(future));
}
fn run_all(&self) {
// Take all tasks out to process them
let tasks = self.tasks.lock().unwrap().drain(..).collect::<Vec<_>>();
// Use a basic future executor to run each task to completion
for mut task in tasks {
// Use futures-lite's block_on to complete the future
futures::executor::block_on(async {
unsafe {
let task_mut = Pin::new_unchecked(&mut task);
let _ = std::future::Future::poll(
task_mut,
&mut std::task::Context::from_waker(
futures::task::noop_waker_ref(),
),
);
}
});
}
}
}
#[test]
fn test_async_executor() {
let executor = Arc::new(TestExecutor::new());
let executor_clone = executor.clone();
// Create a spawner function that will use our test executor
let spawner = move |future| {
executor_clone.spawn(future);
};
// Prepare test data
let counter = Arc::new(Mutex::new(0));
let counter_clone = counter.clone();
// Use the spawner to spawn a task
spawner(async move {
*counter_clone.lock().unwrap() += 1;
});
// Run all tasks
executor.run_all();
// Check if the task completed correctly
assert_eq!(*counter.lock().unwrap(), 1);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/executor_tick.rs | any_spawner/tests/executor_tick.rs | #![cfg(feature = "tokio")]
use any_spawner::Executor;
use std::{
sync::{Arc, Mutex},
time::Duration,
};
#[tokio::test]
async fn test_executor_tick() {
// Initialize the tokio executor
Executor::init_tokio().expect("Failed to initialize tokio executor");
let value = Arc::new(Mutex::new(false));
let value_clone = value.clone();
// Spawn a task that sets the value after a tick
Executor::spawn(async move {
Executor::tick().await;
*value_clone.lock().unwrap() = true;
});
// Allow some time for the task to complete
tokio::time::sleep(Duration::from_millis(50)).await;
// Check that the value was set
assert!(*value.lock().unwrap());
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/tokio_executor.rs | any_spawner/tests/tokio_executor.rs | #![cfg(feature = "tokio")]
use any_spawner::Executor;
use futures::channel::oneshot;
#[tokio::test]
async fn test_tokio_executor() {
// Initialize the tokio executor
Executor::init_tokio().expect("Failed to initialize tokio executor");
let (tx, rx) = oneshot::channel();
// Spawn a task that sends a value
Executor::spawn(async move {
tx.send(42).expect("Failed to send value");
});
// Wait for the spawned task to complete
assert_eq!(rx.await.unwrap(), 42);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/multiple_tasks.rs | any_spawner/tests/multiple_tasks.rs | #![cfg(feature = "tokio")]
use any_spawner::Executor;
use futures::channel::oneshot;
use std::sync::{Arc, Mutex};
#[tokio::test]
async fn test_multiple_tasks() {
Executor::init_tokio().expect("Failed to initialize tokio executor");
let counter = Arc::new(Mutex::new(0));
let tasks = 10;
let mut handles = Vec::new();
// Spawn multiple tasks that increment the counter
for _ in 0..tasks {
let counter_clone = counter.clone();
let (tx, rx) = oneshot::channel();
Executor::spawn(async move {
*counter_clone.lock().unwrap() += 1;
tx.send(()).expect("Failed to send completion signal");
});
handles.push(rx);
}
// Wait for all tasks to complete
for handle in handles {
handle.await.expect("Task failed");
}
// Verify that all tasks incremented the counter
assert_eq!(*counter.lock().unwrap(), tasks);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/glib.rs | any_spawner/tests/glib.rs | #![cfg(feature = "glib")]
use any_spawner::Executor;
use glib::{MainContext, MainLoop};
use serial_test::serial;
use std::{
cell::Cell,
future::Future,
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
time::Duration,
};
// Helper to run a future to completion on a dedicated glib MainContext.
// Returns true if the future completed within the timeout, false otherwise.
fn run_on_glib_context<F>(fut: F)
where
F: Future<Output = ()> + Send + 'static,
{
let _ = Executor::init_glib();
let context = MainContext::default();
let main_loop = MainLoop::new(Some(&context), false);
let main_loop_clone = main_loop.clone();
Executor::spawn(async move {
fut.await;
main_loop_clone.quit();
});
main_loop.run();
}
// Helper to run a local (!Send) future on the glib context.
fn run_local_on_glib_context<F>(fut: F)
where
F: Future<Output = ()> + 'static,
{
let _ = Executor::init_glib();
let context = MainContext::default();
let main_loop = MainLoop::new(Some(&context), false);
let main_loop_clone = main_loop.clone();
Executor::spawn_local(async move {
fut.await;
main_loop_clone.quit();
});
main_loop.run();
}
// This test must run after a test that successfully initializes glib,
// or within its own process.
#[test]
#[serial]
fn test_glib_spawn() {
let success_flag = Arc::new(AtomicBool::new(false));
let flag_clone = success_flag.clone();
run_on_glib_context(async move {
// Simulate async work
futures_lite::future::yield_now().await;
flag_clone.store(true, Ordering::SeqCst);
// We need to give the spawned task time to run.
// The run_on_glib_context handles the main loop.
// We just need to ensure spawn happened correctly.
// Let's wait a tiny bit within the driving future to ensure spawn gets processed.
glib::timeout_future(Duration::from_millis(10)).await;
});
assert!(
success_flag.load(Ordering::SeqCst),
"Spawned future did not complete successfully"
);
}
// Similar conditions as test_glib_spawn regarding initialization state.
#[test]
#[serial]
fn test_glib_spawn_local() {
let success_flag = Rc::new(Cell::new(false));
let flag_clone = success_flag.clone();
run_local_on_glib_context(async move {
// Use Rc to make the future !Send
let non_send_data = Rc::new(Cell::new(10));
let data = non_send_data.get();
assert_eq!(data, 10, "Rc data should be accessible");
non_send_data.set(20); // Modify non-Send data
// Simulate async work
futures_lite::future::yield_now().await;
assert_eq!(
non_send_data.get(),
20,
"Rc data should persist modification"
);
flag_clone.set(true);
// Wait a tiny bit
glib::timeout_future(Duration::from_millis(10)).await;
});
assert!(
success_flag.get(),
"Spawned local future did not complete successfully"
);
}
// Test Executor::tick with glib backend
#[test]
#[serial]
fn test_glib_tick() {
run_on_glib_context(async {
let value = Arc::new(Mutex::new(false));
let value_clone = value.clone();
// Spawn a task that sets the value after a tick
Executor::spawn(async move {
Executor::tick().await;
*value_clone.lock().unwrap() = true;
});
// Allow some time for the task to complete
glib::timeout_future(Duration::from_millis(10)).await;
// Check that the value was set
assert!(*value.lock().unwrap());
});
}
// Test Executor::poll_local with glib backend (should be a no-op)
#[test]
#[serial]
fn test_glib_poll_local_is_no_op() {
// Ensure glib executor is initialized
let _ = Executor::init_glib();
// poll_local for glib is configured as a no-op
// Calling it should not panic or cause issues.
Executor::poll_local();
Executor::poll_local();
println!("Executor::poll_local called successfully (expected no-op).");
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/custom_executor.rs | any_spawner/tests/custom_executor.rs | use any_spawner::Executor;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
#[test]
fn test_custom_executor() {
// Define a simple custom executor
struct TestExecutor {
spawn_called: Arc<AtomicBool>,
spawn_local_called: Arc<AtomicBool>,
poll_local_called: Arc<AtomicBool>,
}
impl any_spawner::CustomExecutor for TestExecutor {
fn spawn(&self, fut: any_spawner::PinnedFuture<()>) {
self.spawn_called.store(true, Ordering::SeqCst);
// Execute the future immediately (this works for simple test futures)
futures::executor::block_on(fut);
}
fn spawn_local(&self, fut: any_spawner::PinnedLocalFuture<()>) {
self.spawn_local_called.store(true, Ordering::SeqCst);
// Execute the future immediately
futures::executor::block_on(fut);
}
fn poll_local(&self) {
self.poll_local_called.store(true, Ordering::SeqCst);
}
}
let spawn_called = Arc::new(AtomicBool::new(false));
let spawn_local_called = Arc::new(AtomicBool::new(false));
let poll_local_called = Arc::new(AtomicBool::new(false));
let executor = TestExecutor {
spawn_called: spawn_called.clone(),
spawn_local_called: spawn_local_called.clone(),
poll_local_called: poll_local_called.clone(),
};
// Initialize with our custom executor
Executor::init_custom_executor(executor)
.expect("Failed to initialize custom executor");
// Test spawn
Executor::spawn(async {
// Simple task
});
assert!(spawn_called.load(Ordering::SeqCst));
// Test spawn_local
Executor::spawn_local(async {
// Simple local task
});
assert!(spawn_local_called.load(Ordering::SeqCst));
// Test poll_local
Executor::poll_local();
assert!(poll_local_called.load(Ordering::SeqCst));
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_spawner/tests/custom_runtime.rs | any_spawner/tests/custom_runtime.rs | #![cfg(feature = "futures-executor")]
use any_spawner::{CustomExecutor, Executor, PinnedFuture, PinnedLocalFuture};
#[test]
fn can_create_custom_executor() {
use futures::{
executor::{LocalPool, LocalSpawner},
task::LocalSpawnExt,
};
use std::{
cell::RefCell,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
thread_local! {
static LOCAL_POOL: RefCell<LocalPool> = RefCell::new(LocalPool::new());
static SPAWNER: LocalSpawner = LOCAL_POOL.with(|pool| pool.borrow().spawner());
}
struct CustomFutureExecutor;
impl CustomExecutor for CustomFutureExecutor {
fn spawn(&self, _fut: PinnedFuture<()>) {
panic!("not supported in this test");
}
fn spawn_local(&self, fut: PinnedLocalFuture<()>) {
SPAWNER.with(|spawner| {
spawner.spawn_local(fut).expect("failed to spawn future");
});
}
fn poll_local(&self) {
LOCAL_POOL.with(|pool| {
if let Ok(mut pool) = pool.try_borrow_mut() {
pool.run_until_stalled();
}
// If we couldn't borrow_mut, we're in a nested call to poll, so we don't need to do anything.
});
}
}
Executor::init_custom_executor(CustomFutureExecutor)
.expect("couldn't set executor");
let counter = Arc::new(AtomicUsize::new(0));
let counter_clone = Arc::clone(&counter);
Executor::spawn_local(async move {
counter_clone.store(1, Ordering::Release);
});
Executor::poll_local();
assert_eq!(counter.load(Ordering::Acquire), 1);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/any_error/src/lib.rs | any_error/src/lib.rs | #![forbid(unsafe_code)]
#![deny(missing_docs)]
//! A utility library for wrapping arbitrary errors, and for “throwing” errors in a way
//! that can be caught by user-defined error hooks.
use std::{
cell::RefCell,
error,
fmt::{self, Display},
future::Future,
ops,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
/* Wrapper Types */
/// A generic wrapper for any error.
#[derive(Debug, Clone)]
#[repr(transparent)]
pub struct Error(Arc<dyn error::Error + Send + Sync>);
impl Error {
/// Converts the wrapper into the inner reference-counted error.
pub fn into_inner(self) -> Arc<dyn error::Error + Send + Sync> {
Arc::clone(&self.0)
}
}
impl ops::Deref for Error {
type Target = Arc<dyn error::Error + Send + Sync>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl<T> From<T> for Error
where
T: Into<Box<dyn error::Error + Send + Sync + 'static>>,
{
fn from(value: T) -> Self {
Error(Arc::from(value.into()))
}
}
/// Implements behavior that allows for global or scoped error handling.
///
/// This allows for both "throwing" errors to register them, and "clearing" errors when they are no
/// longer valid. This is useful for something like a user interface, in which an error can be
/// "thrown" on some invalid user input, and later "cleared" if the user corrects the input.
/// Keeping a unique identifier for each error allows the UI to be updated accordingly.
pub trait ErrorHook: Send + Sync {
/// Handles the given error, returning a unique identifier.
fn throw(&self, error: Error) -> ErrorId;
/// Clears the error associated with the given identifier.
fn clear(&self, id: &ErrorId);
}
/// A unique identifier for an error. This is returned when you call [`throw`], which calls a
/// global error handler.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Default)]
pub struct ErrorId(usize);
impl Display for ErrorId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
impl From<usize> for ErrorId {
fn from(value: usize) -> Self {
Self(value)
}
}
thread_local! {
static ERROR_HOOK: RefCell<Option<Arc<dyn ErrorHook>>> = RefCell::new(None);
}
/// Resets the error hook to its previous state when dropped.
pub struct ResetErrorHookOnDrop(Option<Arc<dyn ErrorHook>>);
impl Drop for ResetErrorHookOnDrop {
fn drop(&mut self) {
ERROR_HOOK.with_borrow_mut(|this| *this = self.0.take())
}
}
/// Returns the current error hook.
pub fn get_error_hook() -> Option<Arc<dyn ErrorHook>> {
ERROR_HOOK.with_borrow(Clone::clone)
}
/// Sets the current thread-local error hook, which will be invoked when [`throw`] is called.
pub fn set_error_hook(hook: Arc<dyn ErrorHook>) -> ResetErrorHookOnDrop {
ResetErrorHookOnDrop(
ERROR_HOOK.with_borrow_mut(|this| Option::replace(this, hook)),
)
}
/// Invokes the error hook set by [`set_error_hook`] with the given error.
pub fn throw(error: impl Into<Error>) -> ErrorId {
ERROR_HOOK
.with_borrow(|hook| hook.as_ref().map(|hook| hook.throw(error.into())))
.unwrap_or_default()
}
/// Clears the given error from the current error hook.
pub fn clear(id: &ErrorId) {
ERROR_HOOK
.with_borrow(|hook| hook.as_ref().map(|hook| hook.clear(id)))
.unwrap_or_default()
}
pin_project_lite::pin_project! {
/// A [`Future`] that reads the error hook that is set when it is created, and sets this as the
/// current error hook whenever it is polled.
pub struct ErrorHookFuture<Fut> {
hook: Option<Arc<dyn ErrorHook>>,
#[pin]
inner: Fut
}
}
impl<Fut> ErrorHookFuture<Fut> {
/// Reads the current hook and wraps the given [`Future`], returning a new `Future` that will
/// set the error hook whenever it is polled.
pub fn new(inner: Fut) -> Self {
Self {
hook: ERROR_HOOK.with_borrow(Clone::clone),
inner,
}
}
}
impl<Fut> Future for ErrorHookFuture<Fut>
where
Fut: Future,
{
type Output = Fut::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let _hook = this
.hook
.as_ref()
.map(|hook| set_error_hook(Arc::clone(hook)));
this.inner.poll(cx)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error as StdError;
#[derive(Debug)]
struct MyError;
impl Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MyError")
}
}
impl StdError for MyError {}
#[test]
fn test_from() {
let e = MyError;
let _le = Error::from(e);
let e = "some error".to_string();
let _le = Error::from(e);
let e = anyhow::anyhow!("anyhow error");
let _le = Error::from(e);
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn_macro/build.rs | server_fn_macro/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/server_fn_macro/src/lib.rs | server_fn_macro/src/lib.rs | #![cfg_attr(all(feature = "nightly", rustc_nightly), feature(proc_macro_span))]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
//! Implementation of the `server_fn` macro.
//!
//! This crate contains the implementation of the `server_fn` macro. [`server_macro_impl`] can be used to implement custom versions of the macro for different frameworks that allow users to pass a custom context from the server to the server function.
use convert_case::{Case, Converter};
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{format_ident, quote, quote_spanned, ToTokens};
use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
spanned::Spanned,
*,
};
/// A parsed server function call.
pub struct ServerFnCall {
args: ServerFnArgs,
body: ServerFnBody,
default_path: String,
server_fn_path: Option<Path>,
preset_server: Option<Type>,
default_protocol: Option<Type>,
default_input_encoding: Option<Type>,
default_output_encoding: Option<Type>,
}
impl ServerFnCall {
/// Parse the arguments of a server function call.
///
/// ```ignore
/// #[proc_macro_attribute]
/// pub fn server(args: proc_macro::TokenStream, s: TokenStream) -> TokenStream {
/// match ServerFnCall::parse(
/// "/api",
/// args.into(),
/// s.into(),
/// ) {
/// Err(e) => e.to_compile_error().into(),
/// Ok(s) => s.to_token_stream().into(),
/// }
/// }
/// ```
pub fn parse(
default_path: &str,
args: TokenStream2,
body: TokenStream2,
) -> Result<Self> {
let args = syn::parse2(args)?;
let body = syn::parse2(body)?;
let mut myself = ServerFnCall {
default_path: default_path.into(),
args,
body,
server_fn_path: None,
preset_server: None,
default_protocol: None,
default_input_encoding: None,
default_output_encoding: None,
};
// We need to make the server function body send if actix is enabled. To
// do that, we wrap the body in a SendWrapper, which is an async fn that
// asserts that the future is always polled from the same thread.
if cfg!(feature = "actix") {
let server_fn_path = myself.server_fn_path();
let block = myself.body.block.to_token_stream();
myself.body.block = quote! {
{
#server_fn_path::actix::SendWrapper::new(async move {
#block
})
.await
}
};
}
Ok(myself)
}
/// Get a reference to the server function arguments.
pub fn get_args(&self) -> &ServerFnArgs {
&self.args
}
/// Get a mutable reference to the server function arguments.
pub fn get_args_mut(&mut self) -> &mut ServerFnArgs {
&mut self.args
}
/// Get a reference to the server function body.
pub fn get_body(&self) -> &ServerFnBody {
&self.body
}
/// Get a mutable reference to the server function body.
pub fn get_body_mut(&mut self) -> &mut ServerFnBody {
&mut self.body
}
/// Set the path to the server function crate.
pub fn default_server_fn_path(mut self, path: Option<Path>) -> Self {
self.server_fn_path = path;
self
}
/// Set the default server implementation.
pub fn default_server_type(mut self, server: Option<Type>) -> Self {
self.preset_server = server;
self
}
/// Set the default protocol.
pub fn default_protocol(mut self, protocol: Option<Type>) -> Self {
self.default_protocol = protocol;
self
}
/// Set the default input http encoding. This will be used by [`Self::protocol`]
/// if no protocol or default protocol is set or if only the output encoding is set
///
/// Defaults to `PostUrl`
pub fn default_input_encoding(mut self, protocol: Option<Type>) -> Self {
self.default_input_encoding = protocol;
self
}
/// Set the default output http encoding. This will be used by [`Self::protocol`]
/// if no protocol or default protocol is set or if only the input encoding is set
///
/// Defaults to `Json`
pub fn default_output_encoding(mut self, protocol: Option<Type>) -> Self {
self.default_output_encoding = protocol;
self
}
/// Get the client type to use for the server function.
pub fn client_type(&self) -> Type {
let server_fn_path = self.server_fn_path();
if let Some(client) = self.args.client.clone() {
client
} else if cfg!(feature = "reqwest") {
parse_quote! {
#server_fn_path::client::reqwest::ReqwestClient
}
} else {
parse_quote! {
#server_fn_path::client::browser::BrowserClient
}
}
}
/// Get the server type to use for the server function.
pub fn server_type(&self) -> Type {
let server_fn_path = self.server_fn_path();
if !cfg!(feature = "ssr") {
parse_quote! {
#server_fn_path::mock::BrowserMockServer
}
} else if cfg!(feature = "axum") {
parse_quote! {
#server_fn_path::axum::AxumServerFnBackend
}
} else if cfg!(feature = "actix") {
parse_quote! {
#server_fn_path::actix::ActixServerFnBackend
}
} else if cfg!(feature = "generic") {
parse_quote! {
#server_fn_path::axum::AxumServerFnBackend
}
} else if let Some(server) = &self.args.server {
server.clone()
} else if let Some(server) = &self.preset_server {
server.clone()
} else {
// fall back to the browser version, to avoid erroring out
// in things like doctests
// in reality, one of the above needs to be set
parse_quote! {
#server_fn_path::mock::BrowserMockServer
}
}
}
/// Get the path to the server_fn crate.
pub fn server_fn_path(&self) -> Path {
self.server_fn_path
.clone()
.unwrap_or_else(|| parse_quote! { server_fn })
}
/// Get the input http encoding if no protocol is set
fn input_http_encoding(&self) -> Type {
let server_fn_path = self.server_fn_path();
self.args
.input
.as_ref()
.map(|n| {
if self.args.builtin_encoding {
parse_quote! { #server_fn_path::codec::#n }
} else {
n.clone()
}
})
.unwrap_or_else(|| {
self.default_input_encoding.clone().unwrap_or_else(
|| parse_quote!(#server_fn_path::codec::PostUrl),
)
})
}
/// Get the output http encoding if no protocol is set
fn output_http_encoding(&self) -> Type {
let server_fn_path = self.server_fn_path();
self.args
.output
.as_ref()
.map(|n| {
if self.args.builtin_encoding {
parse_quote! { #server_fn_path::codec::#n }
} else {
n.clone()
}
})
.unwrap_or_else(|| {
self.default_output_encoding.clone().unwrap_or_else(
|| parse_quote!(#server_fn_path::codec::Json),
)
})
}
/// Get the http input and output encodings for the server function
/// if no protocol is set
pub fn http_encodings(&self) -> Option<(Type, Type)> {
self.args
.protocol
.is_none()
.then(|| (self.input_http_encoding(), self.output_http_encoding()))
}
/// Get the protocol to use for the server function.
pub fn protocol(&self) -> Type {
let server_fn_path = self.server_fn_path();
let default_protocol = &self.default_protocol;
self.args.protocol.clone().unwrap_or_else(|| {
// If both the input and output encodings are none,
// use the default protocol
if self.args.input.is_none() && self.args.output.is_none() {
default_protocol.clone().unwrap_or_else(|| {
parse_quote! {
#server_fn_path::Http<#server_fn_path::codec::PostUrl, #server_fn_path::codec::Json>
}
})
} else {
// Otherwise use the input and output encodings, filling in
// defaults if necessary
let input = self.input_http_encoding();
let output = self.output_http_encoding();
parse_quote! {
#server_fn_path::Http<#input, #output>
}
}
})
}
fn input_ident(&self) -> Option<String> {
match &self.args.input {
Some(Type::Path(path)) => {
path.path.segments.last().map(|seg| seg.ident.to_string())
}
None => Some("PostUrl".to_string()),
_ => None,
}
}
fn websocket_protocol(&self) -> bool {
if let Type::Path(path) = self.protocol() {
path.path
.segments
.iter()
.any(|segment| segment.ident == "Websocket")
} else {
false
}
}
fn serde_path(&self) -> String {
let path = self
.server_fn_path()
.segments
.iter()
.map(|segment| segment.ident.to_string())
.collect::<Vec<_>>();
let path = path.join("::");
format!("{path}::serde")
}
/// Get the docs for the server function.
pub fn docs(&self) -> TokenStream2 {
// pass through docs from the function body
self.body
.docs
.iter()
.map(|(doc, span)| quote_spanned!(*span=> #[doc = #doc]))
.collect::<TokenStream2>()
}
/// Get the lint attributes for the server function.
pub fn lint_attrs(&self) -> TokenStream2 {
// pass through lint attributes from the function body
self.body
.lint_attrs
.iter()
.map(|lint_attr| quote!(#lint_attr))
.collect::<TokenStream2>()
}
fn fn_name_as_str(&self) -> String {
self.body.ident.to_string()
}
fn struct_tokens(&self) -> TokenStream2 {
let server_fn_path = self.server_fn_path();
let fn_name_as_str = self.fn_name_as_str();
let link_to_server_fn = format!(
"Serialized arguments for the [`{fn_name_as_str}`] server \
function.\n\n"
);
let args_docs = quote! {
#[doc = #link_to_server_fn]
};
let docs = self.docs();
let input_ident = self.input_ident();
enum PathInfo {
Serde,
Rkyv,
Bitcode,
None,
}
let (path, derives) = match input_ident.as_deref() {
Some("Rkyv") => (
PathInfo::Rkyv,
quote! {
Clone, #server_fn_path::rkyv::Archive, #server_fn_path::rkyv::Serialize, #server_fn_path::rkyv::Deserialize
},
),
Some("Bitcode") => (
PathInfo::Bitcode,
quote! {
Clone, #server_fn_path::bitcode::Encode, #server_fn_path::bitcode::Decode
},
),
Some("MultipartFormData")
| Some("Streaming")
| Some("StreamingText") => (PathInfo::None, quote! {}),
Some("SerdeLite") => (
PathInfo::Serde,
quote! {
Clone, #server_fn_path::serde_lite::Serialize, #server_fn_path::serde_lite::Deserialize
},
),
_ => match &self.args.input_derive {
Some(derives) => {
let d = &derives.elems;
(PathInfo::None, quote! { #d })
}
None => {
if self.websocket_protocol() {
(PathInfo::None, quote! {})
} else {
(
PathInfo::Serde,
quote! {
Clone, #server_fn_path::serde::Serialize, #server_fn_path::serde::Deserialize
},
)
}
}
},
};
let addl_path = match path {
PathInfo::Serde => {
let serde_path = self.serde_path();
quote! {
#[serde(crate = #serde_path)]
}
}
PathInfo::Bitcode => quote! {},
PathInfo::Rkyv => quote! {},
PathInfo::None => quote! {},
};
let lint_attrs = self.lint_attrs();
let vis = &self.body.vis;
let struct_name = self.struct_name();
let fields = self
.body
.inputs
.iter()
.map(|server_fn_arg| {
let mut typed_arg = server_fn_arg.arg.clone();
// strip `mut`, which is allowed in fn args but not in struct fields
if let Pat::Ident(ident) = &mut *typed_arg.pat {
ident.mutability = None;
}
let attrs = &server_fn_arg.server_fn_attributes;
quote! { #(#attrs ) * #vis #typed_arg }
})
.collect::<Vec<_>>();
quote! {
#args_docs
#docs
#[derive(Debug, #derives)]
#addl_path
#lint_attrs
#vis struct #struct_name {
#(#fields),*
}
}
}
/// Get the name of the server function struct that will be submitted to inventory.
///
/// This will either be the name specified in the macro arguments or the PascalCase
/// version of the function name.
pub fn struct_name(&self) -> Ident {
// default to PascalCase version of function name if no struct name given
self.args.struct_name.clone().unwrap_or_else(|| {
let upper_camel_case_name = Converter::new()
.from_case(Case::Snake)
.to_case(Case::UpperCamel)
.convert(self.body.ident.to_string());
Ident::new(&upper_camel_case_name, self.body.ident.span())
})
}
/// Wrap the struct name in any custom wrapper specified in the macro arguments
/// and return it as a type
fn wrapped_struct_name(&self) -> TokenStream2 {
let struct_name = self.struct_name();
if let Some(wrapper) = self.args.custom_wrapper.as_ref() {
quote! { #wrapper<#struct_name> }
} else {
quote! { #struct_name }
}
}
/// Wrap the struct name in any custom wrapper specified in the macro arguments
/// and return it as a type with turbofish
fn wrapped_struct_name_turbofish(&self) -> TokenStream2 {
let struct_name = self.struct_name();
if let Some(wrapper) = self.args.custom_wrapper.as_ref() {
quote! { #wrapper::<#struct_name> }
} else {
quote! { #struct_name }
}
}
/// Generate the code to submit the server function type to inventory.
pub fn submit_to_inventory(&self) -> TokenStream2 {
// auto-registration with inventory
if cfg!(feature = "ssr") {
let server_fn_path = self.server_fn_path();
let wrapped_struct_name = self.wrapped_struct_name();
let wrapped_struct_name_turbofish =
self.wrapped_struct_name_turbofish();
quote! {
#server_fn_path::inventory::submit! {{
use #server_fn_path::{ServerFn, codec::Encoding};
#server_fn_path::ServerFnTraitObj::new::<#wrapped_struct_name>(
|req| Box::pin(#wrapped_struct_name_turbofish::run_on_server(req)),
)
}}
}
} else {
quote! {}
}
}
/// Generate the server function's URL. This will be the prefix path, then by the
/// module path if `SERVER_FN_MOD_PATH` is set, then the function name, and finally
/// a hash of the function name and location in the source code.
pub fn server_fn_url(&self) -> TokenStream2 {
let default_path = &self.default_path;
let prefix =
self.args.prefix.clone().unwrap_or_else(|| {
LitStr::new(default_path, Span::call_site())
});
let server_fn_path = self.server_fn_path();
let fn_path = self.args.fn_path.clone().map(|fn_path| {
let fn_path = fn_path.value();
// Remove any leading slashes, then add one slash back
let fn_path = "/".to_string() + fn_path.trim_start_matches('/');
fn_path
});
let enable_server_fn_mod_path =
option_env!("SERVER_FN_MOD_PATH").is_some();
let mod_path = if enable_server_fn_mod_path {
quote! {
#server_fn_path::const_format::concatcp!(
#server_fn_path::const_str::replace!(module_path!(), "::", "/"),
"/"
)
}
} else {
quote! { "" }
};
let enable_hash = option_env!("DISABLE_SERVER_FN_HASH").is_none();
let key_env_var = match option_env!("SERVER_FN_OVERRIDE_KEY") {
Some(_) => "SERVER_FN_OVERRIDE_KEY",
None => "CARGO_MANIFEST_DIR",
};
let hash = if enable_hash {
quote! {
#server_fn_path::xxhash_rust::const_xxh64::xxh64(
concat!(env!(#key_env_var), ":", module_path!()).as_bytes(),
0
)
}
} else {
quote! { "" }
};
let fn_name_as_str = self.fn_name_as_str();
if let Some(fn_path) = fn_path {
quote! {
#server_fn_path::const_format::concatcp!(
#prefix,
#mod_path,
#fn_path
)
}
} else {
quote! {
#server_fn_path::const_format::concatcp!(
#prefix,
"/",
#mod_path,
#fn_name_as_str,
#hash
)
}
}
}
/// Get the names of the fields the server function takes as inputs.
fn field_names(&self) -> Vec<&std::boxed::Box<syn::Pat>> {
self.body
.inputs
.iter()
.map(|f| &f.arg.pat)
.collect::<Vec<_>>()
}
/// Generate the implementation for the server function trait.
fn server_fn_impl(&self) -> TokenStream2 {
let server_fn_path = self.server_fn_path();
let struct_name = self.struct_name();
let protocol = self.protocol();
let middlewares = &self.body.middlewares;
let return_ty = &self.body.return_ty;
let output_ty = self.body.output_ty
.as_ref()
.map_or_else(|| {
quote! {
<#return_ty as #server_fn_path::error::ServerFnMustReturnResult>::Ok
}
},
ToTokens::to_token_stream,
);
let error_ty = &self.body.error_ty;
let error_ty = error_ty
.as_ref()
.map_or_else(|| {
quote! {
<#return_ty as #server_fn_path::error::ServerFnMustReturnResult>::Err
}
},
ToTokens::to_token_stream,
);
let error_ws_in_ty = if self.websocket_protocol() {
self.body
.error_ws_in_ty
.as_ref()
.map(ToTokens::to_token_stream)
.unwrap_or(error_ty.clone())
} else {
error_ty.clone()
};
let error_ws_out_ty = if self.websocket_protocol() {
self.body
.error_ws_out_ty
.as_ref()
.map(ToTokens::to_token_stream)
.unwrap_or(error_ty.clone())
} else {
error_ty.clone()
};
let field_names = self.field_names();
// run_body in the trait implementation
let run_body = if cfg!(feature = "ssr") {
let destructure =
if let Some(wrapper) = self.args.custom_wrapper.as_ref() {
quote! {
let #wrapper(#struct_name { #(#field_names),* }) = self;
}
} else {
quote! {
let #struct_name { #(#field_names),* } = self;
}
};
let dummy_name = self.body.to_dummy_ident();
// using the impl Future syntax here is thanks to Actix
//
// if we use Actix types inside the function, here, it becomes !Send
// so we need to add SendWrapper, because Actix won't actually send it anywhere
// but if we used SendWrapper in an async fn, the types don't work out because it
// becomes impl Future<Output = SendWrapper<_>>
//
// however, SendWrapper<Future<Output = T>> impls Future<Output = T>
let body = quote! {
async move {
#destructure
#dummy_name(#(#field_names),*).await
}
};
quote! {
// we need this for Actix, for the SendWrapper to count as impl Future
// but non-Actix will have a clippy warning otherwise
#[allow(clippy::manual_async_fn)]
fn run_body(self) -> impl std::future::Future<Output = #return_ty> + Send {
#body
}
}
} else {
quote! {
#[allow(unused_variables)]
async fn run_body(self) -> #return_ty {
unreachable!()
}
}
};
let client = self.client_type();
let server = self.server_type();
// generate the url of the server function
let path = self.server_fn_url();
let middlewares = if cfg!(feature = "ssr") {
quote! {
vec![
#(
std::sync::Arc::new(#middlewares)
),*
]
}
} else {
quote! { vec![] }
};
let wrapped_struct_name = self.wrapped_struct_name();
quote! {
impl #server_fn_path::ServerFn for #wrapped_struct_name {
const PATH: &'static str = #path;
type Client = #client;
type Server = #server;
type Protocol = #protocol;
type Output = #output_ty;
type Error = #error_ty;
type InputStreamError = #error_ws_in_ty;
type OutputStreamError = #error_ws_out_ty;
fn middlewares() -> Vec<std::sync::Arc<dyn #server_fn_path::middleware::Layer<<Self::Server as #server_fn_path::server::Server<Self::Error>>::Request, <Self::Server as #server_fn_path::server::Server<Self::Error>>::Response>>> {
#middlewares
}
#run_body
}
}
}
/// Return the name and type of the first field if there is only one field.
fn single_field(&self) -> Option<(&Pat, &Type)> {
self.body
.inputs
.first()
.filter(|_| self.body.inputs.len() == 1)
.map(|field| (&*field.arg.pat, &*field.arg.ty))
}
fn deref_impl(&self) -> TokenStream2 {
let impl_deref = self
.args
.impl_deref
.as_ref()
.map(|v| v.value)
.unwrap_or(true)
|| self.websocket_protocol();
if !impl_deref {
return quote! {};
}
// if there's exactly one field, impl Deref<T> for the struct
let Some(single_field) = self.single_field() else {
return quote! {};
};
let struct_name = self.struct_name();
let (name, ty) = single_field;
quote! {
impl std::ops::Deref for #struct_name {
type Target = #ty;
fn deref(&self) -> &Self::Target {
&self.#name
}
}
}
}
fn impl_from(&self) -> TokenStream2 {
let impl_from = self
.args
.impl_from
.as_ref()
.map(|v| v.value)
.unwrap_or(true)
|| self.websocket_protocol();
if !impl_from {
return quote! {};
}
// if there's exactly one field, impl From<T> for the struct
let Some(single_field) = self.single_field() else {
return quote! {};
};
let struct_name = self.struct_name();
let (name, ty) = single_field;
quote! {
impl From<#struct_name> for #ty {
fn from(value: #struct_name) -> Self {
let #struct_name { #name } = value;
#name
}
}
impl From<#ty> for #struct_name {
fn from(#name: #ty) -> Self {
#struct_name { #name }
}
}
}
}
fn func_tokens(&self) -> TokenStream2 {
let body = &self.body;
// default values for args
let struct_name = self.struct_name();
// build struct for type
let fn_name = &body.ident;
let attrs = &body.attrs;
let fn_args = body.inputs.iter().map(|f| &f.arg).collect::<Vec<_>>();
let field_names = self.field_names();
// check output type
let output_arrow = body.output_arrow;
let return_ty = &body.return_ty;
let vis = &body.vis;
// Forward the docs from the function
let docs = self.docs();
// the actual function definition
if cfg!(feature = "ssr") {
let dummy_name = body.to_dummy_ident();
quote! {
#docs
#(#attrs)*
#vis async fn #fn_name(#(#fn_args),*) #output_arrow #return_ty {
#dummy_name(#(#field_names),*).await
}
}
} else {
let restructure = if let Some(custom_wrapper) =
self.args.custom_wrapper.as_ref()
{
quote! {
let data = #custom_wrapper(#struct_name { #(#field_names),* });
}
} else {
quote! {
let data = #struct_name { #(#field_names),* };
}
};
let server_fn_path = self.server_fn_path();
quote! {
#docs
#(#attrs)*
#[allow(unused_variables)]
#vis async fn #fn_name(#(#fn_args),*) #output_arrow #return_ty {
use #server_fn_path::ServerFn;
#restructure
data.run_on_client().await
}
}
}
}
}
impl ToTokens for ServerFnCall {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let body = &self.body;
// only emit the dummy (unmodified server-only body) for the server build
let dummy = cfg!(feature = "ssr").then(|| body.to_dummy_output());
let impl_from = self.impl_from();
let deref_impl = self.deref_impl();
let inventory = self.submit_to_inventory();
let func = self.func_tokens();
let server_fn_impl = self.server_fn_impl();
let struct_tokens = self.struct_tokens();
tokens.extend(quote! {
#struct_tokens
#impl_from
#deref_impl
#server_fn_impl
#inventory
#func
#dummy
});
}
}
/// The implementation of the `server` macro.
/// ```ignore
/// #[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!(my_crate::exports::server_fn)),
/// ) {
/// Err(e) => e.to_compile_error().into(),
/// Ok(s) => s.to_token_stream().into(),
/// }
/// }
/// ```
pub fn server_macro_impl(
args: TokenStream2,
body: TokenStream2,
server_fn_path: Option<Path>,
default_path: &str,
preset_server: Option<Type>,
default_protocol: Option<Type>,
) -> Result<TokenStream2> {
let body = ServerFnCall::parse(default_path, args, body)?
.default_server_fn_path(server_fn_path)
.default_server_type(preset_server)
.default_protocol(default_protocol);
Ok(body.to_token_stream())
}
fn type_from_ident(ident: Ident) -> Type {
let mut segments = Punctuated::new();
segments.push(PathSegment {
ident,
arguments: PathArguments::None,
});
Type::Path(TypePath {
qself: None,
path: Path {
leading_colon: None,
segments,
},
})
}
/// Middleware for a server function.
#[derive(Debug, Clone)]
pub struct Middleware {
expr: syn::Expr,
}
impl ToTokens for Middleware {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let expr = &self.expr;
tokens.extend(quote::quote! {
#expr
});
}
}
impl Parse for Middleware {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let arg: syn::Expr = input.parse()?;
Ok(Middleware { expr: arg })
}
}
fn output_type(return_ty: &Type) -> Option<&Type> {
if let syn::Type::Path(pat) = &return_ty {
if pat.path.segments[0].ident == "Result" {
if pat.path.segments.is_empty() {
panic!("{:#?}", pat.path);
} else if let PathArguments::AngleBracketed(args) =
&pat.path.segments[0].arguments
{
if let GenericArgument::Type(ty) = &args.args[0] {
return Some(ty);
}
}
}
};
None
}
fn err_type(return_ty: &Type) -> Option<&Type> {
if let syn::Type::Path(pat) = &return_ty {
if pat.path.segments[0].ident == "Result" {
if let PathArguments::AngleBracketed(args) =
&pat.path.segments[0].arguments
{
// Result<T>
if args.args.len() == 1 {
return None;
}
// Result<T, _>
else if let GenericArgument::Type(ty) = &args.args[1] {
return Some(ty);
}
}
}
};
None
}
fn err_ws_in_type(
inputs: &Punctuated<ServerFnArg, syn::token::Comma>,
) -> Option<Type> {
inputs.into_iter().find_map(|pat| {
if let syn::Type::Path(ref pat) = *pat.arg.ty {
if pat.path.segments[0].ident != "BoxedStream" {
return None;
}
if let PathArguments::AngleBracketed(args) =
&pat.path.segments[0].arguments
{
// BoxedStream<T>
if args.args.len() == 1 {
return None;
}
// BoxedStream<T, E>
else if let GenericArgument::Type(ty) = &args.args[1] {
return Some(ty.clone());
}
};
};
None
})
}
fn err_ws_out_type(output_ty: &Option<Type>) -> Result<Option<Type>> {
if let Some(syn::Type::Path(ref pat)) = output_ty {
if pat.path.segments[0].ident == "BoxedStream" {
if let PathArguments::AngleBracketed(args) =
&pat.path.segments[0].arguments
{
// BoxedStream<T>
if args.args.len() == 1 {
return Ok(None);
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/build.rs | server_fn/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/server_fn/src/lib.rs | server_fn/src/lib.rs | #![forbid(unsafe_code)]
#![deny(missing_docs)]
//! # Server Functions
//!
//! This package is based on a simple idea: sometimes it’s useful to write functions
//! that will only run on the server, and call them from the client.
//!
//! If you’re creating anything beyond a toy app, you’ll need to do this all the time:
//! reading from or writing to a database that only runs on the server, running expensive
//! computations using libraries you don’t want to ship down to the client, accessing
//! APIs that need to be called from the server rather than the client for CORS reasons
//! or because you need a secret API key that’s stored on the server and definitely
//! shouldn’t be shipped down to a user’s browser.
//!
//! Traditionally, this is done by separating your server and client code, and by setting
//! up something like a REST API or GraphQL API to allow your client to fetch and mutate
//! data on the server. This is fine, but it requires you to write and maintain your code
//! in multiple separate places (client-side code for fetching, server-side functions to run),
//! as well as creating a third thing to manage, which is the API contract between the two.
//!
//! This package provides two simple primitives that allow you instead to write co-located,
//! isomorphic server functions. (*Co-located* means you can write them in your app code so
//! that they are “located alongside” the client code that calls them, rather than separating
//! the client and server sides. *Isomorphic* means you can call them from the client as if
//! you were simply calling a function; the function call has the “same shape” on the client
//! as it does on the server.)
//!
//! ### `#[server]`
//!
//! The [`#[server]`](../leptos/attr.server.html) macro allows you to annotate a function to
//! indicate that it should only run on the server (i.e., when you have an `ssr` feature in your
//! crate that is enabled).
//!
//! **Important**: Before calling a server function on a non-web platform, you must set the server URL by calling
//! [`set_server_url`](crate::client::set_server_url).
//!
//! ```rust,ignore
//! #[server]
//! async fn read_posts(how_many: usize, query: String) -> Result<Vec<Posts>, ServerFnError> {
//! // do some server-only work here to access the database
//! let posts = ...;
//! Ok(posts)
//! }
//!
//! // call the function
//! # #[tokio::main]
//! # async fn main() {
//! async {
//! let posts = read_posts(3, "my search".to_string()).await;
//! log::debug!("posts = {posts:#?}");
//! }
//! # }
//! ```
//!
//! If you call this function from the client, it will serialize the function arguments and `POST`
//! them to the server as if they were the URL-encoded inputs in `<form method="post">`.
//!
//! Here’s what you need to remember:
//! - **Server functions must be `async`.** Even if the work being done inside the function body
//! can run synchronously on the server, from the client’s perspective it involves an asynchronous
//! function call.
//! - **Server functions must return `Result<T, ServerFnError>`.** Even if the work being done
//! inside the function body can’t fail, the processes of serialization/deserialization and the
//! network call are fallible. [`ServerFnError`] can receive generic errors.
//! - **Server functions are part of the public API of your application.** A server function is an
//! ad hoc HTTP API endpoint, not a magic formula. Any server function can be accessed by any HTTP
//! client. You should take care to sanitize any data being returned from the function to ensure it
//! does not leak data that should exist only on the server.
//! - **Server functions can’t be generic.** Because each server function creates a separate API endpoint,
//! it is difficult to monomorphize. As a result, server functions cannot be generic (for now?) If you need to use
//! a generic function, you can define a generic inner function called by multiple concrete server functions.
//! - **Arguments and return types must be serializable.** We support a variety of different encodings,
//! but one way or another arguments need to be serialized to be sent to the server and deserialized
//! on the server, and the return type must be serialized on the server and deserialized on the client.
//! This means that the set of valid server function argument and return types is a subset of all
//! possible Rust argument and return types. (i.e., server functions are strictly more limited than
//! ordinary functions.)
//!
//! ## Server Function Encodings
//!
//! Server functions are designed to allow a flexible combination of input and output encodings, the set
//! of which can be found in the [`codec`] module.
//!
//! Calling and handling server functions is done through the [`Protocol`] trait, which is implemented
//! for the [`Http`] and [`Websocket`] protocols. Most server functions will use the [`Http`] protocol.
//!
//! When using the [`Http`] protocol, the serialization/deserialization process for server functions
//! consists of a series of steps, each of which is represented by a different trait:
//! 1. [`IntoReq`]: The client serializes the [`ServerFn`] argument type into an HTTP request.
//! 2. The [`Client`] sends the request to the server.
//! 3. [`FromReq`]: The server deserializes the HTTP request back into the [`ServerFn`] type.
//! 4. The server calls calls [`ServerFn::run_body`] on the data.
//! 5. [`IntoRes`]: The server serializes the [`ServerFn::Output`] type into an HTTP response.
//! 6. The server integration applies any middleware from [`ServerFn::middlewares`] and responds to the request.
//! 7. [`FromRes`]: The client deserializes the response back into the [`ServerFn::Output`] type.
//!
//! [server]: ../leptos/attr.server.html
//! [`serde_qs`]: <https://docs.rs/serde_qs/latest/serde_qs/>
//! [`cbor`]: <https://docs.rs/cbor/latest/cbor/>
/// Implementations of the client side of the server function call.
pub mod client;
/// Implementations of the server side of the server function call.
pub mod server;
/// Encodings for arguments and results.
pub mod codec;
#[macro_use]
/// Error types and utilities.
pub mod error;
/// Types to add server middleware to a server function.
pub mod middleware;
/// Utilities to allow client-side redirects.
pub mod redirect;
/// Types and traits for for HTTP requests.
pub mod request;
/// Types and traits for HTTP responses.
pub mod response;
#[cfg(feature = "actix-no-default")]
#[doc(hidden)]
pub use ::actix_web as actix_export;
#[cfg(feature = "axum-no-default")]
#[doc(hidden)]
pub use ::axum as axum_export;
#[cfg(feature = "generic")]
#[doc(hidden)]
pub use ::bytes as bytes_export;
#[cfg(feature = "generic")]
#[doc(hidden)]
pub use ::http as http_export;
use base64::{engine::general_purpose::STANDARD_NO_PAD, DecodeError, Engine};
#[cfg(feature = "bitcode")]
pub use bitcode;
// re-exported to make it possible to implement a custom Client without adding a separate
// dependency on `bytes`
pub use bytes::Bytes;
use bytes::{BufMut, BytesMut};
use client::Client;
use codec::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
#[doc(hidden)]
pub use const_format;
#[doc(hidden)]
pub use const_str;
use dashmap::DashMap;
pub use error::ServerFnError;
#[cfg(feature = "form-redirects")]
use error::ServerFnUrlError;
use error::{FromServerFnError, ServerFnErrorErr};
use futures::{pin_mut, SinkExt, Stream, StreamExt};
use http::Method;
use middleware::{BoxedService, Layer, Service};
use redirect::call_redirect_hook;
use request::Req;
use response::{ClientRes, Res, TryRes};
#[cfg(feature = "rkyv")]
pub use rkyv;
#[doc(hidden)]
pub use serde;
#[doc(hidden)]
#[cfg(feature = "serde-lite")]
pub use serde_lite;
use server::Server;
use std::{
fmt::{Debug, Display},
future::Future,
marker::PhantomData,
ops::{Deref, DerefMut},
pin::Pin,
sync::{Arc, LazyLock},
};
#[doc(hidden)]
pub use xxhash_rust;
type ServerFnServerRequest<Fn> = <<Fn as ServerFn>::Server as crate::Server<
<Fn as ServerFn>::Error,
<Fn as ServerFn>::InputStreamError,
<Fn as ServerFn>::OutputStreamError,
>>::Request;
type ServerFnServerResponse<Fn> = <<Fn as ServerFn>::Server as crate::Server<
<Fn as ServerFn>::Error,
<Fn as ServerFn>::InputStreamError,
<Fn as ServerFn>::OutputStreamError,
>>::Response;
/// Defines a function that runs only on the server, but can be called from the server or the client.
///
/// The type for which `ServerFn` is implemented is actually the type of the arguments to the function,
/// while the function body itself is implemented in [`run_body`](ServerFn::run_body).
///
/// This means that `Self` here is usually a struct, in which each field is an argument to the function.
/// In other words,
/// ```rust,ignore
/// #[server]
/// pub async fn my_function(foo: String, bar: usize) -> Result<usize, ServerFnError> {
/// Ok(foo.len() + bar)
/// }
/// ```
/// should expand to
/// ```rust,ignore
/// #[derive(Serialize, Deserialize)]
/// pub struct MyFunction {
/// foo: String,
/// bar: usize
/// }
///
/// impl ServerFn for MyFunction {
/// async fn run_body() -> Result<usize, ServerFnError> {
/// Ok(foo.len() + bar)
/// }
///
/// // etc.
/// }
/// ```
pub trait ServerFn: Send + Sized {
/// A unique path for the server function’s API endpoint, relative to the host, including its prefix.
const PATH: &'static str;
/// The type of the HTTP client that will send the request from the client side.
///
/// For example, this might be `gloo-net` in the browser, or `reqwest` for a desktop app.
type Client: Client<
Self::Error,
Self::InputStreamError,
Self::OutputStreamError,
>;
/// The type of the HTTP server that will send the response from the server side.
///
/// For example, this might be `axum` or `actix-web`.
type Server: Server<
Self::Error,
Self::InputStreamError,
Self::OutputStreamError,
>;
/// The protocol the server function uses to communicate with the client.
type Protocol: Protocol<
Self,
Self::Output,
Self::Client,
Self::Server,
Self::Error,
Self::InputStreamError,
Self::OutputStreamError,
>;
/// The return type of the server function.
///
/// This needs to be converted into `ServerResponse` on the server side, and converted
/// *from* `ClientResponse` when received by the client.
type Output: Send;
/// The type of error in the server function return.
/// Typically [`ServerFnError`], but allowed to be any type that implements [`FromServerFnError`].
type Error: FromServerFnError + Send + Sync;
/// The type of error in the server function for stream items sent from the client to the server.
/// Typically [`ServerFnError`], but allowed to be any type that implements [`FromServerFnError`].
type InputStreamError: FromServerFnError + Send + Sync;
/// The type of error in the server function for stream items sent from the server to the client.
/// Typically [`ServerFnError`], but allowed to be any type that implements [`FromServerFnError`].
type OutputStreamError: FromServerFnError + Send + Sync;
/// Returns [`Self::PATH`].
fn url() -> &'static str {
Self::PATH
}
/// Middleware that should be applied to this server function.
fn middlewares() -> Vec<
Arc<
dyn Layer<
ServerFnServerRequest<Self>,
ServerFnServerResponse<Self>,
>,
>,
> {
Vec::new()
}
/// The body of the server function. This will only run on the server.
fn run_body(
self,
) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send;
#[doc(hidden)]
fn run_on_server(
req: ServerFnServerRequest<Self>,
) -> impl Future<Output = ServerFnServerResponse<Self>> + Send {
// Server functions can either be called by a real Client,
// or directly by an HTML <form>. If they're accessed by a <form>, default to
// redirecting back to the Referer.
#[cfg(feature = "form-redirects")]
let accepts_html = req
.accepts()
.map(|n| n.contains("text/html"))
.unwrap_or(false);
#[cfg(feature = "form-redirects")]
let mut referer = req.referer().as_deref().map(ToOwned::to_owned);
async move {
#[allow(unused_variables, unused_mut)]
// used in form redirects feature
let (mut res, err) =
Self::Protocol::run_server(req, Self::run_body)
.await
.map(|res| (res, None))
.unwrap_or_else(|e| {
let mut response =
<<Self as ServerFn>::Server as crate::Server<
Self::Error,
Self::InputStreamError,
Self::OutputStreamError,
>>::Response::error_response(
Self::PATH, e.ser()
);
let content_type =
<Self::Error as FromServerFnError>::Encoder::CONTENT_TYPE;
response.content_type(content_type);
(response, Some(e))
});
// if it accepts HTML, we'll redirect to the Referer
#[cfg(feature = "form-redirects")]
if accepts_html {
// if it had an error, encode that error in the URL
if let Some(err) = err {
if let Ok(url) = ServerFnUrlError::new(Self::PATH, err)
.to_url(referer.as_deref().unwrap_or("/"))
{
referer = Some(url.to_string());
}
}
// otherwise, strip error info from referer URL, as that means it's from a previous
// call
else if let Some(referer) = referer.as_mut() {
ServerFnUrlError::<Self::Error>::strip_error_info(referer)
}
// set the status code and Location header
res.redirect(referer.as_deref().unwrap_or("/"));
}
res
}
}
#[doc(hidden)]
fn run_on_client(
self,
) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send {
async move { Self::Protocol::run_client(Self::PATH, self).await }
}
}
/// The protocol that a server function uses to communicate with the client. This trait handles
/// the server and client side of running a server function. It is implemented for the [`Http`] and
/// [`Websocket`] protocols and can be used to implement custom protocols.
pub trait Protocol<
Input,
Output,
Client,
Server,
Error,
InputStreamError = Error,
OutputStreamError = Error,
> where
Server: crate::Server<Error, InputStreamError, OutputStreamError>,
Client: crate::Client<Error, InputStreamError, OutputStreamError>,
{
/// The HTTP method used for requests.
const METHOD: Method;
/// Run the server function on the server. The implementation should handle deserializing the
/// input, running the server function, and serializing the output.
fn run_server<F, Fut>(
request: Server::Request,
server_fn: F,
) -> impl Future<Output = Result<Server::Response, Error>> + Send
where
F: Fn(Input) -> Fut + Send,
Fut: Future<Output = Result<Output, Error>> + Send;
/// Run the server function on the client. The implementation should handle serializing the
/// input, sending the request, and deserializing the output.
fn run_client(
path: &str,
input: Input,
) -> impl Future<Output = Result<Output, Error>> + Send;
}
/// The http protocol with specific input and output encodings for the request and response. This is
/// the default protocol server functions use if no override is set in the server function macro
///
/// The http protocol accepts two generic argument that define how the input and output for a server
/// function are turned into HTTP requests and responses. For example, [`Http<GetUrl, Json>`] will
/// accept a Url encoded Get request and return a JSON post response.
///
/// # Example
///
/// ```rust, no_run
/// # use server_fn_macro_default::server;
/// use serde::{Serialize, Deserialize};
/// use server_fn::{Http, ServerFnError, codec::{Json, GetUrl}};
///
/// #[derive(Debug, Clone, Serialize, Deserialize)]
/// pub struct Message {
/// user: String,
/// message: String,
/// }
///
/// // The http protocol can be used on any server function that accepts and returns arguments that implement
/// // the [`IntoReq`] and [`FromRes`] traits.
/// //
/// // In this case, the input and output encodings are [`GetUrl`] and [`Json`], respectively which requires
/// // the items to implement [`IntoReq<GetUrl, ...>`] and [`FromRes<Json, ...>`]. Both of those implementations
/// // require the items to implement [`Serialize`] and [`Deserialize`].
/// # #[cfg(feature = "browser")] {
/// #[server(protocol = Http<GetUrl, Json>)]
/// async fn echo_http(
/// input: Message,
/// ) -> Result<Message, ServerFnError> {
/// Ok(input)
/// }
/// # }
/// ```
pub struct Http<InputProtocol, OutputProtocol>(
PhantomData<(InputProtocol, OutputProtocol)>,
);
impl<InputProtocol, OutputProtocol, Input, Output, Client, Server, E>
Protocol<Input, Output, Client, Server, E>
for Http<InputProtocol, OutputProtocol>
where
Input: IntoReq<InputProtocol, Client::Request, E>
+ FromReq<InputProtocol, Server::Request, E>
+ Send,
Output: IntoRes<OutputProtocol, Server::Response, E>
+ FromRes<OutputProtocol, Client::Response, E>
+ Send,
E: FromServerFnError,
InputProtocol: Encoding,
OutputProtocol: Encoding,
Client: crate::Client<E>,
Server: crate::Server<E>,
{
const METHOD: Method = InputProtocol::METHOD;
async fn run_server<F, Fut>(
request: Server::Request,
server_fn: F,
) -> Result<Server::Response, E>
where
F: Fn(Input) -> Fut + Send,
Fut: Future<Output = Result<Output, E>> + Send,
{
let input = Input::from_req(request).await?;
let output = server_fn(input).await?;
let response = Output::into_res(output).await?;
Ok(response)
}
async fn run_client(path: &str, input: Input) -> Result<Output, E>
where
Client: crate::Client<E>,
{
// create and send request on client
let req = input.into_req(path, OutputProtocol::CONTENT_TYPE)?;
let res = Client::send(req).await?;
let status = res.status();
let location = res.location();
let has_redirect_header = res.has_redirect();
// if it returns an error status, deserialize the error using the error's decoder.
let res = if (400..=599).contains(&status) {
Err(E::de(res.try_into_bytes().await?))
} else {
// otherwise, deserialize the body as is
let output = Output::from_res(res).await?;
Ok(output)
}?;
// if redirected, call the redirect hook (if that's been set)
if (300..=399).contains(&status) || has_redirect_header {
call_redirect_hook(&location);
}
Ok(res)
}
}
/// The websocket protocol that encodes the input and output streams using a websocket connection.
///
/// The websocket protocol accepts two generic argument that define the input and output serialization
/// formats. For example, [`Websocket<CborEncoding, JsonEncoding>`] would accept a stream of Cbor-encoded messages
/// and return a stream of JSON-encoded messages.
///
/// # Example
///
/// ```rust, no_run
/// # use server_fn_macro_default::server;
/// # #[cfg(feature = "browser")] {
/// use server_fn::{ServerFnError, BoxedStream, Websocket, codec::JsonEncoding};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Clone, Serialize, Deserialize)]
/// pub struct Message {
/// user: String,
/// message: String,
/// }
/// // The websocket protocol can be used on any server function that accepts and returns a [`BoxedStream`]
/// // with items that can be encoded by the input and output encoding generics.
/// //
/// // In this case, the input and output encodings are [`Json`] and [`Json`], respectively which requires
/// // the items to implement [`Serialize`] and [`Deserialize`].
/// #[server(protocol = Websocket<JsonEncoding, JsonEncoding>)]
/// async fn echo_websocket(
/// input: BoxedStream<Message, ServerFnError>,
/// ) -> Result<BoxedStream<Message, ServerFnError>, ServerFnError> {
/// Ok(input.into())
/// }
/// # }
/// ```
pub struct Websocket<InputEncoding, OutputEncoding>(
PhantomData<(InputEncoding, OutputEncoding)>,
);
/// A boxed stream type that can be used with the websocket protocol.
///
/// You can easily convert any static type that implement [`futures::Stream`] into a [`BoxedStream`]
/// with the [`From`] trait.
///
/// # Example
///
/// ```rust, no_run
/// use futures::StreamExt;
/// use server_fn::{BoxedStream, ServerFnError};
///
/// let stream: BoxedStream<_, ServerFnError> =
/// futures::stream::iter(0..10).map(Result::Ok).into();
/// ```
pub struct BoxedStream<T, E> {
stream: Pin<Box<dyn Stream<Item = Result<T, E>> + Send>>,
}
impl<T, E> From<BoxedStream<T, E>>
for Pin<Box<dyn Stream<Item = Result<T, E>> + Send>>
{
fn from(val: BoxedStream<T, E>) -> Self {
val.stream
}
}
impl<T, E> Deref for BoxedStream<T, E> {
type Target = Pin<Box<dyn Stream<Item = Result<T, E>> + Send>>;
fn deref(&self) -> &Self::Target {
&self.stream
}
}
impl<T, E> DerefMut for BoxedStream<T, E> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.stream
}
}
impl<T, E> Debug for BoxedStream<T, E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BoxedStream").finish()
}
}
impl<T, E, S> From<S> for BoxedStream<T, E>
where
S: Stream<Item = Result<T, E>> + Send + 'static,
{
fn from(stream: S) -> Self {
BoxedStream {
stream: Box::pin(stream),
}
}
}
impl<
Input,
InputItem,
OutputItem,
InputEncoding,
OutputEncoding,
Client,
Server,
Error,
InputStreamError,
OutputStreamError,
>
Protocol<
Input,
BoxedStream<OutputItem, OutputStreamError>,
Client,
Server,
Error,
InputStreamError,
OutputStreamError,
> for Websocket<InputEncoding, OutputEncoding>
where
Input: Deref<Target = BoxedStream<InputItem, InputStreamError>>
+ Into<BoxedStream<InputItem, InputStreamError>>
+ From<BoxedStream<InputItem, InputStreamError>>,
InputEncoding: Encodes<InputItem> + Decodes<InputItem>,
OutputEncoding: Encodes<OutputItem> + Decodes<OutputItem>,
InputStreamError: FromServerFnError + Send,
OutputStreamError: FromServerFnError + Send,
Error: FromServerFnError + Send,
Server: crate::Server<Error, InputStreamError, OutputStreamError>,
Client: crate::Client<Error, InputStreamError, OutputStreamError>,
OutputItem: Send + 'static,
InputItem: Send + 'static,
{
const METHOD: Method = Method::GET;
async fn run_server<F, Fut>(
request: Server::Request,
server_fn: F,
) -> Result<Server::Response, Error>
where
F: Fn(Input) -> Fut + Send,
Fut: Future<
Output = Result<
BoxedStream<OutputItem, OutputStreamError>,
Error,
>,
> + Send,
{
let (request_bytes, response_stream, response) =
request.try_into_websocket().await?;
let input = request_bytes.map(|request_bytes| {
let request_bytes = request_bytes
.map(|bytes| deserialize_result::<InputStreamError>(bytes))
.unwrap_or_else(Err);
match request_bytes {
Ok(request_bytes) => InputEncoding::decode(request_bytes)
.map_err(|e| {
InputStreamError::from_server_fn_error(
ServerFnErrorErr::Deserialization(e.to_string()),
)
}),
Err(err) => Err(InputStreamError::de(err)),
}
});
let boxed = Box::pin(input)
as Pin<
Box<
dyn Stream<Item = Result<InputItem, InputStreamError>>
+ Send,
>,
>;
let input = BoxedStream { stream: boxed };
let output = server_fn(input.into()).await?;
let output = output.stream.map(|output| {
let result = match output {
Ok(output) => OutputEncoding::encode(&output).map_err(|e| {
OutputStreamError::from_server_fn_error(
ServerFnErrorErr::Serialization(e.to_string()),
)
.ser()
}),
Err(err) => Err(err.ser()),
};
serialize_result(result)
});
Server::spawn(async move {
pin_mut!(response_stream);
pin_mut!(output);
while let Some(output) = output.next().await {
if response_stream.send(output).await.is_err() {
break;
}
}
})?;
Ok(response)
}
fn run_client(
path: &str,
input: Input,
) -> impl Future<
Output = Result<BoxedStream<OutputItem, OutputStreamError>, Error>,
> + Send {
let input = input.into();
async move {
let (stream, sink) = Client::open_websocket(path).await?;
// Forward the input stream to the websocket
Client::spawn(async move {
pin_mut!(input);
pin_mut!(sink);
while let Some(input) = input.stream.next().await {
let result = match input {
Ok(input) => {
InputEncoding::encode(&input).map_err(|e| {
InputStreamError::from_server_fn_error(
ServerFnErrorErr::Serialization(
e.to_string(),
),
)
.ser()
})
}
Err(err) => Err(err.ser()),
};
let result = serialize_result(result);
if sink.send(result).await.is_err() {
break;
}
}
});
// Return the output stream
let stream = stream.map(|request_bytes| {
let request_bytes = request_bytes
.map(|bytes| deserialize_result::<OutputStreamError>(bytes))
.unwrap_or_else(Err);
match request_bytes {
Ok(request_bytes) => OutputEncoding::decode(request_bytes)
.map_err(|e| {
OutputStreamError::from_server_fn_error(
ServerFnErrorErr::Deserialization(
e.to_string(),
),
)
}),
Err(err) => Err(OutputStreamError::de(err)),
}
});
let boxed = Box::pin(stream)
as Pin<
Box<
dyn Stream<Item = Result<OutputItem, OutputStreamError>>
+ Send,
>,
>;
let output = BoxedStream { stream: boxed };
Ok(output)
}
}
}
// Serializes a Result<Bytes, Bytes> into a single Bytes instance.
// Format: [tag: u8][content: Bytes]
// - Tag 0: Ok variant
// - Tag 1: Err variant
fn serialize_result(result: Result<Bytes, Bytes>) -> Bytes {
match result {
Ok(bytes) => {
let mut buf = BytesMut::with_capacity(1 + bytes.len());
buf.put_u8(0); // Tag for Ok variant
buf.extend_from_slice(&bytes);
buf.freeze()
}
Err(bytes) => {
let mut buf = BytesMut::with_capacity(1 + bytes.len());
buf.put_u8(1); // Tag for Err variant
buf.extend_from_slice(&bytes);
buf.freeze()
}
}
}
// Deserializes a Bytes instance back into a Result<Bytes, Bytes>.
fn deserialize_result<E: FromServerFnError>(
bytes: Bytes,
) -> Result<Bytes, Bytes> {
if bytes.is_empty() {
return Err(E::from_server_fn_error(
ServerFnErrorErr::Deserialization("Data is empty".into()),
)
.ser());
}
let tag = bytes[0];
let content = bytes.slice(1..);
match tag {
0 => Ok(content),
1 => Err(content),
_ => Err(E::from_server_fn_error(ServerFnErrorErr::Deserialization(
"Invalid data tag".into(),
))
.ser()), // Invalid tag
}
}
/// Encode format type
pub enum Format {
/// Binary representation
Binary,
/// utf-8 compatible text representation
Text,
}
/// A trait for types with an associated content type.
pub trait ContentType {
/// The MIME type of the data.
const CONTENT_TYPE: &'static str;
}
/// Data format representation
pub trait FormatType {
/// The representation type
const FORMAT_TYPE: Format;
/// Encodes data into a string.
fn into_encoded_string(bytes: Bytes) -> String {
match Self::FORMAT_TYPE {
Format::Binary => STANDARD_NO_PAD.encode(bytes),
Format::Text => String::from_utf8(bytes.into())
.expect("Valid text format type with utf-8 comptabile string"),
}
}
/// Decodes string to bytes
fn from_encoded_string(data: &str) -> Result<Bytes, DecodeError> {
match Self::FORMAT_TYPE {
Format::Binary => {
STANDARD_NO_PAD.decode(data).map(|data| data.into())
}
Format::Text => Ok(Bytes::copy_from_slice(data.as_bytes())),
}
}
}
/// A trait for types that can be encoded into a bytes for a request body.
pub trait Encodes<T>: ContentType + FormatType {
/// The error type that can be returned if the encoding fails.
type Error: Display + Debug;
/// Encodes the given value into a bytes.
fn encode(output: &T) -> Result<Bytes, Self::Error>;
}
/// A trait for types that can be decoded from a bytes for a response body.
pub trait Decodes<T> {
/// The error type that can be returned if the decoding fails.
type Error: Display;
/// Decodes the given bytes into a value.
fn decode(bytes: Bytes) -> Result<T, Self::Error>;
}
#[cfg(feature = "ssr")]
#[doc(hidden)]
pub use inventory;
/// Uses the `inventory` crate to initialize a map between paths and server functions.
#[macro_export]
macro_rules! initialize_server_fn_map {
($req:ty, $res:ty) => {
std::sync::LazyLock::new(|| {
$crate::inventory::iter::<ServerFnTraitObj<$req, $res>>
.into_iter()
.map(|obj| {
((obj.path().to_string(), obj.method()), obj.clone())
})
.collect()
})
};
}
/// A list of middlewares that can be applied to a server function.
pub type MiddlewareSet<Req, Res> = Vec<Arc<dyn Layer<Req, Res>>>;
/// A trait object that allows multiple server functions that take the same
/// request type and return the same response type to be gathered into a single
/// collection.
pub struct ServerFnTraitObj<Req, Res> {
path: &'static str,
method: Method,
handler: fn(Req) -> Pin<Box<dyn Future<Output = Res> + Send>>,
middleware: fn() -> MiddlewareSet<Req, Res>,
ser: fn(ServerFnErrorErr) -> Bytes,
}
impl<Req, Res> ServerFnTraitObj<Req, Res> {
/// Converts the relevant parts of a server function into a trait object.
pub const fn new<
S: ServerFn<
Server: crate::Server<
S::Error,
S::InputStreamError,
S::OutputStreamError,
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | true |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/redirect.rs | server_fn/src/redirect.rs | use std::sync::OnceLock;
/// A custom header that can be set with any value to indicate
/// that the server function client should redirect to a new route.
///
/// This is useful because it allows returning a value from the request,
/// while also indicating that a redirect should follow. This cannot be
/// done with an HTTP `3xx` status code, because the browser will follow
/// that redirect rather than returning the desired data.
pub const REDIRECT_HEADER: &str = "serverfnredirect";
/// A function that will be called if a server function returns a `3xx` status
/// or the [`REDIRECT_HEADER`].
pub type RedirectHook = Box<dyn Fn(&str) + Send + Sync>;
// allowed: not in a public API, and pretty straightforward
#[allow(clippy::type_complexity)]
pub(crate) static REDIRECT_HOOK: OnceLock<RedirectHook> = OnceLock::new();
/// Sets a function that will be called if a server function returns a `3xx` status
/// or the [`REDIRECT_HEADER`]. Returns `Err(_)` if the hook has already been set.
pub fn set_redirect_hook(
hook: impl Fn(&str) + Send + Sync + 'static,
) -> Result<(), RedirectHook> {
REDIRECT_HOOK.set(Box::new(hook))
}
/// Calls the hook that has been set by [`set_redirect_hook`] to redirect to `loc`.
pub fn call_redirect_hook(loc: &str) {
if let Some(hook) = REDIRECT_HOOK.get() {
hook(loc)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/client.rs | server_fn/src/client.rs | use crate::{request::ClientReq, response::ClientRes};
use bytes::Bytes;
use futures::{Sink, Stream};
use std::{future::Future, sync::OnceLock};
static ROOT_URL: OnceLock<&'static str> = OnceLock::new();
/// Set the root server URL that all server function paths are relative to for the client.
///
/// If this is not set, it defaults to the origin.
pub fn set_server_url(url: &'static str) {
ROOT_URL.set(url).unwrap();
}
/// Returns the root server URL for all server functions.
pub fn get_server_url() -> &'static str {
ROOT_URL.get().copied().unwrap_or("")
}
/// A client defines a pair of request/response types and the logic to send
/// and receive them.
///
/// This trait is implemented for things like a browser `fetch` request or for
/// the `reqwest` trait. It should almost never be necessary to implement it
/// yourself, unless you’re trying to use an alternative HTTP crate on the client side.
pub trait Client<Error, InputStreamError = Error, OutputStreamError = Error> {
/// The type of a request sent by this client.
type Request: ClientReq<Error> + Send + 'static;
/// The type of a response received by this client.
type Response: ClientRes<Error> + Send + 'static;
/// Sends the request and receives a response.
fn send(
req: Self::Request,
) -> impl Future<Output = Result<Self::Response, Error>> + Send;
/// Opens a websocket connection to the server.
#[allow(clippy::type_complexity)]
fn open_websocket(
path: &str,
) -> impl Future<
Output = Result<
(
impl Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
impl Sink<Bytes> + Send + 'static,
),
Error,
>,
> + Send;
/// Spawn a future that runs in the background.
fn spawn(future: impl Future<Output = ()> + Send + 'static);
}
#[cfg(feature = "browser")]
/// Implements [`Client`] for a `fetch` request in the browser.
pub mod browser {
use super::Client;
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::browser::{BrowserRequest, RequestInner},
response::browser::BrowserResponse,
};
use bytes::Bytes;
use futures::{Sink, SinkExt, StreamExt};
use gloo_net::websocket::{Message, WebSocketError};
use send_wrapper::SendWrapper;
use std::future::Future;
/// Implements [`Client`] for a `fetch` request in the browser.
pub struct BrowserClient;
impl<
Error: FromServerFnError,
InputStreamError: FromServerFnError,
OutputStreamError: FromServerFnError,
> Client<Error, InputStreamError, OutputStreamError> for BrowserClient
{
type Request = BrowserRequest;
type Response = BrowserResponse;
fn send(
req: Self::Request,
) -> impl Future<Output = Result<Self::Response, Error>> + Send
{
SendWrapper::new(async move {
let req = req.0.take();
let RequestInner {
request,
mut abort_ctrl,
} = req;
let res = request
.send()
.await
.map(|res| BrowserResponse(SendWrapper::new(res)))
.map_err(|e| {
ServerFnErrorErr::Request(e.to_string())
.into_app_error()
});
// at this point, the future has successfully resolved without being dropped, so we
// can prevent the `AbortController` from firing
if let Some(ctrl) = abort_ctrl.as_mut() {
ctrl.prevent_cancellation();
}
res
})
}
fn open_websocket(
url: &str,
) -> impl Future<
Output = Result<
(
impl futures::Stream<Item = Result<Bytes, Bytes>>
+ Send
+ 'static,
impl futures::Sink<Bytes> + Send + 'static,
),
Error,
>,
> + Send {
SendWrapper::new(async move {
let websocket =
gloo_net::websocket::futures::WebSocket::open(url)
.map_err(|err| {
web_sys::console::error_1(&err.to_string().into());
Error::from_server_fn_error(
ServerFnErrorErr::Request(err.to_string()),
)
})?;
let (sink, stream) = websocket.split();
let stream = stream.map(|message| match message {
Ok(message) => Ok(match message {
Message::Text(text) => Bytes::from(text),
Message::Bytes(bytes) => Bytes::from(bytes),
}),
Err(err) => {
web_sys::console::error_1(&err.to_string().into());
Err(OutputStreamError::from_server_fn_error(
ServerFnErrorErr::Request(err.to_string()),
)
.ser())
}
});
let stream = SendWrapper::new(stream);
struct SendWrapperSink<S> {
sink: SendWrapper<S>,
}
impl<S> SendWrapperSink<S> {
fn new(sink: S) -> Self {
Self {
sink: SendWrapper::new(sink),
}
}
}
impl<S, Item> Sink<Item> for SendWrapperSink<S>
where
S: Sink<Item> + Unpin,
{
type Error = S::Error;
fn poll_ready(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>>
{
self.get_mut().sink.poll_ready_unpin(cx)
}
fn start_send(
self: std::pin::Pin<&mut Self>,
item: Item,
) -> Result<(), Self::Error> {
self.get_mut().sink.start_send_unpin(item)
}
fn poll_flush(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>>
{
self.get_mut().sink.poll_flush_unpin(cx)
}
fn poll_close(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>>
{
self.get_mut().sink.poll_close_unpin(cx)
}
}
let sink = sink.with(|message: Bytes| async move {
Ok::<Message, WebSocketError>(Message::Bytes(
message.into(),
))
});
let sink = SendWrapperSink::new(Box::pin(sink));
Ok((stream, sink))
})
}
fn spawn(future: impl Future<Output = ()> + Send + 'static) {
wasm_bindgen_futures::spawn_local(future);
}
}
}
#[cfg(feature = "reqwest")]
/// Implements [`Client`] for a request made by [`reqwest`].
pub mod reqwest {
use super::{get_server_url, Client};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::reqwest::CLIENT,
};
use bytes::Bytes;
use futures::{SinkExt, StreamExt, TryFutureExt};
use reqwest::{Request, Response};
use std::future::Future;
/// Implements [`Client`] for a request made by [`reqwest`].
pub struct ReqwestClient;
impl<
Error: FromServerFnError,
InputStreamError: FromServerFnError,
OutputStreamError: FromServerFnError,
> Client<Error, InputStreamError, OutputStreamError> for ReqwestClient
{
type Request = Request;
type Response = Response;
fn send(
req: Self::Request,
) -> impl Future<Output = Result<Self::Response, Error>> + Send
{
CLIENT.execute(req).map_err(|e| {
ServerFnErrorErr::Request(e.to_string()).into_app_error()
})
}
async fn open_websocket(
path: &str,
) -> Result<
(
impl futures::Stream<Item = Result<Bytes, Bytes>> + Send + 'static,
impl futures::Sink<Bytes> + Send + 'static,
),
Error,
> {
let mut websocket_server_url = get_server_url().to_string();
if let Some(postfix) = websocket_server_url.strip_prefix("http://")
{
websocket_server_url = format!("ws://{postfix}");
} else if let Some(postfix) =
websocket_server_url.strip_prefix("https://")
{
websocket_server_url = format!("wss://{postfix}");
}
let url = format!("{websocket_server_url}{path}");
let (ws_stream, _) =
tokio_tungstenite::connect_async(url).await.map_err(|e| {
Error::from_server_fn_error(ServerFnErrorErr::Request(
e.to_string(),
))
})?;
let (write, read) = ws_stream.split();
Ok((
read.map(|msg| match msg {
Ok(msg) => Ok(msg.into_data()),
Err(e) => Err(OutputStreamError::from_server_fn_error(
ServerFnErrorErr::Request(e.to_string()),
)
.ser()),
}),
write.with(|msg: Bytes| async move {
Ok::<
tokio_tungstenite::tungstenite::Message,
tokio_tungstenite::tungstenite::Error,
>(
tokio_tungstenite::tungstenite::Message::Binary(msg)
)
}),
))
}
fn spawn(future: impl Future<Output = ()> + Send + 'static) {
tokio::spawn(future);
}
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/error.rs | server_fn/src/error.rs | #![allow(deprecated)]
use crate::{ContentType, Decodes, Encodes, Format, FormatType};
use base64::{engine::general_purpose::URL_SAFE, Engine as _};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use std::{
fmt::{self, Display, Write},
str::FromStr,
};
use throw_error::Error;
use url::Url;
/// A custom header that can be used to indicate a server function returned an error.
pub const SERVER_FN_ERROR_HEADER: &str = "serverfnerror";
impl From<ServerFnError> for Error {
fn from(e: ServerFnError) -> Self {
Error::from(ServerFnErrorWrapper(e))
}
}
/// An empty value indicating that there is no custom error type associated
/// with this server function.
#[derive(
Debug,
Deserialize,
Serialize,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
Clone,
Copy,
)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[deprecated(
since = "0.8.0",
note = "Now server_fn can return any error type other than ServerFnError, \
so the WrappedServerError variant will be removed in 0.9.0"
)]
pub struct NoCustomError;
// Implement `Display` for `NoCustomError`
impl fmt::Display for NoCustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Unit Type Displayed")
}
}
impl FromStr for NoCustomError {
type Err = ();
fn from_str(_s: &str) -> Result<Self, Self::Err> {
Ok(NoCustomError)
}
}
/// Wraps some error type, which may implement any of [`Error`](trait@std::error::Error), [`Clone`], or
/// [`Display`].
#[derive(Debug)]
#[deprecated(
since = "0.8.0",
note = "Now server_fn can return any error type other than ServerFnError, \
so the WrappedServerError variant will be removed in 0.9.0"
)]
pub struct WrapError<T>(pub T);
/// A helper macro to convert a variety of different types into `ServerFnError`.
/// This should mostly be used if you are implementing `From<ServerFnError>` for `YourError`.
#[macro_export]
#[deprecated(
since = "0.8.0",
note = "Now server_fn can return any error type other than ServerFnError, \
so the WrappedServerError variant will be removed in 0.9.0"
)]
macro_rules! server_fn_error {
() => {{
use $crate::{ViaError, WrapError};
(&&&&&WrapError(())).to_server_error()
}};
($err:expr) => {{
use $crate::error::{ViaError, WrapError};
match $err {
error => (&&&&&WrapError(error)).to_server_error(),
}
}};
}
/// This trait serves as the conversion method between a variety of types
/// and [`ServerFnError`].
#[deprecated(
since = "0.8.0",
note = "Now server_fn can return any error type other than ServerFnError, \
so users should place their custom error type instead of \
ServerFnError"
)]
pub trait ViaError<E> {
/// Converts something into an error.
fn to_server_error(&self) -> ServerFnError<E>;
}
// This impl should catch if you fed it a [`ServerFnError`] already.
impl<E: ServerFnErrorKind + std::error::Error + Clone> ViaError<E>
for &&&&WrapError<ServerFnError<E>>
{
fn to_server_error(&self) -> ServerFnError<E> {
self.0.clone()
}
}
// A type tag for ServerFnError so we can special case it
#[deprecated]
pub(crate) trait ServerFnErrorKind {}
impl ServerFnErrorKind for ServerFnError {}
// This impl should catch passing () or nothing to server_fn_error
impl ViaError<NoCustomError> for &&&WrapError<()> {
fn to_server_error(&self) -> ServerFnError {
ServerFnError::WrappedServerError(NoCustomError)
}
}
// This impl will catch any type that implements any type that impls
// Error and Clone, so that it can be wrapped into ServerFnError
impl<E: std::error::Error + Clone> ViaError<E> for &&WrapError<E> {
fn to_server_error(&self) -> ServerFnError<E> {
ServerFnError::WrappedServerError(self.0.clone())
}
}
// If it doesn't impl Error, but does impl Display and Clone,
// we can still wrap it in String form
impl<E: Display + Clone> ViaError<E> for &WrapError<E> {
fn to_server_error(&self) -> ServerFnError<E> {
ServerFnError::ServerError(self.0.to_string())
}
}
// This is what happens if someone tries to pass in something that does
// not meet the above criteria
impl<E> ViaError<E> for WrapError<E> {
#[track_caller]
fn to_server_error(&self) -> ServerFnError<E> {
panic!(
"At {}, you call `to_server_error()` or use `server_fn_error!` \
with a value that does not implement `Clone` and either `Error` \
or `Display`.",
std::panic::Location::caller()
);
}
}
/// A type that can be used as the return type of the server function for easy error conversion with `?` operator.
/// This type can be replaced with any other error type that implements `FromServerFnError`.
///
/// Unlike [`ServerFnErrorErr`], this does not implement [`Error`](trait@std::error::Error).
/// This means that other error types can easily be converted into it using the
/// `?` operator.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub enum ServerFnError<E = NoCustomError> {
#[deprecated(
since = "0.8.0",
note = "Now server_fn can return any error type other than \
ServerFnError, so users should place their custom error type \
instead of ServerFnError"
)]
/// A user-defined custom error type, which defaults to [`NoCustomError`].
WrappedServerError(E),
/// Error while trying to register the server function (only occurs in case of poisoned RwLock).
Registration(String),
/// Occurs on the client if there is a network error while trying to run function on server.
Request(String),
/// Occurs on the server if there is an error creating an HTTP response.
Response(String),
/// Occurs when there is an error while actually running the function on the server.
ServerError(String),
/// Occurs when there is an error while actually running the middleware on the server.
MiddlewareError(String),
/// Occurs on the client if there is an error deserializing the server's response.
Deserialization(String),
/// Occurs on the client if there is an error serializing the server function arguments.
Serialization(String),
/// Occurs on the server if there is an error deserializing one of the arguments that's been sent.
Args(String),
/// Occurs on the server if there's a missing argument.
MissingArg(String),
}
impl ServerFnError<NoCustomError> {
/// Constructs a new [`ServerFnError::ServerError`] from some other type.
pub fn new(msg: impl ToString) -> Self {
Self::ServerError(msg.to_string())
}
}
impl<CustErr> From<CustErr> for ServerFnError<CustErr> {
fn from(value: CustErr) -> Self {
ServerFnError::WrappedServerError(value)
}
}
impl<E: std::error::Error> From<E> for ServerFnError {
fn from(value: E) -> Self {
ServerFnError::ServerError(value.to_string())
}
}
impl<CustErr> Display for ServerFnError<CustErr>
where
CustErr: Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
ServerFnError::Registration(s) => format!(
"error while trying to register the server function: {s}"
),
ServerFnError::Request(s) => format!(
"error reaching server to call server function: {s}"
),
ServerFnError::ServerError(s) =>
format!("error running server function: {s}"),
ServerFnError::MiddlewareError(s) =>
format!("error running middleware: {s}"),
ServerFnError::Deserialization(s) =>
format!("error deserializing server function results: {s}"),
ServerFnError::Serialization(s) =>
format!("error serializing server function arguments: {s}"),
ServerFnError::Args(s) => format!(
"error deserializing server function arguments: {s}"
),
ServerFnError::MissingArg(s) => format!("missing argument {s}"),
ServerFnError::Response(s) =>
format!("error generating HTTP response: {s}"),
ServerFnError::WrappedServerError(e) => format!("{e}"),
}
)
}
}
/// Serializes and deserializes JSON with [`serde_json`].
pub struct ServerFnErrorEncoding;
impl ContentType for ServerFnErrorEncoding {
const CONTENT_TYPE: &'static str = "text/plain";
}
impl FormatType for ServerFnErrorEncoding {
const FORMAT_TYPE: Format = Format::Text;
}
impl<CustErr> Encodes<ServerFnError<CustErr>> for ServerFnErrorEncoding
where
CustErr: Display,
{
type Error = std::fmt::Error;
fn encode(output: &ServerFnError<CustErr>) -> Result<Bytes, Self::Error> {
let mut buf = String::new();
let result = match output {
ServerFnError::WrappedServerError(e) => {
write!(&mut buf, "WrappedServerFn|{e}")
}
ServerFnError::Registration(e) => {
write!(&mut buf, "Registration|{e}")
}
ServerFnError::Request(e) => write!(&mut buf, "Request|{e}"),
ServerFnError::Response(e) => write!(&mut buf, "Response|{e}"),
ServerFnError::ServerError(e) => {
write!(&mut buf, "ServerError|{e}")
}
ServerFnError::MiddlewareError(e) => {
write!(&mut buf, "MiddlewareError|{e}")
}
ServerFnError::Deserialization(e) => {
write!(&mut buf, "Deserialization|{e}")
}
ServerFnError::Serialization(e) => {
write!(&mut buf, "Serialization|{e}")
}
ServerFnError::Args(e) => write!(&mut buf, "Args|{e}"),
ServerFnError::MissingArg(e) => {
write!(&mut buf, "MissingArg|{e}")
}
};
match result {
Ok(()) => Ok(Bytes::from(buf)),
Err(e) => Err(e),
}
}
}
impl<CustErr> Decodes<ServerFnError<CustErr>> for ServerFnErrorEncoding
where
CustErr: FromStr,
{
type Error = String;
fn decode(bytes: Bytes) -> Result<ServerFnError<CustErr>, Self::Error> {
let data = String::from_utf8(bytes.to_vec())
.map_err(|err| format!("UTF-8 conversion error: {err}"))?;
data.split_once('|')
.ok_or_else(|| {
format!("Invalid format: missing delimiter in {data:?}")
})
.and_then(|(ty, data)| match ty {
"WrappedServerFn" => CustErr::from_str(data)
.map(ServerFnError::WrappedServerError)
.map_err(|_| {
format!("Failed to parse CustErr from {data:?}")
}),
"Registration" => {
Ok(ServerFnError::Registration(data.to_string()))
}
"Request" => Ok(ServerFnError::Request(data.to_string())),
"Response" => Ok(ServerFnError::Response(data.to_string())),
"ServerError" => {
Ok(ServerFnError::ServerError(data.to_string()))
}
"MiddlewareError" => {
Ok(ServerFnError::MiddlewareError(data.to_string()))
}
"Deserialization" => {
Ok(ServerFnError::Deserialization(data.to_string()))
}
"Serialization" => {
Ok(ServerFnError::Serialization(data.to_string()))
}
"Args" => Ok(ServerFnError::Args(data.to_string())),
"MissingArg" => Ok(ServerFnError::MissingArg(data.to_string())),
_ => Err(format!("Unknown error type: {ty}")),
})
}
}
impl<CustErr> FromServerFnError for ServerFnError<CustErr>
where
CustErr: std::fmt::Debug + Display + FromStr + 'static,
{
type Encoder = ServerFnErrorEncoding;
fn from_server_fn_error(value: ServerFnErrorErr) -> Self {
match value {
ServerFnErrorErr::Registration(value) => {
ServerFnError::Registration(value)
}
ServerFnErrorErr::Request(value) => ServerFnError::Request(value),
ServerFnErrorErr::ServerError(value) => {
ServerFnError::ServerError(value)
}
ServerFnErrorErr::MiddlewareError(value) => {
ServerFnError::MiddlewareError(value)
}
ServerFnErrorErr::Deserialization(value) => {
ServerFnError::Deserialization(value)
}
ServerFnErrorErr::Serialization(value) => {
ServerFnError::Serialization(value)
}
ServerFnErrorErr::Args(value) => ServerFnError::Args(value),
ServerFnErrorErr::MissingArg(value) => {
ServerFnError::MissingArg(value)
}
ServerFnErrorErr::Response(value) => ServerFnError::Response(value),
ServerFnErrorErr::UnsupportedRequestMethod(value) => {
ServerFnError::Request(value)
}
}
}
}
impl<E> std::error::Error for ServerFnError<E>
where
E: std::error::Error + 'static,
ServerFnError<E>: std::fmt::Display,
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ServerFnError::WrappedServerError(e) => Some(e),
_ => None,
}
}
}
/// Type for errors that can occur when using server functions. If you need to return a custom error type from a server function, implement `FromServerFnError` for your custom error type.
#[derive(
thiserror::Error, Debug, Clone, PartialEq, Eq, Serialize, Deserialize,
)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
pub enum ServerFnErrorErr {
/// Error while trying to register the server function (only occurs in case of poisoned RwLock).
#[error("error while trying to register the server function: {0}")]
Registration(String),
/// Occurs on the client if trying to use an unsupported `HTTP` method when building a request.
#[error("error trying to build `HTTP` method request: {0}")]
UnsupportedRequestMethod(String),
/// Occurs on the client if there is a network error while trying to run function on server.
#[error("error reaching server to call server function: {0}")]
Request(String),
/// Occurs when there is an error while actually running the function on the server.
#[error("error running server function: {0}")]
ServerError(String),
/// Occurs when there is an error while actually running the middleware on the server.
#[error("error running middleware: {0}")]
MiddlewareError(String),
/// Occurs on the client if there is an error deserializing the server's response.
#[error("error deserializing server function results: {0}")]
Deserialization(String),
/// Occurs on the client if there is an error serializing the server function arguments.
#[error("error serializing server function arguments: {0}")]
Serialization(String),
/// Occurs on the server if there is an error deserializing one of the arguments that's been sent.
#[error("error deserializing server function arguments: {0}")]
Args(String),
/// Occurs on the server if there's a missing argument.
#[error("missing argument {0}")]
MissingArg(String),
/// Occurs on the server if there is an error creating an HTTP response.
#[error("error creating response {0}")]
Response(String),
}
/// Associates a particular server function error with the server function
/// found at a particular path.
///
/// This can be used to pass an error from the server back to the client
/// without JavaScript/WASM supported, by encoding it in the URL as a query string.
/// This is useful for progressive enhancement.
#[derive(Debug)]
pub struct ServerFnUrlError<E> {
path: String,
error: E,
}
impl<E: FromServerFnError> ServerFnUrlError<E> {
/// Creates a new structure associating the server function at some path
/// with a particular error.
pub fn new(path: impl Display, error: E) -> Self {
Self {
path: path.to_string(),
error,
}
}
/// The error itself.
pub fn error(&self) -> &E {
&self.error
}
/// The path of the server function that generated this error.
pub fn path(&self) -> &str {
&self.path
}
/// Adds an encoded form of this server function error to the given base URL.
pub fn to_url(&self, base: &str) -> Result<Url, url::ParseError> {
let mut url = Url::parse(base)?;
url.query_pairs_mut()
.append_pair("__path", &self.path)
.append_pair("__err", &URL_SAFE.encode(self.error.ser()));
Ok(url)
}
/// Replaces any ServerFnUrlError info from the URL in the given string
/// with the serialized success value given.
pub fn strip_error_info(path: &mut String) {
if let Ok(mut url) = Url::parse(&*path) {
// NOTE: This is gross, but the Serializer you get from
// .query_pairs_mut() isn't an Iterator so you can't just .retain().
let pairs_previously = url
.query_pairs()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect::<Vec<_>>();
let mut pairs = url.query_pairs_mut();
pairs.clear();
for (key, value) in pairs_previously
.into_iter()
.filter(|(key, _)| key != "__path" && key != "__err")
{
pairs.append_pair(&key, &value);
}
drop(pairs);
*path = url.to_string();
}
}
/// Decodes an error from a URL.
pub fn decode_err(err: &str) -> E {
let decoded = match URL_SAFE.decode(err) {
Ok(decoded) => decoded,
Err(err) => {
return ServerFnErrorErr::Deserialization(err.to_string())
.into_app_error();
}
};
E::de(decoded.into())
}
}
impl<E> From<ServerFnUrlError<E>> for ServerFnError<E> {
fn from(error: ServerFnUrlError<E>) -> Self {
error.error.into()
}
}
impl<E> From<ServerFnUrlError<ServerFnError<E>>> for ServerFnError<E> {
fn from(error: ServerFnUrlError<ServerFnError<E>>) -> Self {
error.error
}
}
#[derive(Debug, thiserror::Error)]
#[doc(hidden)]
/// Only used instantly only when a framework needs E: Error.
pub struct ServerFnErrorWrapper<E: FromServerFnError>(pub E);
impl<E: FromServerFnError> Display for ServerFnErrorWrapper<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
<E::Encoder as FormatType>::into_encoded_string(self.0.ser())
)
}
}
impl<E: FromServerFnError> FromStr for ServerFnErrorWrapper<E> {
type Err = base64::DecodeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bytes =
<E::Encoder as FormatType>::from_encoded_string(s).map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
});
let bytes = match bytes {
Ok(bytes) => bytes,
Err(err) => return Ok(Self(err)),
};
let err = E::de(bytes);
Ok(Self(err))
}
}
/// A trait for types that can be returned from a server function.
pub trait FromServerFnError: std::fmt::Debug + Sized + 'static {
/// The encoding strategy used to serialize and deserialize this error type. Must implement the [`Encodes`](server_fn::Encodes) trait for references to the error type.
type Encoder: Encodes<Self> + Decodes<Self>;
/// Converts a [`ServerFnErrorErr`] into the application-specific custom error type.
fn from_server_fn_error(value: ServerFnErrorErr) -> Self;
/// Serializes the custom error type to bytes, according to the encoding given by `Self::Encoding`.
fn ser(&self) -> Bytes {
Self::Encoder::encode(self).unwrap_or_else(|e| {
Self::Encoder::encode(&Self::from_server_fn_error(
ServerFnErrorErr::Serialization(e.to_string()),
))
.expect(
"error serializing should success at least with the \
Serialization error",
)
})
}
/// Deserializes the custom error type, according to the encoding given by `Self::Encoding`.
fn de(data: Bytes) -> Self {
Self::Encoder::decode(data).unwrap_or_else(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})
}
}
/// A helper trait for converting a [`ServerFnErrorErr`] into an application-specific custom error type that implements [`FromServerFnError`].
pub trait IntoAppError<E> {
/// Converts a [`ServerFnErrorErr`] into the application-specific custom error type.
fn into_app_error(self) -> E;
}
impl<E> IntoAppError<E> for ServerFnErrorErr
where
E: FromServerFnError,
{
fn into_app_error(self) -> E {
E::from_server_fn_error(self)
}
}
#[doc(hidden)]
#[rustversion::attr(
since(1.78),
diagnostic::on_unimplemented(
message = "{Self} is not a `Result` or aliased `Result`. Server \
functions must return a `Result` or aliased `Result`.",
label = "Must return a `Result` or aliased `Result`.",
note = "If you are trying to return an alias of `Result`, you must \
also implement `FromServerFnError` for the error type."
)
)]
/// A trait for extracting the error and ok types from a [`Result`]. This is used to allow alias types to be returned from server functions.
pub trait ServerFnMustReturnResult {
/// The error type of the [`Result`].
type Err;
/// The ok type of the [`Result`].
type Ok;
}
#[doc(hidden)]
impl<T, E> ServerFnMustReturnResult for Result<T, E> {
type Err = E;
type Ok = T;
}
#[test]
fn assert_from_server_fn_error_impl() {
fn assert_impl<T: FromServerFnError>() {}
assert_impl::<ServerFnError>();
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/server.rs | server_fn/src/server.rs | use crate::{
request::Req,
response::{Res, TryRes},
};
use std::future::Future;
/// A server defines a pair of request/response types and the logic to spawn
/// an async task.
///
/// This trait is implemented for any server backend for server functions including
/// `axum` and `actix-web`. It should almost never be necessary to implement it
/// yourself, unless you’re trying to use an alternative HTTP server.
pub trait Server<Error, InputStreamError = Error, OutputStreamError = Error> {
/// The type of the HTTP request when received by the server function on the server side.
type Request: Req<
Error,
InputStreamError,
OutputStreamError,
WebsocketResponse = Self::Response,
> + Send
+ 'static;
/// The type of the HTTP response returned by the server function on the server side.
type Response: Res + TryRes<Error> + Send + 'static;
/// Spawn an async task on the server.
fn spawn(
future: impl Future<Output = ()> + Send + 'static,
) -> Result<(), 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/codec/stream.rs | server_fn/src/codec/stream.rs | use super::{Encoding, FromReq, FromRes, IntoReq};
use crate::{
error::{FromServerFnError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, TryRes},
ContentType, IntoRes, ServerFnError,
};
use bytes::Bytes;
use futures::{Stream, StreamExt, TryStreamExt};
use http::Method;
use std::{fmt::Debug, pin::Pin};
/// An encoding that represents a stream of bytes.
///
/// A server function that uses this as its output encoding should return [`ByteStream`].
///
/// ## Browser Support for Streaming Input
///
/// Browser fetch requests do not currently support full request duplexing, which
/// means that that they do begin handling responses until the full request has been sent.
/// This means that if you use a streaming input encoding, the input stream needs to
/// end before the output will begin.
///
/// Streaming requests are only allowed over HTTP2 or HTTP3.
pub struct Streaming;
impl ContentType for Streaming {
const CONTENT_TYPE: &'static str = "application/octet-stream";
}
impl Encoding for Streaming {
const METHOD: Method = Method::POST;
}
impl<E, T, Request> IntoReq<Streaming, Request, E> for T
where
Request: ClientReq<E>,
T: Stream<Item = Bytes> + Send + 'static,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
Request::try_new_post_streaming(
path,
accepts,
Streaming::CONTENT_TYPE,
self,
)
}
}
impl<E, T, Request> FromReq<Streaming, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: From<ByteStream<E>> + 'static,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let data = req.try_into_stream()?;
let s = ByteStream::new(data.map_err(|e| E::de(e)));
Ok(s.into())
}
}
/// A stream of bytes.
///
/// A server function can return this type if its output encoding is [`Streaming`].
///
/// ## Browser Support for Streaming Input
///
/// Browser fetch requests do not currently support full request duplexing, which
/// means that that they do begin handling responses until the full request has been sent.
/// This means that if you use a streaming input encoding, the input stream needs to
/// end before the output will begin.
///
/// Streaming requests are only allowed over HTTP2 or HTTP3.
pub struct ByteStream<E = ServerFnError>(
Pin<Box<dyn Stream<Item = Result<Bytes, E>> + Send>>,
);
impl<E> ByteStream<E> {
/// Consumes the wrapper, returning a stream of bytes.
pub fn into_inner(self) -> impl Stream<Item = Result<Bytes, E>> + Send {
self.0
}
}
impl<E> Debug for ByteStream<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ByteStream").finish()
}
}
impl<E> ByteStream<E> {
/// Creates a new `ByteStream` from the given stream.
pub fn new<T>(
value: impl Stream<Item = Result<T, E>> + Send + 'static,
) -> Self
where
T: Into<Bytes>,
{
Self(Box::pin(value.map(|value| value.map(Into::into))))
}
}
impl<E, S, T> From<S> for ByteStream<E>
where
S: Stream<Item = T> + Send + 'static,
T: Into<Bytes>,
{
fn from(value: S) -> Self {
Self(Box::pin(value.map(|data| Ok(data.into()))))
}
}
impl<E, Response> IntoRes<Streaming, Response, E> for ByteStream<E>
where
Response: TryRes<E>,
E: FromServerFnError,
{
async fn into_res(self) -> Result<Response, E> {
Response::try_from_stream(
Streaming::CONTENT_TYPE,
self.into_inner().map_err(|e| e.ser()),
)
}
}
impl<E, Response> FromRes<Streaming, Response, E> for ByteStream<E>
where
Response: ClientRes<E> + Send,
E: FromServerFnError,
{
async fn from_res(res: Response) -> Result<Self, E> {
let stream = res.try_into_stream()?;
Ok(ByteStream::new(stream.map_err(|e| E::de(e))))
}
}
/// An encoding that represents a stream of text.
///
/// A server function that uses this as its output encoding should return [`TextStream`].
///
/// ## Browser Support for Streaming Input
///
/// Browser fetch requests do not currently support full request duplexing, which
/// means that that they do begin handling responses until the full request has been sent.
/// This means that if you use a streaming input encoding, the input stream needs to
/// end before the output will begin.
///
/// Streaming requests are only allowed over HTTP2 or HTTP3.
pub struct StreamingText;
impl ContentType for StreamingText {
const CONTENT_TYPE: &'static str = "text/plain";
}
impl Encoding for StreamingText {
const METHOD: Method = Method::POST;
}
/// A stream of text.
///
/// A server function can return this type if its output encoding is [`StreamingText`].
///
/// ## Browser Support for Streaming Input
///
/// Browser fetch requests do not currently support full request duplexing, which
/// means that that they do begin handling responses until the full request has been sent.
/// This means that if you use a streaming input encoding, the input stream needs to
/// end before the output will begin.
///
/// Streaming requests are only allowed over HTTP2 or HTTP3.
pub struct TextStream<E = ServerFnError>(
Pin<Box<dyn Stream<Item = Result<String, E>> + Send>>,
);
impl<E> Debug for TextStream<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("TextStream").finish()
}
}
impl<E> TextStream<E> {
/// Creates a new `TextStream` from the given stream.
pub fn new(
value: impl Stream<Item = Result<String, E>> + Send + 'static,
) -> Self {
Self(Box::pin(value.map(|value| value)))
}
}
impl<E> TextStream<E> {
/// Consumes the wrapper, returning a stream of text.
pub fn into_inner(self) -> impl Stream<Item = Result<String, E>> + Send {
self.0
}
}
impl<E, S, T> From<S> for TextStream<E>
where
S: Stream<Item = T> + Send + 'static,
T: Into<String>,
{
fn from(value: S) -> Self {
Self(Box::pin(value.map(|data| Ok(data.into()))))
}
}
impl<E, T, Request> IntoReq<StreamingText, Request, E> for T
where
Request: ClientReq<E>,
T: Into<TextStream<E>>,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = self.into();
Request::try_new_post_streaming(
path,
accepts,
Streaming::CONTENT_TYPE,
data.0.map(|chunk| chunk.unwrap_or_default().into()),
)
}
}
impl<E, T, Request> FromReq<StreamingText, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: From<TextStream<E>> + 'static,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let data = req.try_into_stream()?;
let s = TextStream::new(data.map(|chunk| match chunk {
Ok(bytes) => {
let de = String::from_utf8(bytes.to_vec()).map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
})?;
Ok(de)
}
Err(bytes) => Err(E::de(bytes)),
}));
Ok(s.into())
}
}
impl<E, Response> IntoRes<StreamingText, Response, E> for TextStream<E>
where
Response: TryRes<E>,
E: FromServerFnError,
{
async fn into_res(self) -> Result<Response, E> {
Response::try_from_stream(
Streaming::CONTENT_TYPE,
self.into_inner()
.map(|stream| stream.map(Into::into).map_err(|e| e.ser())),
)
}
}
impl<E, Response> FromRes<StreamingText, Response, E> for TextStream<E>
where
Response: ClientRes<E> + Send,
E: FromServerFnError,
{
async fn from_res(res: Response) -> Result<Self, E> {
let stream = res.try_into_stream()?;
Ok(TextStream(Box::pin(stream.map(|chunk| match chunk {
Ok(bytes) => {
let de = String::from_utf8(bytes.into()).map_err(|e| {
E::from_server_fn_error(ServerFnErrorErr::Deserialization(
e.to_string(),
))
})?;
Ok(de)
}
Err(bytes) => Err(E::de(bytes)),
}))))
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/msgpack.rs | server_fn/src/codec/msgpack.rs | use crate::{
codec::{Patch, Post, Put},
ContentType, Decodes, Encodes, Format, FormatType,
};
use bytes::Bytes;
use serde::{de::DeserializeOwned, Serialize};
/// Serializes and deserializes MessagePack with [`rmp_serde`].
pub struct MsgPackEncoding;
impl ContentType for MsgPackEncoding {
const CONTENT_TYPE: &'static str = "application/msgpack";
}
impl FormatType for MsgPackEncoding {
const FORMAT_TYPE: Format = Format::Binary;
}
impl<T> Encodes<T> for MsgPackEncoding
where
T: Serialize,
{
type Error = rmp_serde::encode::Error;
fn encode(value: &T) -> Result<Bytes, Self::Error> {
rmp_serde::to_vec(value).map(Bytes::from)
}
}
impl<T> Decodes<T> for MsgPackEncoding
where
T: DeserializeOwned,
{
type Error = rmp_serde::decode::Error;
fn decode(bytes: Bytes) -> Result<T, Self::Error> {
rmp_serde::from_slice(&bytes)
}
}
/// Pass arguments and receive responses as MessagePack in a `POST` request.
pub type MsgPack = Post<MsgPackEncoding>;
/// Pass arguments and receive responses as MessagePack in the body of a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PatchMsgPack = Patch<MsgPackEncoding>;
/// Pass arguments and receive responses as MessagePack in the body of a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PutMsgPack = Put<MsgPackEncoding>;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/put.rs | server_fn/src/codec/put.rs | use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, TryRes},
ContentType, Decodes, Encodes,
};
use std::marker::PhantomData;
/// A codec that encodes the data in the put body
pub struct Put<Codec>(PhantomData<Codec>);
impl<Codec: ContentType> ContentType for Put<Codec> {
const CONTENT_TYPE: &'static str = Codec::CONTENT_TYPE;
}
impl<Codec: ContentType> Encoding for Put<Codec> {
const METHOD: http::Method = http::Method::PUT;
}
impl<E, T, Encoding, Request> IntoReq<Put<Encoding>, Request, E> for T
where
Request: ClientReq<E>,
Encoding: Encodes<T>,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = Encoding::encode(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_put_bytes(path, Encoding::CONTENT_TYPE, accepts, data)
}
}
impl<E, T, Request, Encoding> FromReq<Put<Encoding>, Request, E> for T
where
Request: Req<E> + Send + 'static,
Encoding: Decodes<T>,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let data = req.try_into_bytes().await?;
let s = Encoding::decode(data).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})?;
Ok(s)
}
}
impl<E, Response, Encoding, T> IntoRes<Put<Encoding>, Response, E> for T
where
Response: TryRes<E>,
Encoding: Encodes<T>,
E: FromServerFnError + Send,
T: Send,
{
async fn into_res(self) -> Result<Response, E> {
let data = Encoding::encode(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Response::try_from_bytes(Encoding::CONTENT_TYPE, data)
}
}
impl<E, Encoding, Response, T> FromRes<Put<Encoding>, Response, E> for T
where
Response: ClientRes<E> + Send,
Encoding: Decodes<T>,
E: FromServerFnError,
{
async fn from_res(res: Response) -> Result<Self, E> {
let data = res.try_into_bytes().await?;
let s = Encoding::decode(data).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})?;
Ok(s)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/multipart.rs | server_fn/src/codec/multipart.rs | use super::{Encoding, FromReq};
use crate::{
error::{FromServerFnError, ServerFnErrorWrapper},
request::{browser::BrowserFormData, ClientReq, Req},
ContentType, IntoReq,
};
use futures::StreamExt;
use http::Method;
use multer::Multipart;
use web_sys::FormData;
/// Encodes multipart form data.
///
/// You should primarily use this if you are trying to handle file uploads.
pub struct MultipartFormData;
impl ContentType for MultipartFormData {
const CONTENT_TYPE: &'static str = "multipart/form-data";
}
impl Encoding for MultipartFormData {
const METHOD: Method = Method::POST;
}
/// Describes whether the multipart data is on the client side or the server side.
#[derive(Debug)]
pub enum MultipartData {
/// `FormData` from the browser.
Client(BrowserFormData),
/// Generic multipart form using [`multer`]. This implements [`Stream`](futures::Stream).
Server(multer::Multipart<'static>),
}
impl MultipartData {
/// Extracts the inner data to handle as a stream.
///
/// On the server side, this always returns `Some(_)`. On the client side, always returns `None`.
pub fn into_inner(self) -> Option<Multipart<'static>> {
match self {
MultipartData::Client(_) => None,
MultipartData::Server(data) => Some(data),
}
}
/// Extracts the inner form data on the client side.
///
/// On the server side, this always returns `None`. On the client side, always returns `Some(_)`.
pub fn into_client_data(self) -> Option<BrowserFormData> {
match self {
MultipartData::Client(data) => Some(data),
MultipartData::Server(_) => None,
}
}
}
impl From<FormData> for MultipartData {
fn from(value: FormData) -> Self {
MultipartData::Client(value.into())
}
}
impl<E: FromServerFnError, T, Request> IntoReq<MultipartFormData, Request, E>
for T
where
Request: ClientReq<E, FormData = BrowserFormData>,
T: Into<MultipartData>,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let multi = self.into();
Request::try_new_post_multipart(
path,
accepts,
multi.into_client_data().unwrap(),
)
}
}
impl<E, T, Request> FromReq<MultipartFormData, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: From<MultipartData>,
E: FromServerFnError + Send + Sync,
{
async fn from_req(req: Request) -> Result<Self, E> {
let boundary = req
.to_content_type()
.and_then(|ct| multer::parse_boundary(ct).ok())
.expect("couldn't parse boundary");
let stream = req.try_into_stream()?;
let data = multer::Multipart::new(
stream.map(|data| data.map_err(|e| ServerFnErrorWrapper(E::de(e)))),
boundary,
);
Ok(MultipartData::Server(data).into())
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/json.rs | server_fn/src/codec/json.rs | use super::{Patch, Post, Put};
use crate::{ContentType, Decodes, Encodes, Format, FormatType};
use bytes::Bytes;
use serde::{de::DeserializeOwned, Serialize};
/// Serializes and deserializes JSON with [`serde_json`].
pub struct JsonEncoding;
impl ContentType for JsonEncoding {
const CONTENT_TYPE: &'static str = "application/json";
}
impl FormatType for JsonEncoding {
const FORMAT_TYPE: Format = Format::Text;
}
impl<T> Encodes<T> for JsonEncoding
where
T: Serialize,
{
type Error = serde_json::Error;
fn encode(output: &T) -> Result<Bytes, Self::Error> {
serde_json::to_vec(output).map(Bytes::from)
}
}
impl<T> Decodes<T> for JsonEncoding
where
T: DeserializeOwned,
{
type Error = serde_json::Error;
fn decode(bytes: Bytes) -> Result<T, Self::Error> {
serde_json::from_slice(&bytes)
}
}
/// Pass arguments and receive responses as JSON in the body of a `POST` request.
pub type Json = Post<JsonEncoding>;
/// Pass arguments and receive responses as JSON in the body of a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PatchJson = Patch<JsonEncoding>;
/// Pass arguments and receive responses as JSON in the body of a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PutJson = Put<JsonEncoding>;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/url.rs | server_fn/src/codec/url.rs | use super::{Encoding, FromReq, IntoReq};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
ContentType,
};
use http::Method;
use serde::{de::DeserializeOwned, Serialize};
/// Pass arguments as a URL-encoded query string of a `GET` request.
pub struct GetUrl;
/// Pass arguments as the URL-encoded body of a `POST` request.
pub struct PostUrl;
/// Pass arguments as the URL-encoded query string of a `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.
pub struct DeleteUrl;
/// Pass arguments as the URL-encoded body of a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub struct PatchUrl;
/// Pass arguments as the URL-encoded body of a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub struct PutUrl;
impl ContentType for GetUrl {
const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
}
impl Encoding for GetUrl {
const METHOD: Method = Method::GET;
}
impl<E, T, Request> IntoReq<GetUrl, Request, E> for T
where
Request: ClientReq<E>,
T: Serialize + Send,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = serde_qs::to_string(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_get(path, GetUrl::CONTENT_TYPE, accepts, &data)
}
}
impl<E, T, Request> FromReq<GetUrl, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: DeserializeOwned,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let string_data = req.as_query().unwrap_or_default();
let args = serde_qs::Config::new(5, false)
.deserialize_str::<Self>(string_data)
.map_err(|e| {
ServerFnErrorErr::Args(e.to_string()).into_app_error()
})?;
Ok(args)
}
}
impl ContentType for PostUrl {
const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
}
impl Encoding for PostUrl {
const METHOD: Method = Method::POST;
}
impl<E, T, Request> IntoReq<PostUrl, Request, E> for T
where
Request: ClientReq<E>,
T: Serialize + Send,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let qs = serde_qs::to_string(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_post(path, PostUrl::CONTENT_TYPE, accepts, qs)
}
}
impl<E, T, Request> FromReq<PostUrl, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: DeserializeOwned,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let string_data = req.try_into_string().await?;
let args = serde_qs::Config::new(5, false)
.deserialize_str::<Self>(&string_data)
.map_err(|e| {
ServerFnErrorErr::Args(e.to_string()).into_app_error()
})?;
Ok(args)
}
}
impl ContentType for DeleteUrl {
const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
}
impl Encoding for DeleteUrl {
const METHOD: Method = Method::DELETE;
}
impl<E, T, Request> IntoReq<DeleteUrl, Request, E> for T
where
Request: ClientReq<E>,
T: Serialize + Send,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = serde_qs::to_string(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_delete(path, DeleteUrl::CONTENT_TYPE, accepts, &data)
}
}
impl<E, T, Request> FromReq<DeleteUrl, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: DeserializeOwned,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let string_data = req.as_query().unwrap_or_default();
let args = serde_qs::Config::new(5, false)
.deserialize_str::<Self>(string_data)
.map_err(|e| {
ServerFnErrorErr::Args(e.to_string()).into_app_error()
})?;
Ok(args)
}
}
impl ContentType for PatchUrl {
const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
}
impl Encoding for PatchUrl {
const METHOD: Method = Method::PATCH;
}
impl<E, T, Request> IntoReq<PatchUrl, Request, E> for T
where
Request: ClientReq<E>,
T: Serialize + Send,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = serde_qs::to_string(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_patch(path, PatchUrl::CONTENT_TYPE, accepts, data)
}
}
impl<E, T, Request> FromReq<PatchUrl, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: DeserializeOwned,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let string_data = req.try_into_string().await?;
let args = serde_qs::Config::new(5, false)
.deserialize_str::<Self>(&string_data)
.map_err(|e| {
ServerFnErrorErr::Args(e.to_string()).into_app_error()
})?;
Ok(args)
}
}
impl ContentType for PutUrl {
const CONTENT_TYPE: &'static str = "application/x-www-form-urlencoded";
}
impl Encoding for PutUrl {
const METHOD: Method = Method::PUT;
}
impl<E, T, Request> IntoReq<PutUrl, Request, E> for T
where
Request: ClientReq<E>,
T: Serialize + Send,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = serde_qs::to_string(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_put(path, PutUrl::CONTENT_TYPE, accepts, data)
}
}
impl<E, T, Request> FromReq<PutUrl, Request, E> for T
where
Request: Req<E> + Send + 'static,
T: DeserializeOwned,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let string_data = req.try_into_string().await?;
let args = serde_qs::Config::new(5, false)
.deserialize_str::<Self>(&string_data)
.map_err(|e| {
ServerFnErrorErr::Args(e.to_string()).into_app_error()
})?;
Ok(args)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/cbor.rs | server_fn/src/codec/cbor.rs | use super::{Patch, Post, Put};
use crate::{ContentType, Decodes, Encodes, Format, FormatType};
use bytes::Bytes;
use serde::{de::DeserializeOwned, Serialize};
/// Serializes and deserializes CBOR with [`ciborium`].
pub struct CborEncoding;
impl ContentType for CborEncoding {
const CONTENT_TYPE: &'static str = "application/cbor";
}
impl FormatType for CborEncoding {
const FORMAT_TYPE: Format = Format::Binary;
}
impl<T> Encodes<T> for CborEncoding
where
T: Serialize,
{
type Error = ciborium::ser::Error<std::io::Error>;
fn encode(value: &T) -> Result<Bytes, Self::Error> {
let mut buffer: Vec<u8> = Vec::new();
ciborium::ser::into_writer(value, &mut buffer)?;
Ok(Bytes::from(buffer))
}
}
impl<T> Decodes<T> for CborEncoding
where
T: DeserializeOwned,
{
type Error = ciborium::de::Error<std::io::Error>;
fn decode(bytes: Bytes) -> Result<T, Self::Error> {
ciborium::de::from_reader(bytes.as_ref())
}
}
/// Pass arguments and receive responses using `cbor` in a `POST` request.
pub type Cbor = Post<CborEncoding>;
/// Pass arguments and receive responses using `cbor` in the body of a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PatchCbor = Patch<CborEncoding>;
/// Pass arguments and receive responses using `cbor` in the body of a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PutCbor = Put<CborEncoding>;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/serde_lite.rs | server_fn/src/codec/serde_lite.rs | use crate::{
codec::{Patch, Post, Put},
error::ServerFnErrorErr,
ContentType, Decodes, Encodes, Format, FormatType,
};
use bytes::Bytes;
use serde_lite::{Deserialize, Serialize};
/// Pass arguments and receive responses as JSON in the body of a `POST` request.
pub struct SerdeLiteEncoding;
impl ContentType for SerdeLiteEncoding {
const CONTENT_TYPE: &'static str = "application/json";
}
impl FormatType for SerdeLiteEncoding {
const FORMAT_TYPE: Format = Format::Text;
}
impl<T> Encodes<T> for SerdeLiteEncoding
where
T: Serialize,
{
type Error = ServerFnErrorErr;
fn encode(value: &T) -> Result<Bytes, Self::Error> {
serde_json::to_vec(
&value
.serialize()
.map_err(|e| ServerFnErrorErr::Serialization(e.to_string()))?,
)
.map_err(|e| ServerFnErrorErr::Serialization(e.to_string()))
.map(Bytes::from)
}
}
impl<T> Decodes<T> for SerdeLiteEncoding
where
T: Deserialize,
{
type Error = ServerFnErrorErr;
fn decode(bytes: Bytes) -> Result<T, Self::Error> {
T::deserialize(
&serde_json::from_slice(&bytes).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string())
})?,
)
.map_err(|e| ServerFnErrorErr::Deserialization(e.to_string()))
}
}
/// Pass arguments and receive responses as JSON in the body of a `POST` request.
pub type SerdeLite = Post<SerdeLiteEncoding>;
/// Pass arguments and receive responses as JSON in the body of a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PatchSerdeLite = Patch<SerdeLiteEncoding>;
/// Pass arguments and receive responses as JSON in the body of a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PutSerdeLite = Put<SerdeLiteEncoding>;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/mod.rs | server_fn/src/codec/mod.rs | //! The serialization/deserialization process for server functions consists of a series of steps,
//! each of which is represented by a different trait:
//! 1. [`IntoReq`]: The client serializes the [`ServerFn`] argument type into an HTTP request.
//! 2. The [`Client`] sends the request to the server.
//! 3. [`FromReq`]: The server deserializes the HTTP request back into the [`ServerFn`] type.
//! 4. The server calls [`ServerFn::run_body`] on the data.
//! 5. [`IntoRes`]: The server serializes the [`ServerFn::Output`] type into an HTTP response.
//! 6. The server integration applies any middleware from [`ServerFn::middlewares`] and responds to the request.
//! 7. [`FromRes`]: The client deserializes the response back into the [`ServerFn::Output`] type.
//!
//! Rather than a limited number of encodings, this crate allows you to define server functions that
//! mix and match the input encoding and output encoding. To define a new encoding, you simply implement
//! an input combination ([`IntoReq`] and [`FromReq`]) and/or an output encoding ([`IntoRes`] and [`FromRes`]).
//! This genuinely is an and/or: while some encodings can be used for both input and output (`Json`, `Cbor`, `Rkyv`),
//! others can only be used for input (`GetUrl`, `MultipartData`).
#[cfg(feature = "cbor")]
mod cbor;
#[cfg(feature = "cbor")]
pub use cbor::*;
mod json;
pub use json::*;
#[cfg(feature = "serde-lite")]
mod serde_lite;
#[cfg(feature = "serde-lite")]
pub use serde_lite::*;
#[cfg(feature = "rkyv")]
mod rkyv;
#[cfg(feature = "rkyv")]
pub use rkyv::*;
mod url;
pub use url::*;
#[cfg(feature = "multipart")]
mod multipart;
#[cfg(feature = "multipart")]
pub use multipart::*;
#[cfg(feature = "msgpack")]
mod msgpack;
#[cfg(feature = "msgpack")]
pub use msgpack::*;
#[cfg(feature = "postcard")]
mod postcard;
#[cfg(feature = "postcard")]
pub use postcard::*;
#[cfg(feature = "bitcode")]
mod bitcode;
#[cfg(feature = "bitcode")]
pub use bitcode::*;
mod patch;
pub use patch::*;
mod post;
pub use post::*;
mod put;
pub use put::*;
mod stream;
use crate::ContentType;
use futures::Future;
use http::Method;
pub use stream::*;
/// Serializes a data type into an HTTP request, on the client.
///
/// Implementations use the methods of the [`ClientReq`](crate::request::ClientReq) trait to
/// convert data into a request body. They are often quite short, usually consisting
/// of just two steps:
/// 1. Serializing the data into some [`String`], [`Bytes`](bytes::Bytes), or [`Stream`](futures::Stream).
/// 2. Creating a request with a body of that type.
///
/// For example, here’s the implementation for [`Json`].
///
/// ```rust,ignore
/// impl<E, T, Request> IntoReq<Json, Request, E> for T
/// where
/// Request: ClientReq<E>,
/// T: Serialize + Send,
/// {
/// fn into_req(
/// self,
/// path: &str,
/// accepts: &str,
/// ) -> Result<Request, E> {
/// // try to serialize the data
/// let data = serde_json::to_string(&self)
/// .map_err(|e| ServerFnErrorErr::Serialization(e.to_string()).into_app_error())?;
/// // and use it as the body of a POST request
/// Request::try_new_post(path, accepts, Json::CONTENT_TYPE, data)
/// }
/// }
/// ```
pub trait IntoReq<Encoding, Request, E> {
/// Attempts to serialize the arguments into an HTTP request.
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E>;
}
/// Deserializes an HTTP request into the data type, on the server.
///
/// Implementations use the methods of the [`Req`](crate::Req) trait to access whatever is
/// needed from the request. They are often quite short, usually consisting
/// of just two steps:
/// 1. Extracting the request body into some [`String`], [`Bytes`](bytes::Bytes), or [`Stream`](futures::Stream).
/// 2. Deserializing that data into the data type.
///
/// For example, here’s the implementation for [`Json`].
///
/// ```rust,ignore
/// impl<E, T, Request> FromReq<Json, Request, E> for T
/// where
/// // require the Request implement `Req`
/// Request: Req<E> + Send + 'static,
/// // require that the type can be deserialized with `serde`
/// T: DeserializeOwned,
/// E: FromServerFnError,
/// {
/// async fn from_req(
/// req: Request,
/// ) -> Result<Self, E> {
/// // try to convert the body of the request into a `String`
/// let string_data = req.try_into_string().await?;
/// // deserialize the data
/// serde_json::from_str(&string_data)
/// .map_err(|e| ServerFnErrorErr::Args(e.to_string()).into_app_error())
/// }
/// }
/// ```
pub trait FromReq<Encoding, Request, E>
where
Self: Sized,
{
/// Attempts to deserialize the arguments from a request.
fn from_req(req: Request) -> impl Future<Output = Result<Self, E>> + Send;
}
/// Serializes the data type into an HTTP response.
///
/// Implementations use the methods of the [`Res`](crate::Res) trait to create a
/// response. They are often quite short, usually consisting
/// of just two steps:
/// 1. Serializing the data type to a [`String`], [`Bytes`](bytes::Bytes), or a [`Stream`](futures::Stream).
/// 2. Creating a response with that serialized value as its body.
///
/// For example, here’s the implementation for [`Json`].
///
/// ```rust,ignore
/// impl<E, T, Response> IntoRes<Json, Response, E> for T
/// where
/// Response: Res<E>,
/// T: Serialize + Send,
/// E: FromServerFnError,
/// {
/// async fn into_res(self) -> Result<Response, E> {
/// // try to serialize the data
/// let data = serde_json::to_string(&self)
/// .map_err(|e| ServerFnErrorErr::Serialization(e.to_string()).into())?;
/// // and use it as the body of a response
/// Response::try_from_string(Json::CONTENT_TYPE, data)
/// }
/// }
/// ```
pub trait IntoRes<Encoding, Response, E> {
/// Attempts to serialize the output into an HTTP response.
fn into_res(self) -> impl Future<Output = Result<Response, E>> + Send;
}
/// Deserializes the data type from an HTTP response.
///
/// Implementations use the methods of the [`ClientRes`](crate::ClientRes) trait to extract
/// data from a response. They are often quite short, usually consisting
/// of just two steps:
/// 1. Extracting a [`String`], [`Bytes`](bytes::Bytes), or a [`Stream`](futures::Stream)
/// from the response body.
/// 2. Deserializing the data type from that value.
///
/// For example, here’s the implementation for [`Json`].
///
/// ```rust,ignore
/// impl<E, T, Response> FromRes<Json, Response, E> for T
/// where
/// Response: ClientRes<E> + Send,
/// T: DeserializeOwned + Send,
/// E: FromServerFnError,
/// {
/// async fn from_res(
/// res: Response,
/// ) -> Result<Self, E> {
/// // extracts the request body
/// let data = res.try_into_string().await?;
/// // and tries to deserialize it as JSON
/// serde_json::from_str(&data)
/// .map_err(|e| ServerFnErrorErr::Deserialization(e.to_string()).into_app_error())
/// }
/// }
/// ```
pub trait FromRes<Encoding, Response, E>
where
Self: Sized,
{
/// Attempts to deserialize the outputs from a response.
fn from_res(res: Response) -> impl Future<Output = Result<Self, E>> + Send;
}
/// Defines a particular encoding format, which can be used for serializing or deserializing data.
pub trait Encoding: ContentType {
/// The HTTP method used for requests.
///
/// This should be `POST` in most cases.
const METHOD: Method;
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/post.rs | server_fn/src/codec/post.rs | use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, TryRes},
ContentType, Decodes, Encodes,
};
use std::marker::PhantomData;
/// A codec that encodes the data in the post body
pub struct Post<Codec>(PhantomData<Codec>);
impl<Codec: ContentType> ContentType for Post<Codec> {
const CONTENT_TYPE: &'static str = Codec::CONTENT_TYPE;
}
impl<Codec: ContentType> Encoding for Post<Codec> {
const METHOD: http::Method = http::Method::POST;
}
impl<E, T, Encoding, Request> IntoReq<Post<Encoding>, Request, E> for T
where
Request: ClientReq<E>,
Encoding: Encodes<T>,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = Encoding::encode(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_post_bytes(path, Encoding::CONTENT_TYPE, accepts, data)
}
}
impl<E, T, Request, Encoding> FromReq<Post<Encoding>, Request, E> for T
where
Request: Req<E> + Send + 'static,
Encoding: Decodes<T>,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let data = req.try_into_bytes().await?;
let s = Encoding::decode(data).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})?;
Ok(s)
}
}
impl<E, Response, Encoding, T> IntoRes<Post<Encoding>, Response, E> for T
where
Response: TryRes<E>,
Encoding: Encodes<T>,
E: FromServerFnError + Send,
T: Send,
{
async fn into_res(self) -> Result<Response, E> {
let data = Encoding::encode(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Response::try_from_bytes(Encoding::CONTENT_TYPE, data)
}
}
impl<E, Encoding, Response, T> FromRes<Post<Encoding>, Response, E> for T
where
Response: ClientRes<E> + Send,
Encoding: Decodes<T>,
E: FromServerFnError,
{
async fn from_res(res: Response) -> Result<Self, E> {
let data = res.try_into_bytes().await?;
let s = Encoding::decode(data).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})?;
Ok(s)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/postcard.rs | server_fn/src/codec/postcard.rs | use crate::{
codec::{Patch, Post, Put},
ContentType, Decodes, Encodes, Format, FormatType,
};
use bytes::Bytes;
use serde::{de::DeserializeOwned, Serialize};
/// A codec for Postcard.
pub struct PostcardEncoding;
impl ContentType for PostcardEncoding {
const CONTENT_TYPE: &'static str = "application/x-postcard";
}
impl FormatType for PostcardEncoding {
const FORMAT_TYPE: Format = Format::Binary;
}
impl<T> Encodes<T> for PostcardEncoding
where
T: Serialize,
{
type Error = postcard::Error;
fn encode(value: &T) -> Result<Bytes, Self::Error> {
postcard::to_allocvec(value).map(Bytes::from)
}
}
impl<T> Decodes<T> for PostcardEncoding
where
T: DeserializeOwned,
{
type Error = postcard::Error;
fn decode(bytes: Bytes) -> Result<T, Self::Error> {
postcard::from_bytes(&bytes)
}
}
/// Pass arguments and receive responses with postcard in a `POST` request.
pub type Postcard = Post<PostcardEncoding>;
/// Pass arguments and receive responses with postcard in a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PatchPostcard = Patch<PostcardEncoding>;
/// Pass arguments and receive responses with postcard in a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PutPostcard = Put<PostcardEncoding>;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/rkyv.rs | server_fn/src/codec/rkyv.rs | use crate::{
codec::{Patch, Post, Put},
ContentType, Decodes, Encodes, Format, FormatType,
};
use bytes::Bytes;
use rkyv::{
api::high::{HighDeserializer, HighSerializer, HighValidator},
bytecheck::CheckBytes,
rancor,
ser::allocator::ArenaHandle,
util::AlignedVec,
Archive, Deserialize, Serialize,
};
type RkyvSerializer<'a> =
HighSerializer<AlignedVec, ArenaHandle<'a>, rancor::Error>;
type RkyvDeserializer = HighDeserializer<rancor::Error>;
type RkyvValidator<'a> = HighValidator<'a, rancor::Error>;
/// Pass arguments and receive responses using `rkyv` in a `POST` request.
pub struct RkyvEncoding;
impl ContentType for RkyvEncoding {
const CONTENT_TYPE: &'static str = "application/rkyv";
}
impl FormatType for RkyvEncoding {
const FORMAT_TYPE: Format = Format::Binary;
}
impl<T> Encodes<T> for RkyvEncoding
where
T: Archive + for<'a> Serialize<RkyvSerializer<'a>>,
T::Archived: Deserialize<T, RkyvDeserializer>
+ for<'a> CheckBytes<RkyvValidator<'a>>,
{
type Error = rancor::Error;
fn encode(value: &T) -> Result<Bytes, Self::Error> {
let encoded = rkyv::to_bytes::<rancor::Error>(value)?;
Ok(Bytes::copy_from_slice(encoded.as_ref()))
}
}
impl<T> Decodes<T> for RkyvEncoding
where
T: Archive + for<'a> Serialize<RkyvSerializer<'a>>,
T::Archived: Deserialize<T, RkyvDeserializer>
+ for<'a> CheckBytes<RkyvValidator<'a>>,
{
type Error = rancor::Error;
fn decode(bytes: Bytes) -> Result<T, Self::Error> {
let mut aligned = AlignedVec::<1024>::new();
aligned.extend_from_slice(bytes.as_ref());
rkyv::from_bytes::<T, rancor::Error>(aligned.as_ref())
}
}
/// Pass arguments and receive responses as `rkyv` in a `POST` request.
pub type Rkyv = Post<RkyvEncoding>;
/// Pass arguments and receive responses as `rkyv` in a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PatchRkyv = Patch<RkyvEncoding>;
/// Pass arguments and receive responses as `rkyv` in a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PutRkyv = Put<RkyvEncoding>;
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/patch.rs | server_fn/src/codec/patch.rs | use super::{Encoding, FromReq, FromRes, IntoReq, IntoRes};
use crate::{
error::{FromServerFnError, IntoAppError, ServerFnErrorErr},
request::{ClientReq, Req},
response::{ClientRes, TryRes},
ContentType, Decodes, Encodes,
};
use std::marker::PhantomData;
/// A codec that encodes the data in the patch body
pub struct Patch<Codec>(PhantomData<Codec>);
impl<Codec: ContentType> ContentType for Patch<Codec> {
const CONTENT_TYPE: &'static str = Codec::CONTENT_TYPE;
}
impl<Codec: ContentType> Encoding for Patch<Codec> {
const METHOD: http::Method = http::Method::PATCH;
}
impl<E, T, Encoding, Request> IntoReq<Patch<Encoding>, Request, E> for T
where
Request: ClientReq<E>,
Encoding: Encodes<T>,
E: FromServerFnError,
{
fn into_req(self, path: &str, accepts: &str) -> Result<Request, E> {
let data = Encoding::encode(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Request::try_new_patch_bytes(
path,
Encoding::CONTENT_TYPE,
accepts,
data,
)
}
}
impl<E, T, Request, Encoding> FromReq<Patch<Encoding>, Request, E> for T
where
Request: Req<E> + Send + 'static,
Encoding: Decodes<T>,
E: FromServerFnError,
{
async fn from_req(req: Request) -> Result<Self, E> {
let data = req.try_into_bytes().await?;
let s = Encoding::decode(data).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})?;
Ok(s)
}
}
impl<E, Response, Encoding, T> IntoRes<Patch<Encoding>, Response, E> for T
where
Response: TryRes<E>,
Encoding: Encodes<T>,
E: FromServerFnError + Send,
T: Send,
{
async fn into_res(self) -> Result<Response, E> {
let data = Encoding::encode(&self).map_err(|e| {
ServerFnErrorErr::Serialization(e.to_string()).into_app_error()
})?;
Response::try_from_bytes(Encoding::CONTENT_TYPE, data)
}
}
impl<E, Encoding, Response, T> FromRes<Patch<Encoding>, Response, E> for T
where
Response: ClientRes<E> + Send,
Encoding: Decodes<T>,
E: FromServerFnError,
{
async fn from_res(res: Response) -> Result<Self, E> {
let data = res.try_into_bytes().await?;
let s = Encoding::decode(data).map_err(|e| {
ServerFnErrorErr::Deserialization(e.to_string()).into_app_error()
})?;
Ok(s)
}
}
| rust | MIT | dd507168fa47b5eead64339431b0bd654bd1c951 | 2026-01-04T15:41:20.302544Z | false |
leptos-rs/leptos | https://github.com/leptos-rs/leptos/blob/dd507168fa47b5eead64339431b0bd654bd1c951/server_fn/src/codec/bitcode.rs | server_fn/src/codec/bitcode.rs | use super::{Patch, Post, Put};
use crate::{ContentType, Decodes, Encodes, Format, FormatType};
use bytes::Bytes;
/// Serializes and deserializes with [`bitcode`].
pub struct BitcodeEncoding;
impl ContentType for BitcodeEncoding {
const CONTENT_TYPE: &'static str = "application/bitcode";
}
impl FormatType for BitcodeEncoding {
const FORMAT_TYPE: Format = Format::Binary;
}
impl<T> Encodes<T> for BitcodeEncoding
where
T: bitcode::Encode,
{
type Error = std::convert::Infallible;
fn encode(value: &T) -> Result<Bytes, Self::Error> {
Ok(Bytes::from(bitcode::encode(value)))
}
}
impl<T> Decodes<T> for BitcodeEncoding
where
T: bitcode::DecodeOwned,
{
type Error = bitcode::Error;
fn decode(bytes: Bytes) -> Result<T, Self::Error> {
bitcode::decode(bytes.as_ref())
}
}
/// Pass arguments and receive responses using `bitcode` in a `POST` request.
pub type Bitcode = Post<BitcodeEncoding>;
/// Pass arguments and receive responses using `bitcode` in the body of a `PATCH` request.
/// **Note**: Browser support for `PATCH` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PatchBitcode = Patch<BitcodeEncoding>;
/// Pass arguments and receive responses using `bitcode` in the body of a `PUT` request.
/// **Note**: Browser support for `PUT` requests without JS/WASM may be poor.
/// Consider using a `POST` request if functionality without JS/WASM is required.
pub type PutBitcode = Put<BitcodeEncoding>;
| 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.